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