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