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