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