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 (tok == "(" || tok == ")") {
949       setError("expected filename pattern");
950     } else if (peek() == "(") {
951       osec->commands.push_back(readInputSectionDescription(tok));
952     } else {
953       // We have a file name and no input sections description. It is not a
954       // commonly used syntax, but still acceptable. In that case, all sections
955       // from the file will be included.
956       // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
957       // handle this case here as it will already have been matched by the
958       // case above.
959       auto *isd = make<InputSectionDescription>(tok);
960       isd->sectionPatterns.push_back({{}, StringMatcher("*")});
961       osec->commands.push_back(isd);
962     }
963   }
964 
965   if (consume(">"))
966     osec->memoryRegionName = std::string(next());
967 
968   if (consume("AT")) {
969     expect(">");
970     osec->lmaRegionName = std::string(next());
971   }
972 
973   if (osec->lmaExpr && !osec->lmaRegionName.empty())
974     error("section can't have both LMA and a load region");
975 
976   osec->phdrs = readOutputSectionPhdrs();
977 
978   if (peek() == "=" || peek().startswith("=")) {
979     inExpr = true;
980     consume("=");
981     osec->filler = readFill();
982     inExpr = false;
983   }
984 
985   // Consume optional comma following output section command.
986   consume(",");
987 
988   if (script->referencedSymbols.size() > symbolsReferenced)
989     osec->expressionsUseSymbols = true;
990   return cmd;
991 }
992 
993 // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
994 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
995 // We do not support using symbols in such expressions.
996 //
997 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
998 // size, while ld.gold always handles it as a 32-bit big-endian number.
999 // We are compatible with ld.gold because it's easier to implement.
1000 // Also, we require that expressions with operators must be wrapped into
1001 // round brackets. We did it to resolve the ambiguity when parsing scripts like:
1002 // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
1003 std::array<uint8_t, 4> ScriptParser::readFill() {
1004   uint64_t value = readPrimary()().val;
1005   if (value > UINT32_MAX)
1006     setError("filler expression result does not fit 32-bit: 0x" +
1007              Twine::utohexstr(value));
1008 
1009   std::array<uint8_t, 4> buf;
1010   write32be(buf.data(), (uint32_t)value);
1011   return buf;
1012 }
1013 
1014 SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
1015   expect("(");
1016   SymbolAssignment *cmd = readSymbolAssignment(next());
1017   cmd->provide = provide;
1018   cmd->hidden = hidden;
1019   expect(")");
1020   return cmd;
1021 }
1022 
1023 SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
1024   // Assert expression returns Dot, so this is equal to ".=."
1025   if (tok == "ASSERT")
1026     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
1027 
1028   size_t oldPos = pos;
1029   SymbolAssignment *cmd = nullptr;
1030   if (peek() == "=" || peek() == "+=")
1031     cmd = readSymbolAssignment(tok);
1032   else if (tok == "PROVIDE")
1033     cmd = readProvideHidden(true, false);
1034   else if (tok == "HIDDEN")
1035     cmd = readProvideHidden(false, true);
1036   else if (tok == "PROVIDE_HIDDEN")
1037     cmd = readProvideHidden(true, true);
1038 
1039   if (cmd) {
1040     cmd->commandString =
1041         tok.str() + " " +
1042         llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1043     expect(";");
1044   }
1045   return cmd;
1046 }
1047 
1048 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
1049   name = unquote(name);
1050   StringRef op = next();
1051   assert(op == "=" || op == "+=");
1052   Expr e = readExpr();
1053   if (op == "+=") {
1054     std::string loc = getCurrentLocation();
1055     e = [=] { return add(script->getSymbolValue(name, loc), e()); };
1056   }
1057   return make<SymbolAssignment>(name, e, getCurrentLocation());
1058 }
1059 
1060 // This is an operator-precedence parser to parse a linker
1061 // script expression.
1062 Expr ScriptParser::readExpr() {
1063   // Our lexer is context-aware. Set the in-expression bit so that
1064   // they apply different tokenization rules.
1065   bool orig = inExpr;
1066   inExpr = true;
1067   Expr e = readExpr1(readPrimary(), 0);
1068   inExpr = orig;
1069   return e;
1070 }
1071 
1072 Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
1073   if (op == "+")
1074     return [=] { return add(l(), r()); };
1075   if (op == "-")
1076     return [=] { return sub(l(), r()); };
1077   if (op == "*")
1078     return [=] { return l().getValue() * r().getValue(); };
1079   if (op == "/") {
1080     std::string loc = getCurrentLocation();
1081     return [=]() -> uint64_t {
1082       if (uint64_t rv = r().getValue())
1083         return l().getValue() / rv;
1084       error(loc + ": division by zero");
1085       return 0;
1086     };
1087   }
1088   if (op == "%") {
1089     std::string loc = getCurrentLocation();
1090     return [=]() -> uint64_t {
1091       if (uint64_t rv = r().getValue())
1092         return l().getValue() % rv;
1093       error(loc + ": modulo by zero");
1094       return 0;
1095     };
1096   }
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 l().getValue() && r().getValue(); };
1117   if (op == "&")
1118     return [=] { return bitAnd(l(), r()); };
1119   if (op == "|")
1120     return [=] { return bitOr(l(), r()); };
1121   llvm_unreachable("invalid operator");
1122 }
1123 
1124 // This is a part of the operator-precedence parser. This function
1125 // assumes that the remaining token stream starts with an operator.
1126 Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1127   while (!atEOF() && !errorCount()) {
1128     // Read an operator and an expression.
1129     if (consume("?"))
1130       return readTernary(lhs);
1131     StringRef op1 = peek();
1132     if (precedence(op1) < minPrec)
1133       break;
1134     skip();
1135     Expr rhs = readPrimary();
1136 
1137     // Evaluate the remaining part of the expression first if the
1138     // next operator has greater precedence than the previous one.
1139     // For example, if we have read "+" and "3", and if the next
1140     // operator is "*", then we'll evaluate 3 * ... part first.
1141     while (!atEOF()) {
1142       StringRef op2 = peek();
1143       if (precedence(op2) <= precedence(op1))
1144         break;
1145       rhs = readExpr1(rhs, precedence(op2));
1146     }
1147 
1148     lhs = combine(op1, lhs, rhs);
1149   }
1150   return lhs;
1151 }
1152 
1153 Expr ScriptParser::getPageSize() {
1154   std::string location = getCurrentLocation();
1155   return [=]() -> uint64_t {
1156     if (target)
1157       return config->commonPageSize;
1158     error(location + ": unable to calculate page size");
1159     return 4096; // Return a dummy value.
1160   };
1161 }
1162 
1163 Expr ScriptParser::readConstant() {
1164   StringRef s = readParenLiteral();
1165   if (s == "COMMONPAGESIZE")
1166     return getPageSize();
1167   if (s == "MAXPAGESIZE")
1168     return [] { return config->maxPageSize; };
1169   setError("unknown constant: " + s);
1170   return [] { return 0; };
1171 }
1172 
1173 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1174 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1175 // have "K" (Ki) or "M" (Mi) suffixes.
1176 static Optional<uint64_t> parseInt(StringRef tok) {
1177   // Hexadecimal
1178   uint64_t val;
1179   if (tok.startswith_insensitive("0x")) {
1180     if (!to_integer(tok.substr(2), val, 16))
1181       return None;
1182     return val;
1183   }
1184   if (tok.endswith_insensitive("H")) {
1185     if (!to_integer(tok.drop_back(), val, 16))
1186       return None;
1187     return val;
1188   }
1189 
1190   // Decimal
1191   if (tok.endswith_insensitive("K")) {
1192     if (!to_integer(tok.drop_back(), val, 10))
1193       return None;
1194     return val * 1024;
1195   }
1196   if (tok.endswith_insensitive("M")) {
1197     if (!to_integer(tok.drop_back(), val, 10))
1198       return None;
1199     return val * 1024 * 1024;
1200   }
1201   if (!to_integer(tok, val, 10))
1202     return None;
1203   return val;
1204 }
1205 
1206 ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
1207   int size = StringSwitch<int>(tok)
1208                  .Case("BYTE", 1)
1209                  .Case("SHORT", 2)
1210                  .Case("LONG", 4)
1211                  .Case("QUAD", 8)
1212                  .Default(-1);
1213   if (size == -1)
1214     return nullptr;
1215 
1216   size_t oldPos = pos;
1217   Expr e = readParenExpr();
1218   std::string commandString =
1219       tok.str() + " " +
1220       llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1221   return make<ByteCommand>(e, size, commandString);
1222 }
1223 
1224 static llvm::Optional<uint64_t> parseFlag(StringRef tok) {
1225   if (llvm::Optional<uint64_t> asInt = parseInt(tok))
1226     return asInt;
1227 #define CASE_ENT(enum) #enum, ELF::enum
1228   return StringSwitch<llvm::Optional<uint64_t>>(tok)
1229       .Case(CASE_ENT(SHF_WRITE))
1230       .Case(CASE_ENT(SHF_ALLOC))
1231       .Case(CASE_ENT(SHF_EXECINSTR))
1232       .Case(CASE_ENT(SHF_MERGE))
1233       .Case(CASE_ENT(SHF_STRINGS))
1234       .Case(CASE_ENT(SHF_INFO_LINK))
1235       .Case(CASE_ENT(SHF_LINK_ORDER))
1236       .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1237       .Case(CASE_ENT(SHF_GROUP))
1238       .Case(CASE_ENT(SHF_TLS))
1239       .Case(CASE_ENT(SHF_COMPRESSED))
1240       .Case(CASE_ENT(SHF_EXCLUDE))
1241       .Case(CASE_ENT(SHF_ARM_PURECODE))
1242       .Default(None);
1243 #undef CASE_ENT
1244 }
1245 
1246 // Reads the '(' <flags> ')' list of section flags in
1247 // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1248 // following form:
1249 // <flags> ::= <flag>
1250 //           | <flags> & flag
1251 // <flag>  ::= Recognized Flag Name, or Integer value of flag.
1252 // If the first character of <flag> is a ! then this means without flag,
1253 // otherwise with flag.
1254 // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1255 // without flag SHF_WRITE.
1256 std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1257    uint64_t withFlags = 0;
1258    uint64_t withoutFlags = 0;
1259    expect("(");
1260    while (!errorCount()) {
1261     StringRef tok = unquote(next());
1262     bool without = tok.consume_front("!");
1263     if (llvm::Optional<uint64_t> flag = parseFlag(tok)) {
1264       if (without)
1265         withoutFlags |= *flag;
1266       else
1267         withFlags |= *flag;
1268     } else {
1269       setError("unrecognised flag: " + tok);
1270     }
1271     if (consume(")"))
1272       break;
1273     if (!consume("&")) {
1274       next();
1275       setError("expected & or )");
1276     }
1277   }
1278   return std::make_pair(withFlags, withoutFlags);
1279 }
1280 
1281 StringRef ScriptParser::readParenLiteral() {
1282   expect("(");
1283   bool orig = inExpr;
1284   inExpr = false;
1285   StringRef tok = next();
1286   inExpr = orig;
1287   expect(")");
1288   return tok;
1289 }
1290 
1291 static void checkIfExists(const OutputSection &osec, StringRef location) {
1292   if (osec.location.empty() && script->errorOnMissingSection)
1293     error(location + ": undefined section " + osec.name);
1294 }
1295 
1296 static bool isValidSymbolName(StringRef s) {
1297   auto valid = [](char c) {
1298     return isAlnum(c) || c == '$' || c == '.' || c == '_';
1299   };
1300   return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);
1301 }
1302 
1303 Expr ScriptParser::readPrimary() {
1304   if (peek() == "(")
1305     return readParenExpr();
1306 
1307   if (consume("~")) {
1308     Expr e = readPrimary();
1309     return [=] { return ~e().getValue(); };
1310   }
1311   if (consume("!")) {
1312     Expr e = readPrimary();
1313     return [=] { return !e().getValue(); };
1314   }
1315   if (consume("-")) {
1316     Expr e = readPrimary();
1317     return [=] { return -e().getValue(); };
1318   }
1319 
1320   StringRef tok = next();
1321   std::string location = getCurrentLocation();
1322 
1323   // Built-in functions are parsed here.
1324   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1325   if (tok == "ABSOLUTE") {
1326     Expr inner = readParenExpr();
1327     return [=] {
1328       ExprValue i = inner();
1329       i.forceAbsolute = true;
1330       return i;
1331     };
1332   }
1333   if (tok == "ADDR") {
1334     StringRef name = readParenLiteral();
1335     OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1336     osec->usedInExpression = true;
1337     return [=]() -> ExprValue {
1338       checkIfExists(*osec, location);
1339       return {osec, false, 0, location};
1340     };
1341   }
1342   if (tok == "ALIGN") {
1343     expect("(");
1344     Expr e = readExpr();
1345     if (consume(")")) {
1346       e = checkAlignment(e, location);
1347       return [=] { return alignTo(script->getDot(), e().getValue()); };
1348     }
1349     expect(",");
1350     Expr e2 = checkAlignment(readExpr(), location);
1351     expect(")");
1352     return [=] {
1353       ExprValue v = e();
1354       v.alignment = e2().getValue();
1355       return v;
1356     };
1357   }
1358   if (tok == "ALIGNOF") {
1359     StringRef name = readParenLiteral();
1360     OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1361     return [=] {
1362       checkIfExists(*osec, location);
1363       return osec->alignment;
1364     };
1365   }
1366   if (tok == "ASSERT")
1367     return readAssert();
1368   if (tok == "CONSTANT")
1369     return readConstant();
1370   if (tok == "DATA_SEGMENT_ALIGN") {
1371     expect("(");
1372     Expr e = readExpr();
1373     expect(",");
1374     readExpr();
1375     expect(")");
1376     seenDataAlign = true;
1377     return [=] {
1378       return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue()));
1379     };
1380   }
1381   if (tok == "DATA_SEGMENT_END") {
1382     expect("(");
1383     expect(".");
1384     expect(")");
1385     return [] { return script->getDot(); };
1386   }
1387   if (tok == "DATA_SEGMENT_RELRO_END") {
1388     // GNU linkers implements more complicated logic to handle
1389     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1390     // just align to the next page boundary for simplicity.
1391     expect("(");
1392     readExpr();
1393     expect(",");
1394     readExpr();
1395     expect(")");
1396     seenRelroEnd = true;
1397     Expr e = getPageSize();
1398     return [=] { return alignTo(script->getDot(), e().getValue()); };
1399   }
1400   if (tok == "DEFINED") {
1401     StringRef name = unquote(readParenLiteral());
1402     return [=] {
1403       Symbol *b = symtab->find(name);
1404       return (b && b->isDefined()) ? 1 : 0;
1405     };
1406   }
1407   if (tok == "LENGTH") {
1408     StringRef name = readParenLiteral();
1409     if (script->memoryRegions.count(name) == 0) {
1410       setError("memory region not defined: " + name);
1411       return [] { return 0; };
1412     }
1413     return script->memoryRegions[name]->length;
1414   }
1415   if (tok == "LOADADDR") {
1416     StringRef name = readParenLiteral();
1417     OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1418     osec->usedInExpression = true;
1419     return [=] {
1420       checkIfExists(*osec, location);
1421       return osec->getLMA();
1422     };
1423   }
1424   if (tok == "LOG2CEIL") {
1425     expect("(");
1426     Expr a = readExpr();
1427     expect(")");
1428     return [=] {
1429       // LOG2CEIL(0) is defined to be 0.
1430       return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1431     };
1432   }
1433   if (tok == "MAX" || tok == "MIN") {
1434     expect("(");
1435     Expr a = readExpr();
1436     expect(",");
1437     Expr b = readExpr();
1438     expect(")");
1439     if (tok == "MIN")
1440       return [=] { return std::min(a().getValue(), b().getValue()); };
1441     return [=] { return std::max(a().getValue(), b().getValue()); };
1442   }
1443   if (tok == "ORIGIN") {
1444     StringRef name = readParenLiteral();
1445     if (script->memoryRegions.count(name) == 0) {
1446       setError("memory region not defined: " + name);
1447       return [] { return 0; };
1448     }
1449     return script->memoryRegions[name]->origin;
1450   }
1451   if (tok == "SEGMENT_START") {
1452     expect("(");
1453     skip();
1454     expect(",");
1455     Expr e = readExpr();
1456     expect(")");
1457     return [=] { return e(); };
1458   }
1459   if (tok == "SIZEOF") {
1460     StringRef name = readParenLiteral();
1461     OutputSection *cmd = &script->getOrCreateOutputSection(name)->osec;
1462     // Linker script does not create an output section if its content is empty.
1463     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1464     // be empty.
1465     return [=] { return cmd->size; };
1466   }
1467   if (tok == "SIZEOF_HEADERS")
1468     return [=] { return elf::getHeaderSize(); };
1469 
1470   // Tok is the dot.
1471   if (tok == ".")
1472     return [=] { return script->getSymbolValue(tok, location); };
1473 
1474   // Tok is a literal number.
1475   if (Optional<uint64_t> val = parseInt(tok))
1476     return [=] { return *val; };
1477 
1478   // Tok is a symbol name.
1479   if (tok.startswith("\""))
1480     tok = unquote(tok);
1481   else if (!isValidSymbolName(tok))
1482     setError("malformed number: " + tok);
1483   script->referencedSymbols.push_back(tok);
1484   return [=] { return script->getSymbolValue(tok, location); };
1485 }
1486 
1487 Expr ScriptParser::readTernary(Expr cond) {
1488   Expr l = readExpr();
1489   expect(":");
1490   Expr r = readExpr();
1491   return [=] { return cond().getValue() ? l() : r(); };
1492 }
1493 
1494 Expr ScriptParser::readParenExpr() {
1495   expect("(");
1496   Expr e = readExpr();
1497   expect(")");
1498   return e;
1499 }
1500 
1501 SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() {
1502   SmallVector<StringRef, 0> phdrs;
1503   while (!errorCount() && peek().startswith(":")) {
1504     StringRef tok = next();
1505     phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
1506   }
1507   return phdrs;
1508 }
1509 
1510 // Read a program header type name. The next token must be a
1511 // name of a program header type or a constant (e.g. "0x3").
1512 unsigned ScriptParser::readPhdrType() {
1513   StringRef tok = next();
1514   if (Optional<uint64_t> val = parseInt(tok))
1515     return *val;
1516 
1517   unsigned ret = StringSwitch<unsigned>(tok)
1518                      .Case("PT_NULL", PT_NULL)
1519                      .Case("PT_LOAD", PT_LOAD)
1520                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1521                      .Case("PT_INTERP", PT_INTERP)
1522                      .Case("PT_NOTE", PT_NOTE)
1523                      .Case("PT_SHLIB", PT_SHLIB)
1524                      .Case("PT_PHDR", PT_PHDR)
1525                      .Case("PT_TLS", PT_TLS)
1526                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1527                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1528                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1529                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1530                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1531                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1532                      .Default(-1);
1533 
1534   if (ret == (unsigned)-1) {
1535     setError("invalid program header type: " + tok);
1536     return PT_NULL;
1537   }
1538   return ret;
1539 }
1540 
1541 // Reads an anonymous version declaration.
1542 void ScriptParser::readAnonymousDeclaration() {
1543   SmallVector<SymbolVersion, 0> locals;
1544   SmallVector<SymbolVersion, 0> globals;
1545   std::tie(locals, globals) = readSymbols();
1546   for (const SymbolVersion &pat : locals)
1547     config->versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(pat);
1548   for (const SymbolVersion &pat : globals)
1549     config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(pat);
1550 
1551   expect(";");
1552 }
1553 
1554 // Reads a non-anonymous version definition,
1555 // e.g. "VerStr { global: foo; bar; local: *; };".
1556 void ScriptParser::readVersionDeclaration(StringRef verStr) {
1557   // Read a symbol list.
1558   SmallVector<SymbolVersion, 0> locals;
1559   SmallVector<SymbolVersion, 0> globals;
1560   std::tie(locals, globals) = readSymbols();
1561 
1562   // Create a new version definition and add that to the global symbols.
1563   VersionDefinition ver;
1564   ver.name = verStr;
1565   ver.nonLocalPatterns = std::move(globals);
1566   ver.localPatterns = std::move(locals);
1567   ver.id = config->versionDefinitions.size();
1568   config->versionDefinitions.push_back(ver);
1569 
1570   // Each version may have a parent version. For example, "Ver2"
1571   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1572   // as a parent. This version hierarchy is, probably against your
1573   // instinct, purely for hint; the runtime doesn't care about it
1574   // at all. In LLD, we simply ignore it.
1575   if (next() != ";")
1576     expect(";");
1577 }
1578 
1579 bool elf::hasWildcard(StringRef s) {
1580   return s.find_first_of("?*[") != StringRef::npos;
1581 }
1582 
1583 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1584 std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
1585 ScriptParser::readSymbols() {
1586   SmallVector<SymbolVersion, 0> locals;
1587   SmallVector<SymbolVersion, 0> globals;
1588   SmallVector<SymbolVersion, 0> *v = &globals;
1589 
1590   while (!errorCount()) {
1591     if (consume("}"))
1592       break;
1593     if (consumeLabel("local")) {
1594       v = &locals;
1595       continue;
1596     }
1597     if (consumeLabel("global")) {
1598       v = &globals;
1599       continue;
1600     }
1601 
1602     if (consume("extern")) {
1603       SmallVector<SymbolVersion, 0> ext = readVersionExtern();
1604       v->insert(v->end(), ext.begin(), ext.end());
1605     } else {
1606       StringRef tok = next();
1607       v->push_back({unquote(tok), false, hasWildcard(tok)});
1608     }
1609     expect(";");
1610   }
1611   return {locals, globals};
1612 }
1613 
1614 // Reads an "extern C++" directive, e.g.,
1615 // "extern "C++" { ns::*; "f(int, double)"; };"
1616 //
1617 // The last semicolon is optional. E.g. this is OK:
1618 // "extern "C++" { ns::*; "f(int, double)" };"
1619 SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() {
1620   StringRef tok = next();
1621   bool isCXX = tok == "\"C++\"";
1622   if (!isCXX && tok != "\"C\"")
1623     setError("Unknown language");
1624   expect("{");
1625 
1626   SmallVector<SymbolVersion, 0> ret;
1627   while (!errorCount() && peek() != "}") {
1628     StringRef tok = next();
1629     ret.push_back(
1630         {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)});
1631     if (consume("}"))
1632       return ret;
1633     expect(";");
1634   }
1635 
1636   expect("}");
1637   return ret;
1638 }
1639 
1640 Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
1641                                         StringRef s3) {
1642   if (!consume(s1) && !consume(s2) && !consume(s3)) {
1643     setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
1644     return [] { return 0; };
1645   }
1646   expect("=");
1647   return readExpr();
1648 }
1649 
1650 // Parse the MEMORY command as specified in:
1651 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1652 //
1653 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1654 void ScriptParser::readMemory() {
1655   expect("{");
1656   while (!errorCount() && !consume("}")) {
1657     StringRef tok = next();
1658     if (tok == "INCLUDE") {
1659       readInclude();
1660       continue;
1661     }
1662 
1663     uint32_t flags = 0;
1664     uint32_t invFlags = 0;
1665     uint32_t negFlags = 0;
1666     uint32_t negInvFlags = 0;
1667     if (consume("(")) {
1668       readMemoryAttributes(flags, invFlags, negFlags, negInvFlags);
1669       expect(")");
1670     }
1671     expect(":");
1672 
1673     Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
1674     expect(",");
1675     Expr length = readMemoryAssignment("LENGTH", "len", "l");
1676 
1677     // Add the memory region to the region map.
1678     MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, invFlags,
1679                                           negFlags, negInvFlags);
1680     if (!script->memoryRegions.insert({tok, mr}).second)
1681       setError("region '" + tok + "' already defined");
1682   }
1683 }
1684 
1685 // This function parses the attributes used to match against section
1686 // flags when placing output sections in a memory region. These flags
1687 // are only used when an explicit memory region name is not used.
1688 void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
1689                                         uint32_t &negFlags,
1690                                         uint32_t &negInvFlags) {
1691   bool invert = false;
1692 
1693   for (char c : next().lower()) {
1694     if (c == '!') {
1695       invert = !invert;
1696       std::swap(flags, negFlags);
1697       std::swap(invFlags, negInvFlags);
1698       continue;
1699     }
1700     if (c == 'w')
1701       flags |= SHF_WRITE;
1702     else if (c == 'x')
1703       flags |= SHF_EXECINSTR;
1704     else if (c == 'a')
1705       flags |= SHF_ALLOC;
1706     else if (c == 'r')
1707       invFlags |= SHF_WRITE;
1708     else
1709       setError("invalid memory region attribute");
1710   }
1711 
1712   if (invert) {
1713     std::swap(flags, negFlags);
1714     std::swap(invFlags, negInvFlags);
1715   }
1716 }
1717 
1718 void elf::readLinkerScript(MemoryBufferRef mb) {
1719   llvm::TimeTraceScope timeScope("Read linker script",
1720                                  mb.getBufferIdentifier());
1721   ScriptParser(mb).readLinkerScript();
1722 }
1723 
1724 void elf::readVersionScript(MemoryBufferRef mb) {
1725   llvm::TimeTraceScope timeScope("Read version script",
1726                                  mb.getBufferIdentifier());
1727   ScriptParser(mb).readVersionScript();
1728 }
1729 
1730 void elf::readDynamicList(MemoryBufferRef mb) {
1731   llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
1732   ScriptParser(mb).readDynamicList();
1733 }
1734 
1735 void elf::readDefsym(StringRef name, MemoryBufferRef mb) {
1736   llvm::TimeTraceScope timeScope("Read defsym input", name);
1737   ScriptParser(mb).readDefsym(name);
1738 }
1739