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