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