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