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