1 //===- ScriptParser.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a recursive-descendent parser for linker scripts.
10 // Parsed results are stored to Config and Script global objects.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ScriptParser.h"
15 #include "Config.h"
16 #include "Driver.h"
17 #include "InputSection.h"
18 #include "LinkerScript.h"
19 #include "OutputSections.h"
20 #include "ScriptLexer.h"
21 #include "Symbols.h"
22 #include "Target.h"
23 #include "lld/Common/Memory.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/BinaryFormat/ELF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/ScopedPrinter.h"
35 #include "llvm/Support/TimeProfiler.h"
36 #include <cassert>
37 #include <limits>
38 #include <vector>
39 
40 using namespace llvm;
41 using namespace llvm::ELF;
42 using namespace llvm::support::endian;
43 using namespace lld;
44 using namespace lld::elf;
45 
46 namespace {
47 class ScriptParser final : ScriptLexer {
48 public:
49   ScriptParser(MemoryBufferRef mb) : ScriptLexer(mb) {
50     // Initialize IsUnderSysroot
51     if (config->sysroot == "")
52       return;
53     StringRef path = mb.getBufferIdentifier();
54     for (; !path.empty(); path = sys::path::parent_path(path)) {
55       if (!sys::fs::equivalent(config->sysroot, path))
56         continue;
57       isUnderSysroot = true;
58       return;
59     }
60   }
61 
62   void readLinkerScript();
63   void readVersionScript();
64   void readDynamicList();
65   void readDefsym(StringRef name);
66 
67 private:
68   void addFile(StringRef path);
69 
70   void readAsNeeded();
71   void readEntry();
72   void readExtern();
73   void readGroup();
74   void readInclude();
75   void readInput();
76   void readMemory();
77   void readOutput();
78   void readOutputArch();
79   void readOutputFormat();
80   void readOverwriteSections();
81   void readPhdrs();
82   void readRegionAlias();
83   void readSearchDir();
84   void readSections();
85   void readTarget();
86   void readVersion();
87   void readVersionScriptCommand();
88 
89   SymbolAssignment *readSymbolAssignment(StringRef name);
90   ByteCommand *readByteCommand(StringRef tok);
91   std::array<uint8_t, 4> readFill();
92   bool readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2);
93   void readSectionAddressType(OutputSection *cmd);
94   OutputSection *readOverlaySectionDescription();
95   OutputSection *readOutputSectionDescription(StringRef outSec);
96   std::vector<BaseCommand *> readOverlay();
97   std::vector<StringRef> readOutputSectionPhdrs();
98   std::pair<uint64_t, uint64_t> readInputSectionFlags();
99   InputSectionDescription *readInputSectionDescription(StringRef tok);
100   StringMatcher readFilePatterns();
101   std::vector<SectionPattern> readInputSectionsList();
102   InputSectionDescription *readInputSectionRules(StringRef filePattern,
103                                                  uint64_t withFlags,
104                                                  uint64_t withoutFlags);
105   unsigned readPhdrType();
106   SortSectionPolicy peekSortKind();
107   SortSectionPolicy readSortKind();
108   SymbolAssignment *readProvideHidden(bool provide, bool hidden);
109   SymbolAssignment *readAssignment(StringRef tok);
110   void readSort();
111   Expr readAssert();
112   Expr readConstant();
113   Expr getPageSize();
114 
115   Expr readMemoryAssignment(StringRef, StringRef, StringRef);
116   std::pair<uint32_t, uint32_t> readMemoryAttributes();
117 
118   Expr combine(StringRef op, Expr l, Expr r);
119   Expr readExpr();
120   Expr readExpr1(Expr lhs, int minPrec);
121   StringRef readParenLiteral();
122   Expr readPrimary();
123   Expr readTernary(Expr cond);
124   Expr readParenExpr();
125 
126   // For parsing version script.
127   std::vector<SymbolVersion> readVersionExtern();
128   void readAnonymousDeclaration();
129   void readVersionDeclaration(StringRef verStr);
130 
131   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
132   readSymbols();
133 
134   // True if a script being read is in a subdirectory specified by -sysroot.
135   bool isUnderSysroot = false;
136 
137   // A set to detect an INCLUDE() cycle.
138   StringSet<> seen;
139 };
140 } // namespace
141 
142 static StringRef unquote(StringRef s) {
143   if (s.startswith("\""))
144     return s.substr(1, s.size() - 2);
145   return s;
146 }
147 
148 // Some operations only support one non absolute value. Move the
149 // absolute one to the right hand side for convenience.
150 static void moveAbsRight(ExprValue &a, ExprValue &b) {
151   if (a.sec == nullptr || (a.forceAbsolute && !b.isAbsolute()))
152     std::swap(a, b);
153   if (!b.isAbsolute())
154     error(a.loc + ": at least one side of the expression must be absolute");
155 }
156 
157 static ExprValue add(ExprValue a, ExprValue b) {
158   moveAbsRight(a, b);
159   return {a.sec, a.forceAbsolute, a.getSectionOffset() + b.getValue(), a.loc};
160 }
161 
162 static ExprValue sub(ExprValue a, ExprValue b) {
163   // The distance between two symbols in sections is absolute.
164   if (!a.isAbsolute() && !b.isAbsolute())
165     return a.getValue() - b.getValue();
166   return {a.sec, false, a.getSectionOffset() - b.getValue(), a.loc};
167 }
168 
169 static ExprValue bitAnd(ExprValue a, ExprValue b) {
170   moveAbsRight(a, b);
171   return {a.sec, a.forceAbsolute,
172           (a.getValue() & b.getValue()) - a.getSecAddr(), a.loc};
173 }
174 
175 static ExprValue bitOr(ExprValue a, ExprValue b) {
176   moveAbsRight(a, b);
177   return {a.sec, a.forceAbsolute,
178           (a.getValue() | b.getValue()) - a.getSecAddr(), a.loc};
179 }
180 
181 void ScriptParser::readDynamicList() {
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 == "ENTRY") {
238       readEntry();
239     } else if (tok == "EXTERN") {
240       readExtern();
241     } else if (tok == "GROUP") {
242       readGroup();
243     } else if (tok == "INCLUDE") {
244       readInclude();
245     } else if (tok == "INPUT") {
246       readInput();
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 == "OVERWRITE_SECTIONS") {
256       readOverwriteSections();
257     } else if (tok == "PHDRS") {
258       readPhdrs();
259     } else if (tok == "REGION_ALIAS") {
260       readRegionAlias();
261     } else if (tok == "SEARCH_DIR") {
262       readSearchDir();
263     } else if (tok == "SECTIONS") {
264       readSections();
265     } else if (tok == "TARGET") {
266       readTarget();
267     } else if (tok == "VERSION") {
268       readVersion();
269     } else if (SymbolAssignment *cmd = readAssignment(tok)) {
270       script->sectionCommands.push_back(cmd);
271     } else {
272       setError("unknown directive: " + tok);
273     }
274   }
275 }
276 
277 void ScriptParser::readDefsym(StringRef name) {
278   if (errorCount())
279     return;
280   Expr e = readExpr();
281   if (!atEOF())
282     setError("EOF expected, but got " + next());
283   SymbolAssignment *cmd = make<SymbolAssignment>(name, e, getCurrentLocation());
284   script->sectionCommands.push_back(cmd);
285 }
286 
287 void ScriptParser::addFile(StringRef s) {
288   if (isUnderSysroot && s.startswith("/")) {
289     SmallString<128> pathData;
290     StringRef path = (config->sysroot + s).toStringRef(pathData);
291     if (sys::fs::exists(path)) {
292       driver->addFile(saver.save(path), /*withLOption=*/false);
293       return;
294     }
295   }
296 
297   if (s.startswith("/")) {
298     // Case 1: s is an absolute path. Just open it.
299     driver->addFile(s, /*withLOption=*/false);
300   } else if (s.startswith("=")) {
301     // Case 2: relative to the sysroot.
302     if (config->sysroot.empty())
303       driver->addFile(s.substr(1), /*withLOption=*/false);
304     else
305       driver->addFile(saver.save(config->sysroot + "/" + s.substr(1)),
306                       /*withLOption=*/false);
307   } else if (s.startswith("-l")) {
308     // Case 3: search in the list of library paths.
309     driver->addLibrary(s.substr(2));
310   } else {
311     // Case 4: s is a relative path. Search in the directory of the script file.
312     std::string filename = std::string(getCurrentMB().getBufferIdentifier());
313     StringRef directory = sys::path::parent_path(filename);
314     if (!directory.empty()) {
315       SmallString<0> path(directory);
316       sys::path::append(path, s);
317       if (sys::fs::exists(path)) {
318         driver->addFile(path, /*withLOption=*/false);
319         return;
320       }
321     }
322     // Then search in the current working directory.
323     if (sys::fs::exists(s)) {
324       driver->addFile(s, /*withLOption=*/false);
325     } else {
326       // Finally, search in the list of library paths.
327       if (Optional<std::string> path = findFromSearchPaths(s))
328         driver->addFile(saver.save(*path), /*withLOption=*/true);
329       else
330         setError("unable to find " + s);
331     }
332   }
333 }
334 
335 void ScriptParser::readAsNeeded() {
336   expect("(");
337   bool orig = config->asNeeded;
338   config->asNeeded = true;
339   while (!errorCount() && !consume(")"))
340     addFile(unquote(next()));
341   config->asNeeded = orig;
342 }
343 
344 void ScriptParser::readEntry() {
345   // -e <symbol> takes predecence over ENTRY(<symbol>).
346   expect("(");
347   StringRef tok = next();
348   if (config->entry.empty())
349     config->entry = tok;
350   expect(")");
351 }
352 
353 void ScriptParser::readExtern() {
354   expect("(");
355   while (!errorCount() && !consume(")"))
356     config->undefined.push_back(unquote(next()));
357 }
358 
359 void ScriptParser::readGroup() {
360   bool orig = InputFile::isInGroup;
361   InputFile::isInGroup = true;
362   readInput();
363   InputFile::isInGroup = orig;
364   if (!orig)
365     ++InputFile::nextGroupId;
366 }
367 
368 void ScriptParser::readInclude() {
369   StringRef tok = unquote(next());
370 
371   if (!seen.insert(tok).second) {
372     setError("there is a cycle in linker script INCLUDEs");
373     return;
374   }
375 
376   if (Optional<std::string> path = searchScript(tok)) {
377     if (Optional<MemoryBufferRef> mb = readFile(*path))
378       tokenize(*mb);
379     return;
380   }
381   setError("cannot find linker script " + tok);
382 }
383 
384 void ScriptParser::readInput() {
385   expect("(");
386   while (!errorCount() && !consume(")")) {
387     if (consume("AS_NEEDED"))
388       readAsNeeded();
389     else
390       addFile(unquote(next()));
391   }
392 }
393 
394 void ScriptParser::readOutput() {
395   // -o <file> takes predecence over OUTPUT(<file>).
396   expect("(");
397   StringRef tok = next();
398   if (config->outputFile.empty())
399     config->outputFile = unquote(tok);
400   expect(")");
401 }
402 
403 void ScriptParser::readOutputArch() {
404   // OUTPUT_ARCH is ignored for now.
405   expect("(");
406   while (!errorCount() && !consume(")"))
407     skip();
408 }
409 
410 static std::pair<ELFKind, uint16_t> parseBfdName(StringRef s) {
411   return StringSwitch<std::pair<ELFKind, uint16_t>>(s)
412       .Case("elf32-i386", {ELF32LEKind, EM_386})
413       .Case("elf32-iamcu", {ELF32LEKind, EM_IAMCU})
414       .Case("elf32-littlearm", {ELF32LEKind, EM_ARM})
415       .Case("elf32-x86-64", {ELF32LEKind, EM_X86_64})
416       .Case("elf64-aarch64", {ELF64LEKind, EM_AARCH64})
417       .Case("elf64-littleaarch64", {ELF64LEKind, EM_AARCH64})
418       .Case("elf64-bigaarch64", {ELF64BEKind, EM_AARCH64})
419       .Case("elf32-powerpc", {ELF32BEKind, EM_PPC})
420       .Case("elf32-powerpcle", {ELF32LEKind, EM_PPC})
421       .Case("elf64-powerpc", {ELF64BEKind, EM_PPC64})
422       .Case("elf64-powerpcle", {ELF64LEKind, EM_PPC64})
423       .Case("elf64-x86-64", {ELF64LEKind, EM_X86_64})
424       .Cases("elf32-tradbigmips", "elf32-bigmips", {ELF32BEKind, EM_MIPS})
425       .Case("elf32-ntradbigmips", {ELF32BEKind, EM_MIPS})
426       .Case("elf32-tradlittlemips", {ELF32LEKind, EM_MIPS})
427       .Case("elf32-ntradlittlemips", {ELF32LEKind, EM_MIPS})
428       .Case("elf64-tradbigmips", {ELF64BEKind, EM_MIPS})
429       .Case("elf64-tradlittlemips", {ELF64LEKind, EM_MIPS})
430       .Case("elf32-littleriscv", {ELF32LEKind, EM_RISCV})
431       .Case("elf64-littleriscv", {ELF64LEKind, EM_RISCV})
432       .Case("elf64-sparc", {ELF64BEKind, EM_SPARCV9})
433       .Case("elf32-msp430", {ELF32LEKind, EM_MSP430})
434       .Default({ELFNoneKind, EM_NONE});
435 }
436 
437 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(default, big, little). Choose
438 // big if -EB is specified, little if -EL is specified, or default if neither is
439 // specified.
440 void ScriptParser::readOutputFormat() {
441   expect("(");
442 
443   StringRef s;
444   config->bfdname = unquote(next());
445   if (!consume(")")) {
446     expect(",");
447     s = unquote(next());
448     if (config->optEB)
449       config->bfdname = s;
450     expect(",");
451     s = unquote(next());
452     if (config->optEL)
453       config->bfdname = s;
454     consume(")");
455   }
456   s = config->bfdname;
457   if (s.consume_back("-freebsd"))
458     config->osabi = ELFOSABI_FREEBSD;
459 
460   std::tie(config->ekind, config->emachine) = parseBfdName(s);
461   if (config->emachine == EM_NONE)
462     setError("unknown output format name: " + config->bfdname);
463   if (s == "elf32-ntradlittlemips" || s == "elf32-ntradbigmips")
464     config->mipsN32Abi = true;
465   if (config->emachine == EM_MSP430)
466     config->osabi = ELFOSABI_STANDALONE;
467 }
468 
469 void ScriptParser::readPhdrs() {
470   expect("{");
471 
472   while (!errorCount() && !consume("}")) {
473     PhdrsCommand cmd;
474     cmd.name = next();
475     cmd.type = readPhdrType();
476 
477     while (!errorCount() && !consume(";")) {
478       if (consume("FILEHDR"))
479         cmd.hasFilehdr = true;
480       else if (consume("PHDRS"))
481         cmd.hasPhdrs = true;
482       else if (consume("AT"))
483         cmd.lmaExpr = readParenExpr();
484       else if (consume("FLAGS"))
485         cmd.flags = readParenExpr()().getValue();
486       else
487         setError("unexpected header attribute: " + next());
488     }
489 
490     script->phdrsCommands.push_back(cmd);
491   }
492 }
493 
494 void ScriptParser::readRegionAlias() {
495   expect("(");
496   StringRef alias = unquote(next());
497   expect(",");
498   StringRef name = next();
499   expect(")");
500 
501   if (script->memoryRegions.count(alias))
502     setError("redefinition of memory region '" + alias + "'");
503   if (!script->memoryRegions.count(name))
504     setError("memory region '" + name + "' is not defined");
505   script->memoryRegions.insert({alias, script->memoryRegions[name]});
506 }
507 
508 void ScriptParser::readSearchDir() {
509   expect("(");
510   StringRef tok = next();
511   if (!config->nostdlib)
512     config->searchPaths.push_back(unquote(tok));
513   expect(")");
514 }
515 
516 // This reads an overlay description. Overlays are used to describe output
517 // sections that use the same virtual memory range and normally would trigger
518 // linker's sections sanity check failures.
519 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
520 std::vector<BaseCommand *> ScriptParser::readOverlay() {
521   // VA and LMA expressions are optional, though for simplicity of
522   // implementation we assume they are not. That is what OVERLAY was designed
523   // for first of all: to allow sections with overlapping VAs at different LMAs.
524   Expr addrExpr = readExpr();
525   expect(":");
526   expect("AT");
527   Expr lmaExpr = readParenExpr();
528   expect("{");
529 
530   std::vector<BaseCommand *> v;
531   OutputSection *prev = nullptr;
532   while (!errorCount() && !consume("}")) {
533     // VA is the same for all sections. The LMAs are consecutive in memory
534     // starting from the base load address specified.
535     OutputSection *os = readOverlaySectionDescription();
536     os->addrExpr = addrExpr;
537     if (prev)
538       os->lmaExpr = [=] { return prev->getLMA() + prev->size; };
539     else
540       os->lmaExpr = lmaExpr;
541     v.push_back(os);
542     prev = os;
543   }
544 
545   // According to the specification, at the end of the overlay, the location
546   // counter should be equal to the overlay base address plus size of the
547   // largest section seen in the overlay.
548   // Here we want to create the Dot assignment command to achieve that.
549   Expr moveDot = [=] {
550     uint64_t max = 0;
551     for (BaseCommand *cmd : v)
552       max = std::max(max, cast<OutputSection>(cmd)->size);
553     return addrExpr().getValue() + max;
554   };
555   v.push_back(make<SymbolAssignment>(".", moveDot, getCurrentLocation()));
556   return v;
557 }
558 
559 void ScriptParser::readOverwriteSections() {
560   expect("{");
561   while (!errorCount() && !consume("}"))
562     script->overwriteSections.push_back(readOutputSectionDescription(next()));
563 }
564 
565 void ScriptParser::readSections() {
566   expect("{");
567   std::vector<BaseCommand *> v;
568   while (!errorCount() && !consume("}")) {
569     StringRef tok = next();
570     if (tok == "OVERLAY") {
571       for (BaseCommand *cmd : readOverlay())
572         v.push_back(cmd);
573       continue;
574     } else if (tok == "INCLUDE") {
575       readInclude();
576       continue;
577     }
578 
579     if (BaseCommand *cmd = readAssignment(tok))
580       v.push_back(cmd);
581     else
582       v.push_back(readOutputSectionDescription(tok));
583   }
584   script->sectionCommands.insert(script->sectionCommands.end(), v.begin(),
585                                  v.end());
586 
587   if (atEOF() || !consume("INSERT")) {
588     script->hasSectionsCommand = true;
589     return;
590   }
591 
592   bool isAfter = false;
593   if (consume("AFTER"))
594     isAfter = true;
595   else if (!consume("BEFORE"))
596     setError("expected AFTER/BEFORE, but got '" + next() + "'");
597   StringRef where = next();
598   for (BaseCommand *cmd : v)
599     if (auto *os = dyn_cast<OutputSection>(cmd))
600       script->insertCommands.push_back({os->name, isAfter, where});
601 }
602 
603 void ScriptParser::readTarget() {
604   // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
605   // we accept only a limited set of BFD names (i.e. "elf" or "binary")
606   // for --format. We recognize only /^elf/ and "binary" in the linker
607   // script as well.
608   expect("(");
609   StringRef tok = next();
610   expect(")");
611 
612   if (tok.startswith("elf"))
613     config->formatBinary = false;
614   else if (tok == "binary")
615     config->formatBinary = true;
616   else
617     setError("unknown target: " + tok);
618 }
619 
620 static int precedence(StringRef op) {
621   return StringSwitch<int>(op)
622       .Cases("*", "/", "%", 8)
623       .Cases("+", "-", 7)
624       .Cases("<<", ">>", 6)
625       .Cases("<", "<=", ">", ">=", "==", "!=", 5)
626       .Case("&", 4)
627       .Case("|", 3)
628       .Case("&&", 2)
629       .Case("||", 1)
630       .Default(-1);
631 }
632 
633 StringMatcher ScriptParser::readFilePatterns() {
634   StringMatcher Matcher;
635 
636   while (!errorCount() && !consume(")"))
637     Matcher.addPattern(SingleStringMatcher(next()));
638   return Matcher;
639 }
640 
641 SortSectionPolicy ScriptParser::peekSortKind() {
642   return StringSwitch<SortSectionPolicy>(peek())
643       .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name)
644       .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment)
645       .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority)
646       .Case("SORT_NONE", SortSectionPolicy::None)
647       .Default(SortSectionPolicy::Default);
648 }
649 
650 SortSectionPolicy ScriptParser::readSortKind() {
651   SortSectionPolicy ret = peekSortKind();
652   if (ret != SortSectionPolicy::Default)
653     skip();
654   return ret;
655 }
656 
657 // Reads SECTIONS command contents in the following form:
658 //
659 // <contents> ::= <elem>*
660 // <elem>     ::= <exclude>? <glob-pattern>
661 // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
662 //
663 // For example,
664 //
665 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
666 //
667 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
668 // The semantics of that is section .foo in any file, section .bar in
669 // any file but a.o, and section .baz in any file but b.o.
670 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
671   std::vector<SectionPattern> ret;
672   while (!errorCount() && peek() != ")") {
673     StringMatcher excludeFilePat;
674     if (consume("EXCLUDE_FILE")) {
675       expect("(");
676       excludeFilePat = readFilePatterns();
677     }
678 
679     StringMatcher SectionMatcher;
680     // Break if the next token is ), EXCLUDE_FILE, or SORT*.
681     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" &&
682            peekSortKind() == SortSectionPolicy::Default)
683       SectionMatcher.addPattern(unquote(next()));
684 
685     if (!SectionMatcher.empty())
686       ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});
687     else if (excludeFilePat.empty())
688       break;
689     else
690       setError("section pattern is expected");
691   }
692   return ret;
693 }
694 
695 // Reads contents of "SECTIONS" directive. That directive contains a
696 // list of glob patterns for input sections. The grammar is as follows.
697 //
698 // <patterns> ::= <section-list>
699 //              | <sort> "(" <section-list> ")"
700 //              | <sort> "(" <sort> "(" <section-list> ")" ")"
701 //
702 // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
703 //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
704 //
705 // <section-list> is parsed by readInputSectionsList().
706 InputSectionDescription *
707 ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
708                                     uint64_t withoutFlags) {
709   auto *cmd =
710       make<InputSectionDescription>(filePattern, withFlags, withoutFlags);
711   expect("(");
712 
713   while (!errorCount() && !consume(")")) {
714     SortSectionPolicy outer = readSortKind();
715     SortSectionPolicy inner = SortSectionPolicy::Default;
716     std::vector<SectionPattern> v;
717     if (outer != SortSectionPolicy::Default) {
718       expect("(");
719       inner = readSortKind();
720       if (inner != SortSectionPolicy::Default) {
721         expect("(");
722         v = readInputSectionsList();
723         expect(")");
724       } else {
725         v = readInputSectionsList();
726       }
727       expect(")");
728     } else {
729       v = readInputSectionsList();
730     }
731 
732     for (SectionPattern &pat : v) {
733       pat.sortInner = inner;
734       pat.sortOuter = outer;
735     }
736 
737     std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));
738   }
739   return cmd;
740 }
741 
742 InputSectionDescription *
743 ScriptParser::readInputSectionDescription(StringRef tok) {
744   // Input section wildcard can be surrounded by KEEP.
745   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
746   uint64_t withFlags = 0;
747   uint64_t withoutFlags = 0;
748   if (tok == "KEEP") {
749     expect("(");
750     if (consume("INPUT_SECTION_FLAGS"))
751       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
752     InputSectionDescription *cmd =
753         readInputSectionRules(next(), withFlags, withoutFlags);
754     expect(")");
755     script->keptSections.push_back(cmd);
756     return cmd;
757   }
758   if (tok == "INPUT_SECTION_FLAGS") {
759     std::tie(withFlags, withoutFlags) = readInputSectionFlags();
760     tok = next();
761   }
762   return readInputSectionRules(tok, withFlags, withoutFlags);
763 }
764 
765 void ScriptParser::readSort() {
766   expect("(");
767   expect("CONSTRUCTORS");
768   expect(")");
769 }
770 
771 Expr ScriptParser::readAssert() {
772   expect("(");
773   Expr e = readExpr();
774   expect(",");
775   StringRef msg = unquote(next());
776   expect(")");
777 
778   return [=] {
779     if (!e().getValue())
780       errorOrWarn(msg);
781     return script->getDot();
782   };
783 }
784 
785 // Tries to read the special directive for an output section definition which
786 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)".
787 // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below.
788 bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) {
789   if (tok1 != "(")
790     return false;
791   if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" && tok2 != "OVERLAY")
792     return false;
793 
794   expect("(");
795   if (consume("NOLOAD")) {
796     cmd->noload = true;
797     cmd->type = SHT_NOBITS;
798   } else {
799     skip(); // This is "COPY", "INFO" or "OVERLAY".
800     cmd->nonAlloc = true;
801   }
802   expect(")");
803   return true;
804 }
805 
806 // Reads an expression and/or the special directive for an output
807 // section definition. Directive is one of following: "(NOLOAD)",
808 // "(COPY)", "(INFO)" or "(OVERLAY)".
809 //
810 // An output section name can be followed by an address expression
811 // and/or directive. This grammar is not LL(1) because "(" can be
812 // interpreted as either the beginning of some expression or beginning
813 // of directive.
814 //
815 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
816 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
817 void ScriptParser::readSectionAddressType(OutputSection *cmd) {
818   if (readSectionDirective(cmd, peek(), peek2()))
819     return;
820 
821   cmd->addrExpr = readExpr();
822   if (peek() == "(" && !readSectionDirective(cmd, "(", peek2()))
823     setError("unknown section directive: " + peek2());
824 }
825 
826 static Expr checkAlignment(Expr e, std::string &loc) {
827   return [=] {
828     uint64_t alignment = std::max((uint64_t)1, e().getValue());
829     if (!isPowerOf2_64(alignment)) {
830       error(loc + ": alignment must be power of 2");
831       return (uint64_t)1; // Return a dummy value.
832     }
833     return alignment;
834   };
835 }
836 
837 OutputSection *ScriptParser::readOverlaySectionDescription() {
838   OutputSection *cmd =
839       script->createOutputSection(next(), getCurrentLocation());
840   cmd->inOverlay = true;
841   expect("{");
842   while (!errorCount() && !consume("}")) {
843     uint64_t withFlags = 0;
844     uint64_t withoutFlags = 0;
845     if (consume("INPUT_SECTION_FLAGS"))
846       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
847     cmd->sectionCommands.push_back(
848         readInputSectionRules(next(), withFlags, withoutFlags));
849   }
850   return cmd;
851 }
852 
853 OutputSection *ScriptParser::readOutputSectionDescription(StringRef outSec) {
854   OutputSection *cmd =
855       script->createOutputSection(outSec, getCurrentLocation());
856 
857   size_t symbolsReferenced = script->referencedSymbols.size();
858 
859   if (peek() != ":")
860     readSectionAddressType(cmd);
861   expect(":");
862 
863   std::string location = getCurrentLocation();
864   if (consume("AT"))
865     cmd->lmaExpr = readParenExpr();
866   if (consume("ALIGN"))
867     cmd->alignExpr = checkAlignment(readParenExpr(), location);
868   if (consume("SUBALIGN"))
869     cmd->subalignExpr = checkAlignment(readParenExpr(), location);
870 
871   // Parse constraints.
872   if (consume("ONLY_IF_RO"))
873     cmd->constraint = ConstraintKind::ReadOnly;
874   if (consume("ONLY_IF_RW"))
875     cmd->constraint = ConstraintKind::ReadWrite;
876   expect("{");
877 
878   while (!errorCount() && !consume("}")) {
879     StringRef tok = next();
880     if (tok == ";") {
881       // Empty commands are allowed. Do nothing here.
882     } else if (SymbolAssignment *assign = readAssignment(tok)) {
883       cmd->sectionCommands.push_back(assign);
884     } else if (ByteCommand *data = readByteCommand(tok)) {
885       cmd->sectionCommands.push_back(data);
886     } else if (tok == "CONSTRUCTORS") {
887       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
888       // by name. This is for very old file formats such as ECOFF/XCOFF.
889       // For ELF, we should ignore.
890     } else if (tok == "FILL") {
891       // We handle the FILL command as an alias for =fillexp section attribute,
892       // which is different from what GNU linkers do.
893       // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
894       if (peek() != "(")
895         setError("( expected, but got " + peek());
896       cmd->filler = readFill();
897     } else if (tok == "SORT") {
898       readSort();
899     } else if (tok == "INCLUDE") {
900       readInclude();
901     } else if (peek() == "(") {
902       cmd->sectionCommands.push_back(readInputSectionDescription(tok));
903     } else {
904       // We have a file name and no input sections description. It is not a
905       // commonly used syntax, but still acceptable. In that case, all sections
906       // from the file will be included.
907       // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
908       // handle this case here as it will already have been matched by the
909       // case above.
910       auto *isd = make<InputSectionDescription>(tok);
911       isd->sectionPatterns.push_back({{}, StringMatcher("*")});
912       cmd->sectionCommands.push_back(isd);
913     }
914   }
915 
916   if (consume(">"))
917     cmd->memoryRegionName = std::string(next());
918 
919   if (consume("AT")) {
920     expect(">");
921     cmd->lmaRegionName = std::string(next());
922   }
923 
924   if (cmd->lmaExpr && !cmd->lmaRegionName.empty())
925     error("section can't have both LMA and a load region");
926 
927   cmd->phdrs = readOutputSectionPhdrs();
928 
929   if (peek() == "=" || peek().startswith("=")) {
930     inExpr = true;
931     consume("=");
932     cmd->filler = readFill();
933     inExpr = false;
934   }
935 
936   // Consume optional comma following output section command.
937   consume(",");
938 
939   if (script->referencedSymbols.size() > symbolsReferenced)
940     cmd->expressionsUseSymbols = true;
941   return cmd;
942 }
943 
944 // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
945 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
946 // We do not support using symbols in such expressions.
947 //
948 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
949 // size, while ld.gold always handles it as a 32-bit big-endian number.
950 // We are compatible with ld.gold because it's easier to implement.
951 // Also, we require that expressions with operators must be wrapped into
952 // round brackets. We did it to resolve the ambiguity when parsing scripts like:
953 // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
954 std::array<uint8_t, 4> ScriptParser::readFill() {
955   uint64_t value = readPrimary()().val;
956   if (value > UINT32_MAX)
957     setError("filler expression result does not fit 32-bit: 0x" +
958              Twine::utohexstr(value));
959 
960   std::array<uint8_t, 4> buf;
961   write32be(buf.data(), (uint32_t)value);
962   return buf;
963 }
964 
965 SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
966   expect("(");
967   SymbolAssignment *cmd = readSymbolAssignment(next());
968   cmd->provide = provide;
969   cmd->hidden = hidden;
970   expect(")");
971   return cmd;
972 }
973 
974 SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
975   // Assert expression returns Dot, so this is equal to ".=."
976   if (tok == "ASSERT")
977     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
978 
979   size_t oldPos = pos;
980   SymbolAssignment *cmd = nullptr;
981   if (peek() == "=" || peek() == "+=")
982     cmd = readSymbolAssignment(tok);
983   else if (tok == "PROVIDE")
984     cmd = readProvideHidden(true, false);
985   else if (tok == "HIDDEN")
986     cmd = readProvideHidden(false, true);
987   else if (tok == "PROVIDE_HIDDEN")
988     cmd = readProvideHidden(true, true);
989 
990   if (cmd) {
991     cmd->commandString =
992         tok.str() + " " +
993         llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
994     expect(";");
995   }
996   return cmd;
997 }
998 
999 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
1000   StringRef op = next();
1001   assert(op == "=" || op == "+=");
1002   Expr e = readExpr();
1003   if (op == "+=") {
1004     std::string loc = getCurrentLocation();
1005     e = [=] { return add(script->getSymbolValue(name, loc), e()); };
1006   }
1007   return make<SymbolAssignment>(name, e, getCurrentLocation());
1008 }
1009 
1010 // This is an operator-precedence parser to parse a linker
1011 // script expression.
1012 Expr ScriptParser::readExpr() {
1013   // Our lexer is context-aware. Set the in-expression bit so that
1014   // they apply different tokenization rules.
1015   bool orig = inExpr;
1016   inExpr = true;
1017   Expr e = readExpr1(readPrimary(), 0);
1018   inExpr = orig;
1019   return e;
1020 }
1021 
1022 Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
1023   if (op == "+")
1024     return [=] { return add(l(), r()); };
1025   if (op == "-")
1026     return [=] { return sub(l(), r()); };
1027   if (op == "*")
1028     return [=] { return l().getValue() * r().getValue(); };
1029   if (op == "/") {
1030     std::string loc = getCurrentLocation();
1031     return [=]() -> uint64_t {
1032       if (uint64_t rv = r().getValue())
1033         return l().getValue() / rv;
1034       error(loc + ": division by zero");
1035       return 0;
1036     };
1037   }
1038   if (op == "%") {
1039     std::string loc = getCurrentLocation();
1040     return [=]() -> uint64_t {
1041       if (uint64_t rv = r().getValue())
1042         return l().getValue() % rv;
1043       error(loc + ": modulo by zero");
1044       return 0;
1045     };
1046   }
1047   if (op == "<<")
1048     return [=] { return l().getValue() << r().getValue(); };
1049   if (op == ">>")
1050     return [=] { return l().getValue() >> r().getValue(); };
1051   if (op == "<")
1052     return [=] { return l().getValue() < r().getValue(); };
1053   if (op == ">")
1054     return [=] { return l().getValue() > r().getValue(); };
1055   if (op == ">=")
1056     return [=] { return l().getValue() >= r().getValue(); };
1057   if (op == "<=")
1058     return [=] { return l().getValue() <= r().getValue(); };
1059   if (op == "==")
1060     return [=] { return l().getValue() == r().getValue(); };
1061   if (op == "!=")
1062     return [=] { return l().getValue() != r().getValue(); };
1063   if (op == "||")
1064     return [=] { return l().getValue() || r().getValue(); };
1065   if (op == "&&")
1066     return [=] { return l().getValue() && r().getValue(); };
1067   if (op == "&")
1068     return [=] { return bitAnd(l(), r()); };
1069   if (op == "|")
1070     return [=] { return bitOr(l(), r()); };
1071   llvm_unreachable("invalid operator");
1072 }
1073 
1074 // This is a part of the operator-precedence parser. This function
1075 // assumes that the remaining token stream starts with an operator.
1076 Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1077   while (!atEOF() && !errorCount()) {
1078     // Read an operator and an expression.
1079     if (consume("?"))
1080       return readTernary(lhs);
1081     StringRef op1 = peek();
1082     if (precedence(op1) < minPrec)
1083       break;
1084     skip();
1085     Expr rhs = readPrimary();
1086 
1087     // Evaluate the remaining part of the expression first if the
1088     // next operator has greater precedence than the previous one.
1089     // For example, if we have read "+" and "3", and if the next
1090     // operator is "*", then we'll evaluate 3 * ... part first.
1091     while (!atEOF()) {
1092       StringRef op2 = peek();
1093       if (precedence(op2) <= precedence(op1))
1094         break;
1095       rhs = readExpr1(rhs, precedence(op2));
1096     }
1097 
1098     lhs = combine(op1, lhs, rhs);
1099   }
1100   return lhs;
1101 }
1102 
1103 Expr ScriptParser::getPageSize() {
1104   std::string location = getCurrentLocation();
1105   return [=]() -> uint64_t {
1106     if (target)
1107       return config->commonPageSize;
1108     error(location + ": unable to calculate page size");
1109     return 4096; // Return a dummy value.
1110   };
1111 }
1112 
1113 Expr ScriptParser::readConstant() {
1114   StringRef s = readParenLiteral();
1115   if (s == "COMMONPAGESIZE")
1116     return getPageSize();
1117   if (s == "MAXPAGESIZE")
1118     return [] { return config->maxPageSize; };
1119   setError("unknown constant: " + s);
1120   return [] { return 0; };
1121 }
1122 
1123 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1124 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1125 // have "K" (Ki) or "M" (Mi) suffixes.
1126 static Optional<uint64_t> parseInt(StringRef tok) {
1127   // Hexadecimal
1128   uint64_t val;
1129   if (tok.startswith_insensitive("0x")) {
1130     if (!to_integer(tok.substr(2), val, 16))
1131       return None;
1132     return val;
1133   }
1134   if (tok.endswith_insensitive("H")) {
1135     if (!to_integer(tok.drop_back(), val, 16))
1136       return None;
1137     return val;
1138   }
1139 
1140   // Decimal
1141   if (tok.endswith_insensitive("K")) {
1142     if (!to_integer(tok.drop_back(), val, 10))
1143       return None;
1144     return val * 1024;
1145   }
1146   if (tok.endswith_insensitive("M")) {
1147     if (!to_integer(tok.drop_back(), val, 10))
1148       return None;
1149     return val * 1024 * 1024;
1150   }
1151   if (!to_integer(tok, val, 10))
1152     return None;
1153   return val;
1154 }
1155 
1156 ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
1157   int size = StringSwitch<int>(tok)
1158                  .Case("BYTE", 1)
1159                  .Case("SHORT", 2)
1160                  .Case("LONG", 4)
1161                  .Case("QUAD", 8)
1162                  .Default(-1);
1163   if (size == -1)
1164     return nullptr;
1165 
1166   size_t oldPos = pos;
1167   Expr e = readParenExpr();
1168   std::string commandString =
1169       tok.str() + " " +
1170       llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1171   return make<ByteCommand>(e, size, commandString);
1172 }
1173 
1174 static llvm::Optional<uint64_t> parseFlag(StringRef tok) {
1175   if (llvm::Optional<uint64_t> asInt = parseInt(tok))
1176     return asInt;
1177 #define CASE_ENT(enum) #enum, ELF::enum
1178   return StringSwitch<llvm::Optional<uint64_t>>(tok)
1179       .Case(CASE_ENT(SHF_WRITE))
1180       .Case(CASE_ENT(SHF_ALLOC))
1181       .Case(CASE_ENT(SHF_EXECINSTR))
1182       .Case(CASE_ENT(SHF_MERGE))
1183       .Case(CASE_ENT(SHF_STRINGS))
1184       .Case(CASE_ENT(SHF_INFO_LINK))
1185       .Case(CASE_ENT(SHF_LINK_ORDER))
1186       .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1187       .Case(CASE_ENT(SHF_GROUP))
1188       .Case(CASE_ENT(SHF_TLS))
1189       .Case(CASE_ENT(SHF_COMPRESSED))
1190       .Case(CASE_ENT(SHF_EXCLUDE))
1191       .Case(CASE_ENT(SHF_ARM_PURECODE))
1192       .Default(None);
1193 #undef CASE_ENT
1194 }
1195 
1196 // Reads the '(' <flags> ')' list of section flags in
1197 // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1198 // following form:
1199 // <flags> ::= <flag>
1200 //           | <flags> & flag
1201 // <flag>  ::= Recognized Flag Name, or Integer value of flag.
1202 // If the first character of <flag> is a ! then this means without flag,
1203 // otherwise with flag.
1204 // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1205 // without flag SHF_WRITE.
1206 std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1207    uint64_t withFlags = 0;
1208    uint64_t withoutFlags = 0;
1209    expect("(");
1210    while (!errorCount()) {
1211     StringRef tok = unquote(next());
1212     bool without = tok.consume_front("!");
1213     if (llvm::Optional<uint64_t> flag = parseFlag(tok)) {
1214       if (without)
1215         withoutFlags |= *flag;
1216       else
1217         withFlags |= *flag;
1218     } else {
1219       setError("unrecognised flag: " + tok);
1220     }
1221     if (consume(")"))
1222       break;
1223     if (!consume("&")) {
1224       next();
1225       setError("expected & or )");
1226     }
1227   }
1228   return std::make_pair(withFlags, withoutFlags);
1229 }
1230 
1231 StringRef ScriptParser::readParenLiteral() {
1232   expect("(");
1233   bool orig = inExpr;
1234   inExpr = false;
1235   StringRef tok = next();
1236   inExpr = orig;
1237   expect(")");
1238   return tok;
1239 }
1240 
1241 static void checkIfExists(OutputSection *cmd, StringRef location) {
1242   if (cmd->location.empty() && script->errorOnMissingSection)
1243     error(location + ": undefined section " + cmd->name);
1244 }
1245 
1246 static bool isValidSymbolName(StringRef s) {
1247   auto valid = [](char c) {
1248     return isAlnum(c) || c == '$' || c == '.' || c == '_';
1249   };
1250   return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);
1251 }
1252 
1253 Expr ScriptParser::readPrimary() {
1254   if (peek() == "(")
1255     return readParenExpr();
1256 
1257   if (consume("~")) {
1258     Expr e = readPrimary();
1259     return [=] { return ~e().getValue(); };
1260   }
1261   if (consume("!")) {
1262     Expr e = readPrimary();
1263     return [=] { return !e().getValue(); };
1264   }
1265   if (consume("-")) {
1266     Expr e = readPrimary();
1267     return [=] { return -e().getValue(); };
1268   }
1269 
1270   StringRef tok = next();
1271   std::string location = getCurrentLocation();
1272 
1273   // Built-in functions are parsed here.
1274   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1275   if (tok == "ABSOLUTE") {
1276     Expr inner = readParenExpr();
1277     return [=] {
1278       ExprValue i = inner();
1279       i.forceAbsolute = true;
1280       return i;
1281     };
1282   }
1283   if (tok == "ADDR") {
1284     StringRef name = readParenLiteral();
1285     OutputSection *sec = script->getOrCreateOutputSection(name);
1286     sec->usedInExpression = true;
1287     return [=]() -> ExprValue {
1288       checkIfExists(sec, location);
1289       return {sec, false, 0, location};
1290     };
1291   }
1292   if (tok == "ALIGN") {
1293     expect("(");
1294     Expr e = readExpr();
1295     if (consume(")")) {
1296       e = checkAlignment(e, location);
1297       return [=] { return alignTo(script->getDot(), e().getValue()); };
1298     }
1299     expect(",");
1300     Expr e2 = checkAlignment(readExpr(), location);
1301     expect(")");
1302     return [=] {
1303       ExprValue v = e();
1304       v.alignment = e2().getValue();
1305       return v;
1306     };
1307   }
1308   if (tok == "ALIGNOF") {
1309     StringRef name = readParenLiteral();
1310     OutputSection *cmd = script->getOrCreateOutputSection(name);
1311     return [=] {
1312       checkIfExists(cmd, location);
1313       return cmd->alignment;
1314     };
1315   }
1316   if (tok == "ASSERT")
1317     return readAssert();
1318   if (tok == "CONSTANT")
1319     return readConstant();
1320   if (tok == "DATA_SEGMENT_ALIGN") {
1321     expect("(");
1322     Expr e = readExpr();
1323     expect(",");
1324     readExpr();
1325     expect(")");
1326     return [=] {
1327       return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue()));
1328     };
1329   }
1330   if (tok == "DATA_SEGMENT_END") {
1331     expect("(");
1332     expect(".");
1333     expect(")");
1334     return [] { return script->getDot(); };
1335   }
1336   if (tok == "DATA_SEGMENT_RELRO_END") {
1337     // GNU linkers implements more complicated logic to handle
1338     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1339     // just align to the next page boundary for simplicity.
1340     expect("(");
1341     readExpr();
1342     expect(",");
1343     readExpr();
1344     expect(")");
1345     Expr e = getPageSize();
1346     return [=] { return alignTo(script->getDot(), e().getValue()); };
1347   }
1348   if (tok == "DEFINED") {
1349     StringRef name = readParenLiteral();
1350     return [=] {
1351       Symbol *b = symtab->find(name);
1352       return (b && b->isDefined()) ? 1 : 0;
1353     };
1354   }
1355   if (tok == "LENGTH") {
1356     StringRef name = readParenLiteral();
1357     if (script->memoryRegions.count(name) == 0) {
1358       setError("memory region not defined: " + name);
1359       return [] { return 0; };
1360     }
1361     return script->memoryRegions[name]->length;
1362   }
1363   if (tok == "LOADADDR") {
1364     StringRef name = readParenLiteral();
1365     OutputSection *cmd = script->getOrCreateOutputSection(name);
1366     cmd->usedInExpression = true;
1367     return [=] {
1368       checkIfExists(cmd, location);
1369       return cmd->getLMA();
1370     };
1371   }
1372   if (tok == "LOG2CEIL") {
1373     expect("(");
1374     Expr a = readExpr();
1375     expect(")");
1376     return [=] {
1377       // LOG2CEIL(0) is defined to be 0.
1378       return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1379     };
1380   }
1381   if (tok == "MAX" || tok == "MIN") {
1382     expect("(");
1383     Expr a = readExpr();
1384     expect(",");
1385     Expr b = readExpr();
1386     expect(")");
1387     if (tok == "MIN")
1388       return [=] { return std::min(a().getValue(), b().getValue()); };
1389     return [=] { return std::max(a().getValue(), b().getValue()); };
1390   }
1391   if (tok == "ORIGIN") {
1392     StringRef name = readParenLiteral();
1393     if (script->memoryRegions.count(name) == 0) {
1394       setError("memory region not defined: " + name);
1395       return [] { return 0; };
1396     }
1397     return script->memoryRegions[name]->origin;
1398   }
1399   if (tok == "SEGMENT_START") {
1400     expect("(");
1401     skip();
1402     expect(",");
1403     Expr e = readExpr();
1404     expect(")");
1405     return [=] { return e(); };
1406   }
1407   if (tok == "SIZEOF") {
1408     StringRef name = readParenLiteral();
1409     OutputSection *cmd = script->getOrCreateOutputSection(name);
1410     // Linker script does not create an output section if its content is empty.
1411     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1412     // be empty.
1413     return [=] { return cmd->size; };
1414   }
1415   if (tok == "SIZEOF_HEADERS")
1416     return [=] { return elf::getHeaderSize(); };
1417 
1418   // Tok is the dot.
1419   if (tok == ".")
1420     return [=] { return script->getSymbolValue(tok, location); };
1421 
1422   // Tok is a literal number.
1423   if (Optional<uint64_t> val = parseInt(tok))
1424     return [=] { return *val; };
1425 
1426   // Tok is a symbol name.
1427   if (!isValidSymbolName(tok))
1428     setError("malformed number: " + tok);
1429   script->referencedSymbols.push_back(tok);
1430   return [=] { return script->getSymbolValue(tok, location); };
1431 }
1432 
1433 Expr ScriptParser::readTernary(Expr cond) {
1434   Expr l = readExpr();
1435   expect(":");
1436   Expr r = readExpr();
1437   return [=] { return cond().getValue() ? l() : r(); };
1438 }
1439 
1440 Expr ScriptParser::readParenExpr() {
1441   expect("(");
1442   Expr e = readExpr();
1443   expect(")");
1444   return e;
1445 }
1446 
1447 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1448   std::vector<StringRef> phdrs;
1449   while (!errorCount() && peek().startswith(":")) {
1450     StringRef tok = next();
1451     phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
1452   }
1453   return phdrs;
1454 }
1455 
1456 // Read a program header type name. The next token must be a
1457 // name of a program header type or a constant (e.g. "0x3").
1458 unsigned ScriptParser::readPhdrType() {
1459   StringRef tok = next();
1460   if (Optional<uint64_t> val = parseInt(tok))
1461     return *val;
1462 
1463   unsigned ret = StringSwitch<unsigned>(tok)
1464                      .Case("PT_NULL", PT_NULL)
1465                      .Case("PT_LOAD", PT_LOAD)
1466                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1467                      .Case("PT_INTERP", PT_INTERP)
1468                      .Case("PT_NOTE", PT_NOTE)
1469                      .Case("PT_SHLIB", PT_SHLIB)
1470                      .Case("PT_PHDR", PT_PHDR)
1471                      .Case("PT_TLS", PT_TLS)
1472                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1473                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1474                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1475                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1476                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1477                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1478                      .Default(-1);
1479 
1480   if (ret == (unsigned)-1) {
1481     setError("invalid program header type: " + tok);
1482     return PT_NULL;
1483   }
1484   return ret;
1485 }
1486 
1487 // Reads an anonymous version declaration.
1488 void ScriptParser::readAnonymousDeclaration() {
1489   std::vector<SymbolVersion> locals;
1490   std::vector<SymbolVersion> globals;
1491   std::tie(locals, globals) = readSymbols();
1492   for (const SymbolVersion &pat : locals)
1493     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat);
1494   for (const SymbolVersion &pat : globals)
1495     config->versionDefinitions[VER_NDX_GLOBAL].patterns.push_back(pat);
1496 
1497   expect(";");
1498 }
1499 
1500 // Reads a non-anonymous version definition,
1501 // e.g. "VerStr { global: foo; bar; local: *; };".
1502 void ScriptParser::readVersionDeclaration(StringRef verStr) {
1503   // Read a symbol list.
1504   std::vector<SymbolVersion> locals;
1505   std::vector<SymbolVersion> globals;
1506   std::tie(locals, globals) = readSymbols();
1507   for (const SymbolVersion &pat : locals)
1508     config->versionDefinitions[VER_NDX_LOCAL].patterns.push_back(pat);
1509 
1510   // Create a new version definition and add that to the global symbols.
1511   VersionDefinition ver;
1512   ver.name = verStr;
1513   ver.patterns = globals;
1514   ver.id = config->versionDefinitions.size();
1515   config->versionDefinitions.push_back(ver);
1516 
1517   // Each version may have a parent version. For example, "Ver2"
1518   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1519   // as a parent. This version hierarchy is, probably against your
1520   // instinct, purely for hint; the runtime doesn't care about it
1521   // at all. In LLD, we simply ignore it.
1522   if (next() != ";")
1523     expect(";");
1524 }
1525 
1526 bool elf::hasWildcard(StringRef s) {
1527   return s.find_first_of("?*[") != StringRef::npos;
1528 }
1529 
1530 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1531 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1532 ScriptParser::readSymbols() {
1533   std::vector<SymbolVersion> locals;
1534   std::vector<SymbolVersion> globals;
1535   std::vector<SymbolVersion> *v = &globals;
1536 
1537   while (!errorCount()) {
1538     if (consume("}"))
1539       break;
1540     if (consumeLabel("local")) {
1541       v = &locals;
1542       continue;
1543     }
1544     if (consumeLabel("global")) {
1545       v = &globals;
1546       continue;
1547     }
1548 
1549     if (consume("extern")) {
1550       std::vector<SymbolVersion> ext = readVersionExtern();
1551       v->insert(v->end(), ext.begin(), ext.end());
1552     } else {
1553       StringRef tok = next();
1554       v->push_back({unquote(tok), false, hasWildcard(tok)});
1555     }
1556     expect(";");
1557   }
1558   return {locals, globals};
1559 }
1560 
1561 // Reads an "extern C++" directive, e.g.,
1562 // "extern "C++" { ns::*; "f(int, double)"; };"
1563 //
1564 // The last semicolon is optional. E.g. this is OK:
1565 // "extern "C++" { ns::*; "f(int, double)" };"
1566 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1567   StringRef tok = next();
1568   bool isCXX = tok == "\"C++\"";
1569   if (!isCXX && tok != "\"C\"")
1570     setError("Unknown language");
1571   expect("{");
1572 
1573   std::vector<SymbolVersion> ret;
1574   while (!errorCount() && peek() != "}") {
1575     StringRef tok = next();
1576     ret.push_back(
1577         {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)});
1578     if (consume("}"))
1579       return ret;
1580     expect(";");
1581   }
1582 
1583   expect("}");
1584   return ret;
1585 }
1586 
1587 Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
1588                                         StringRef s3) {
1589   if (!consume(s1) && !consume(s2) && !consume(s3)) {
1590     setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
1591     return [] { return 0; };
1592   }
1593   expect("=");
1594   return readExpr();
1595 }
1596 
1597 // Parse the MEMORY command as specified in:
1598 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1599 //
1600 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1601 void ScriptParser::readMemory() {
1602   expect("{");
1603   while (!errorCount() && !consume("}")) {
1604     StringRef tok = next();
1605     if (tok == "INCLUDE") {
1606       readInclude();
1607       continue;
1608     }
1609 
1610     uint32_t flags = 0;
1611     uint32_t negFlags = 0;
1612     if (consume("(")) {
1613       std::tie(flags, negFlags) = readMemoryAttributes();
1614       expect(")");
1615     }
1616     expect(":");
1617 
1618     Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
1619     expect(",");
1620     Expr length = readMemoryAssignment("LENGTH", "len", "l");
1621 
1622     // Add the memory region to the region map.
1623     MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, negFlags);
1624     if (!script->memoryRegions.insert({tok, mr}).second)
1625       setError("region '" + tok + "' already defined");
1626   }
1627 }
1628 
1629 // This function parses the attributes used to match against section
1630 // flags when placing output sections in a memory region. These flags
1631 // are only used when an explicit memory region name is not used.
1632 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1633   uint32_t flags = 0;
1634   uint32_t negFlags = 0;
1635   bool invert = false;
1636 
1637   for (char c : next().lower()) {
1638     uint32_t flag = 0;
1639     if (c == '!')
1640       invert = !invert;
1641     else if (c == 'w')
1642       flag = SHF_WRITE;
1643     else if (c == 'x')
1644       flag = SHF_EXECINSTR;
1645     else if (c == 'a')
1646       flag = SHF_ALLOC;
1647     else if (c != 'r')
1648       setError("invalid memory region attribute");
1649 
1650     if (invert)
1651       negFlags |= flag;
1652     else
1653       flags |= flag;
1654   }
1655   return {flags, negFlags};
1656 }
1657 
1658 void elf::readLinkerScript(MemoryBufferRef mb) {
1659   llvm::TimeTraceScope timeScope("Read linker script",
1660                                  mb.getBufferIdentifier());
1661   ScriptParser(mb).readLinkerScript();
1662 }
1663 
1664 void elf::readVersionScript(MemoryBufferRef mb) {
1665   llvm::TimeTraceScope timeScope("Read version script",
1666                                  mb.getBufferIdentifier());
1667   ScriptParser(mb).readVersionScript();
1668 }
1669 
1670 void elf::readDynamicList(MemoryBufferRef mb) {
1671   llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
1672   ScriptParser(mb).readDynamicList();
1673 }
1674 
1675 void elf::readDefsym(StringRef name, MemoryBufferRef mb) {
1676   llvm::TimeTraceScope timeScope("Read defsym input", name);
1677   ScriptParser(mb).readDefsym(name);
1678 }
1679