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