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("*", "/", "%", 8)
640       .Cases("+", "-", 7)
641       .Cases("<<", ">>", 6)
642       .Cases("<", "<=", ">", ">=", "==", "!=", 5)
643       .Case("&", 4)
644       .Case("|", 3)
645       .Case("&&", 2)
646       .Case("||", 1)
647       .Default(-1);
648 }
649 
650 StringMatcher ScriptParser::readFilePatterns() {
651   StringMatcher Matcher;
652 
653   while (!errorCount() && !consume(")"))
654     Matcher.addPattern(SingleStringMatcher(next()));
655   return Matcher;
656 }
657 
658 SortSectionPolicy ScriptParser::peekSortKind() {
659   return StringSwitch<SortSectionPolicy>(peek())
660       .Cases("SORT", "SORT_BY_NAME", SortSectionPolicy::Name)
661       .Case("SORT_BY_ALIGNMENT", SortSectionPolicy::Alignment)
662       .Case("SORT_BY_INIT_PRIORITY", SortSectionPolicy::Priority)
663       .Case("SORT_NONE", SortSectionPolicy::None)
664       .Default(SortSectionPolicy::Default);
665 }
666 
667 SortSectionPolicy ScriptParser::readSortKind() {
668   SortSectionPolicy ret = peekSortKind();
669   if (ret != SortSectionPolicy::Default)
670     skip();
671   return ret;
672 }
673 
674 // Reads SECTIONS command contents in the following form:
675 //
676 // <contents> ::= <elem>*
677 // <elem>     ::= <exclude>? <glob-pattern>
678 // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
679 //
680 // For example,
681 //
682 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
683 //
684 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
685 // The semantics of that is section .foo in any file, section .bar in
686 // any file but a.o, and section .baz in any file but b.o.
687 SmallVector<SectionPattern, 0> ScriptParser::readInputSectionsList() {
688   SmallVector<SectionPattern, 0> ret;
689   while (!errorCount() && peek() != ")") {
690     StringMatcher excludeFilePat;
691     if (consume("EXCLUDE_FILE")) {
692       expect("(");
693       excludeFilePat = readFilePatterns();
694     }
695 
696     StringMatcher SectionMatcher;
697     // Break if the next token is ), EXCLUDE_FILE, or SORT*.
698     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE" &&
699            peekSortKind() == SortSectionPolicy::Default)
700       SectionMatcher.addPattern(unquote(next()));
701 
702     if (!SectionMatcher.empty())
703       ret.push_back({std::move(excludeFilePat), std::move(SectionMatcher)});
704     else if (excludeFilePat.empty())
705       break;
706     else
707       setError("section pattern is expected");
708   }
709   return ret;
710 }
711 
712 // Reads contents of "SECTIONS" directive. That directive contains a
713 // list of glob patterns for input sections. The grammar is as follows.
714 //
715 // <patterns> ::= <section-list>
716 //              | <sort> "(" <section-list> ")"
717 //              | <sort> "(" <sort> "(" <section-list> ")" ")"
718 //
719 // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
720 //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
721 //
722 // <section-list> is parsed by readInputSectionsList().
723 InputSectionDescription *
724 ScriptParser::readInputSectionRules(StringRef filePattern, uint64_t withFlags,
725                                     uint64_t withoutFlags) {
726   auto *cmd =
727       make<InputSectionDescription>(filePattern, withFlags, withoutFlags);
728   expect("(");
729 
730   while (!errorCount() && !consume(")")) {
731     SortSectionPolicy outer = readSortKind();
732     SortSectionPolicy inner = SortSectionPolicy::Default;
733     SmallVector<SectionPattern, 0> v;
734     if (outer != SortSectionPolicy::Default) {
735       expect("(");
736       inner = readSortKind();
737       if (inner != SortSectionPolicy::Default) {
738         expect("(");
739         v = readInputSectionsList();
740         expect(")");
741       } else {
742         v = readInputSectionsList();
743       }
744       expect(")");
745     } else {
746       v = readInputSectionsList();
747     }
748 
749     for (SectionPattern &pat : v) {
750       pat.sortInner = inner;
751       pat.sortOuter = outer;
752     }
753 
754     std::move(v.begin(), v.end(), std::back_inserter(cmd->sectionPatterns));
755   }
756   return cmd;
757 }
758 
759 InputSectionDescription *
760 ScriptParser::readInputSectionDescription(StringRef tok) {
761   // Input section wildcard can be surrounded by KEEP.
762   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
763   uint64_t withFlags = 0;
764   uint64_t withoutFlags = 0;
765   if (tok == "KEEP") {
766     expect("(");
767     if (consume("INPUT_SECTION_FLAGS"))
768       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
769     InputSectionDescription *cmd =
770         readInputSectionRules(next(), withFlags, withoutFlags);
771     expect(")");
772     script->keptSections.push_back(cmd);
773     return cmd;
774   }
775   if (tok == "INPUT_SECTION_FLAGS") {
776     std::tie(withFlags, withoutFlags) = readInputSectionFlags();
777     tok = next();
778   }
779   return readInputSectionRules(tok, withFlags, withoutFlags);
780 }
781 
782 void ScriptParser::readSort() {
783   expect("(");
784   expect("CONSTRUCTORS");
785   expect(")");
786 }
787 
788 Expr ScriptParser::readAssert() {
789   expect("(");
790   Expr e = readExpr();
791   expect(",");
792   StringRef msg = unquote(next());
793   expect(")");
794 
795   return [=] {
796     if (!e().getValue())
797       errorOrWarn(msg);
798     return script->getDot();
799   };
800 }
801 
802 #define ECase(X)                                                               \
803   { #X, X }
804 constexpr std::pair<const char *, unsigned> typeMap[] = {
805     ECase(SHT_PROGBITS),   ECase(SHT_NOTE),       ECase(SHT_NOBITS),
806     ECase(SHT_INIT_ARRAY), ECase(SHT_FINI_ARRAY), ECase(SHT_PREINIT_ARRAY),
807 };
808 #undef ECase
809 
810 // Tries to read the special directive for an output section definition which
811 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)", "(OVERLAY)", and
812 // "(TYPE=<value>)".
813 // Tok1 and Tok2 are next 2 tokens peeked. See comment for
814 // readSectionAddressType below.
815 bool ScriptParser::readSectionDirective(OutputSection *cmd, StringRef tok1, StringRef tok2) {
816   if (tok1 != "(")
817     return false;
818   if (tok2 != "NOLOAD" && tok2 != "COPY" && tok2 != "INFO" &&
819       tok2 != "OVERLAY" && tok2 != "TYPE")
820     return false;
821 
822   expect("(");
823   if (consume("NOLOAD")) {
824     cmd->type = SHT_NOBITS;
825     cmd->typeIsSet = true;
826   } else if (consume("TYPE")) {
827     expect("=");
828     StringRef value = peek();
829     auto it = llvm::find_if(typeMap, [=](auto e) { return e.first == value; });
830     if (it != std::end(typeMap)) {
831       // The value is a recognized literal SHT_*.
832       cmd->type = it->second;
833       skip();
834     } else if (value.startswith("SHT_")) {
835       setError("unknown section type " + value);
836     } else {
837       // Otherwise, read an expression.
838       cmd->type = readExpr()().getValue();
839     }
840     cmd->typeIsSet = true;
841   } else {
842     skip(); // This is "COPY", "INFO" or "OVERLAY".
843     cmd->nonAlloc = true;
844   }
845   expect(")");
846   return true;
847 }
848 
849 // Reads an expression and/or the special directive for an output
850 // section definition. Directive is one of following: "(NOLOAD)",
851 // "(COPY)", "(INFO)" or "(OVERLAY)".
852 //
853 // An output section name can be followed by an address expression
854 // and/or directive. This grammar is not LL(1) because "(" can be
855 // interpreted as either the beginning of some expression or beginning
856 // of directive.
857 //
858 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
859 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
860 void ScriptParser::readSectionAddressType(OutputSection *cmd) {
861   // Temporarily set inExpr to support TYPE=<value> without spaces.
862   bool saved = std::exchange(inExpr, true);
863   bool isDirective = readSectionDirective(cmd, peek(), peek2());
864   inExpr = saved;
865   if (isDirective)
866     return;
867 
868   cmd->addrExpr = readExpr();
869   if (peek() == "(" && !readSectionDirective(cmd, "(", peek2()))
870     setError("unknown section directive: " + peek2());
871 }
872 
873 static Expr checkAlignment(Expr e, std::string &loc) {
874   return [=] {
875     uint64_t alignment = std::max((uint64_t)1, e().getValue());
876     if (!isPowerOf2_64(alignment)) {
877       error(loc + ": alignment must be power of 2");
878       return (uint64_t)1; // Return a dummy value.
879     }
880     return alignment;
881   };
882 }
883 
884 OutputDesc *ScriptParser::readOverlaySectionDescription() {
885   OutputDesc *osd = script->createOutputSection(next(), getCurrentLocation());
886   osd->osec.inOverlay = true;
887   expect("{");
888   while (!errorCount() && !consume("}")) {
889     uint64_t withFlags = 0;
890     uint64_t withoutFlags = 0;
891     if (consume("INPUT_SECTION_FLAGS"))
892       std::tie(withFlags, withoutFlags) = readInputSectionFlags();
893     osd->osec.commands.push_back(
894         readInputSectionRules(next(), withFlags, withoutFlags));
895   }
896   return osd;
897 }
898 
899 OutputDesc *ScriptParser::readOutputSectionDescription(StringRef outSec) {
900   OutputDesc *cmd = script->createOutputSection(outSec, getCurrentLocation());
901   OutputSection *osec = &cmd->osec;
902   // Maybe relro. Will reset to false if DATA_SEGMENT_RELRO_END is absent.
903   osec->relro = seenDataAlign && !seenRelroEnd;
904 
905   size_t symbolsReferenced = script->referencedSymbols.size();
906 
907   if (peek() != ":")
908     readSectionAddressType(osec);
909   expect(":");
910 
911   std::string location = getCurrentLocation();
912   if (consume("AT"))
913     osec->lmaExpr = readParenExpr();
914   if (consume("ALIGN"))
915     osec->alignExpr = checkAlignment(readParenExpr(), location);
916   if (consume("SUBALIGN"))
917     osec->subalignExpr = checkAlignment(readParenExpr(), location);
918 
919   // Parse constraints.
920   if (consume("ONLY_IF_RO"))
921     osec->constraint = ConstraintKind::ReadOnly;
922   if (consume("ONLY_IF_RW"))
923     osec->constraint = ConstraintKind::ReadWrite;
924   expect("{");
925 
926   while (!errorCount() && !consume("}")) {
927     StringRef tok = next();
928     if (tok == ";") {
929       // Empty commands are allowed. Do nothing here.
930     } else if (SymbolAssignment *assign = readAssignment(tok)) {
931       osec->commands.push_back(assign);
932     } else if (ByteCommand *data = readByteCommand(tok)) {
933       osec->commands.push_back(data);
934     } else if (tok == "CONSTRUCTORS") {
935       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
936       // by name. This is for very old file formats such as ECOFF/XCOFF.
937       // For ELF, we should ignore.
938     } else if (tok == "FILL") {
939       // We handle the FILL command as an alias for =fillexp section attribute,
940       // which is different from what GNU linkers do.
941       // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
942       if (peek() != "(")
943         setError("( expected, but got " + peek());
944       osec->filler = readFill();
945     } else if (tok == "SORT") {
946       readSort();
947     } else if (tok == "INCLUDE") {
948       readInclude();
949     } else if (tok == "(" || tok == ")") {
950       setError("expected filename pattern");
951     } else if (peek() == "(") {
952       osec->commands.push_back(readInputSectionDescription(tok));
953     } else {
954       // We have a file name and no input sections description. It is not a
955       // commonly used syntax, but still acceptable. In that case, all sections
956       // from the file will be included.
957       // FIXME: GNU ld permits INPUT_SECTION_FLAGS to be used here. We do not
958       // handle this case here as it will already have been matched by the
959       // case above.
960       auto *isd = make<InputSectionDescription>(tok);
961       isd->sectionPatterns.push_back({{}, StringMatcher("*")});
962       osec->commands.push_back(isd);
963     }
964   }
965 
966   if (consume(">"))
967     osec->memoryRegionName = std::string(next());
968 
969   if (consume("AT")) {
970     expect(">");
971     osec->lmaRegionName = std::string(next());
972   }
973 
974   if (osec->lmaExpr && !osec->lmaRegionName.empty())
975     error("section can't have both LMA and a load region");
976 
977   osec->phdrs = readOutputSectionPhdrs();
978 
979   if (peek() == "=" || peek().startswith("=")) {
980     inExpr = true;
981     consume("=");
982     osec->filler = readFill();
983     inExpr = false;
984   }
985 
986   // Consume optional comma following output section command.
987   consume(",");
988 
989   if (script->referencedSymbols.size() > symbolsReferenced)
990     osec->expressionsUseSymbols = true;
991   return cmd;
992 }
993 
994 // Reads a `=<fillexp>` expression and returns its value as a big-endian number.
995 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
996 // We do not support using symbols in such expressions.
997 //
998 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
999 // size, while ld.gold always handles it as a 32-bit big-endian number.
1000 // We are compatible with ld.gold because it's easier to implement.
1001 // Also, we require that expressions with operators must be wrapped into
1002 // round brackets. We did it to resolve the ambiguity when parsing scripts like:
1003 // SECTIONS { .foo : { ... } =120+3 /DISCARD/ : { ... } }
1004 std::array<uint8_t, 4> ScriptParser::readFill() {
1005   uint64_t value = readPrimary()().val;
1006   if (value > UINT32_MAX)
1007     setError("filler expression result does not fit 32-bit: 0x" +
1008              Twine::utohexstr(value));
1009 
1010   std::array<uint8_t, 4> buf;
1011   write32be(buf.data(), (uint32_t)value);
1012   return buf;
1013 }
1014 
1015 SymbolAssignment *ScriptParser::readProvideHidden(bool provide, bool hidden) {
1016   expect("(");
1017   SymbolAssignment *cmd = readSymbolAssignment(next());
1018   cmd->provide = provide;
1019   cmd->hidden = hidden;
1020   expect(")");
1021   return cmd;
1022 }
1023 
1024 SymbolAssignment *ScriptParser::readAssignment(StringRef tok) {
1025   // Assert expression returns Dot, so this is equal to ".=."
1026   if (tok == "ASSERT")
1027     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
1028 
1029   size_t oldPos = pos;
1030   SymbolAssignment *cmd = nullptr;
1031   if (peek() == "=" || peek() == "+=")
1032     cmd = readSymbolAssignment(tok);
1033   else if (tok == "PROVIDE")
1034     cmd = readProvideHidden(true, false);
1035   else if (tok == "HIDDEN")
1036     cmd = readProvideHidden(false, true);
1037   else if (tok == "PROVIDE_HIDDEN")
1038     cmd = readProvideHidden(true, true);
1039 
1040   if (cmd) {
1041     cmd->commandString =
1042         tok.str() + " " +
1043         llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1044     expect(";");
1045   }
1046   return cmd;
1047 }
1048 
1049 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef name) {
1050   name = unquote(name);
1051   StringRef op = next();
1052   assert(op == "=" || op == "+=");
1053   Expr e = readExpr();
1054   if (op == "+=") {
1055     std::string loc = getCurrentLocation();
1056     e = [=] { return add(script->getSymbolValue(name, loc), e()); };
1057   }
1058   return make<SymbolAssignment>(name, e, getCurrentLocation());
1059 }
1060 
1061 // This is an operator-precedence parser to parse a linker
1062 // script expression.
1063 Expr ScriptParser::readExpr() {
1064   // Our lexer is context-aware. Set the in-expression bit so that
1065   // they apply different tokenization rules.
1066   bool orig = inExpr;
1067   inExpr = true;
1068   Expr e = readExpr1(readPrimary(), 0);
1069   inExpr = orig;
1070   return e;
1071 }
1072 
1073 Expr ScriptParser::combine(StringRef op, Expr l, Expr r) {
1074   if (op == "+")
1075     return [=] { return add(l(), r()); };
1076   if (op == "-")
1077     return [=] { return sub(l(), r()); };
1078   if (op == "*")
1079     return [=] { return l().getValue() * r().getValue(); };
1080   if (op == "/") {
1081     std::string loc = getCurrentLocation();
1082     return [=]() -> uint64_t {
1083       if (uint64_t rv = r().getValue())
1084         return l().getValue() / rv;
1085       error(loc + ": division by zero");
1086       return 0;
1087     };
1088   }
1089   if (op == "%") {
1090     std::string loc = getCurrentLocation();
1091     return [=]() -> uint64_t {
1092       if (uint64_t rv = r().getValue())
1093         return l().getValue() % rv;
1094       error(loc + ": modulo by zero");
1095       return 0;
1096     };
1097   }
1098   if (op == "<<")
1099     return [=] { return l().getValue() << r().getValue(); };
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 bitAnd(l(), r()); };
1120   if (op == "|")
1121     return [=] { return bitOr(l(), r()); };
1122   llvm_unreachable("invalid operator");
1123 }
1124 
1125 // This is a part of the operator-precedence parser. This function
1126 // assumes that the remaining token stream starts with an operator.
1127 Expr ScriptParser::readExpr1(Expr lhs, int minPrec) {
1128   while (!atEOF() && !errorCount()) {
1129     // Read an operator and an expression.
1130     if (consume("?"))
1131       return readTernary(lhs);
1132     StringRef op1 = peek();
1133     if (precedence(op1) < minPrec)
1134       break;
1135     skip();
1136     Expr rhs = readPrimary();
1137 
1138     // Evaluate the remaining part of the expression first if the
1139     // next operator has greater precedence than the previous one.
1140     // For example, if we have read "+" and "3", and if the next
1141     // operator is "*", then we'll evaluate 3 * ... part first.
1142     while (!atEOF()) {
1143       StringRef op2 = peek();
1144       if (precedence(op2) <= precedence(op1))
1145         break;
1146       rhs = readExpr1(rhs, precedence(op2));
1147     }
1148 
1149     lhs = combine(op1, lhs, rhs);
1150   }
1151   return lhs;
1152 }
1153 
1154 Expr ScriptParser::getPageSize() {
1155   std::string location = getCurrentLocation();
1156   return [=]() -> uint64_t {
1157     if (target)
1158       return config->commonPageSize;
1159     error(location + ": unable to calculate page size");
1160     return 4096; // Return a dummy value.
1161   };
1162 }
1163 
1164 Expr ScriptParser::readConstant() {
1165   StringRef s = readParenLiteral();
1166   if (s == "COMMONPAGESIZE")
1167     return getPageSize();
1168   if (s == "MAXPAGESIZE")
1169     return [] { return config->maxPageSize; };
1170   setError("unknown constant: " + s);
1171   return [] { return 0; };
1172 }
1173 
1174 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1175 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1176 // have "K" (Ki) or "M" (Mi) suffixes.
1177 static Optional<uint64_t> parseInt(StringRef tok) {
1178   // Hexadecimal
1179   uint64_t val;
1180   if (tok.startswith_insensitive("0x")) {
1181     if (!to_integer(tok.substr(2), val, 16))
1182       return None;
1183     return val;
1184   }
1185   if (tok.endswith_insensitive("H")) {
1186     if (!to_integer(tok.drop_back(), val, 16))
1187       return None;
1188     return val;
1189   }
1190 
1191   // Decimal
1192   if (tok.endswith_insensitive("K")) {
1193     if (!to_integer(tok.drop_back(), val, 10))
1194       return None;
1195     return val * 1024;
1196   }
1197   if (tok.endswith_insensitive("M")) {
1198     if (!to_integer(tok.drop_back(), val, 10))
1199       return None;
1200     return val * 1024 * 1024;
1201   }
1202   if (!to_integer(tok, val, 10))
1203     return None;
1204   return val;
1205 }
1206 
1207 ByteCommand *ScriptParser::readByteCommand(StringRef tok) {
1208   int size = StringSwitch<int>(tok)
1209                  .Case("BYTE", 1)
1210                  .Case("SHORT", 2)
1211                  .Case("LONG", 4)
1212                  .Case("QUAD", 8)
1213                  .Default(-1);
1214   if (size == -1)
1215     return nullptr;
1216 
1217   size_t oldPos = pos;
1218   Expr e = readParenExpr();
1219   std::string commandString =
1220       tok.str() + " " +
1221       llvm::join(tokens.begin() + oldPos, tokens.begin() + pos, " ");
1222   return make<ByteCommand>(e, size, commandString);
1223 }
1224 
1225 static llvm::Optional<uint64_t> parseFlag(StringRef tok) {
1226   if (llvm::Optional<uint64_t> asInt = parseInt(tok))
1227     return asInt;
1228 #define CASE_ENT(enum) #enum, ELF::enum
1229   return StringSwitch<llvm::Optional<uint64_t>>(tok)
1230       .Case(CASE_ENT(SHF_WRITE))
1231       .Case(CASE_ENT(SHF_ALLOC))
1232       .Case(CASE_ENT(SHF_EXECINSTR))
1233       .Case(CASE_ENT(SHF_MERGE))
1234       .Case(CASE_ENT(SHF_STRINGS))
1235       .Case(CASE_ENT(SHF_INFO_LINK))
1236       .Case(CASE_ENT(SHF_LINK_ORDER))
1237       .Case(CASE_ENT(SHF_OS_NONCONFORMING))
1238       .Case(CASE_ENT(SHF_GROUP))
1239       .Case(CASE_ENT(SHF_TLS))
1240       .Case(CASE_ENT(SHF_COMPRESSED))
1241       .Case(CASE_ENT(SHF_EXCLUDE))
1242       .Case(CASE_ENT(SHF_ARM_PURECODE))
1243       .Default(None);
1244 #undef CASE_ENT
1245 }
1246 
1247 // Reads the '(' <flags> ')' list of section flags in
1248 // INPUT_SECTION_FLAGS '(' <flags> ')' in the
1249 // following form:
1250 // <flags> ::= <flag>
1251 //           | <flags> & flag
1252 // <flag>  ::= Recognized Flag Name, or Integer value of flag.
1253 // If the first character of <flag> is a ! then this means without flag,
1254 // otherwise with flag.
1255 // Example: SHF_EXECINSTR & !SHF_WRITE means with flag SHF_EXECINSTR and
1256 // without flag SHF_WRITE.
1257 std::pair<uint64_t, uint64_t> ScriptParser::readInputSectionFlags() {
1258    uint64_t withFlags = 0;
1259    uint64_t withoutFlags = 0;
1260    expect("(");
1261    while (!errorCount()) {
1262     StringRef tok = unquote(next());
1263     bool without = tok.consume_front("!");
1264     if (llvm::Optional<uint64_t> flag = parseFlag(tok)) {
1265       if (without)
1266         withoutFlags |= *flag;
1267       else
1268         withFlags |= *flag;
1269     } else {
1270       setError("unrecognised flag: " + tok);
1271     }
1272     if (consume(")"))
1273       break;
1274     if (!consume("&")) {
1275       next();
1276       setError("expected & or )");
1277     }
1278   }
1279   return std::make_pair(withFlags, withoutFlags);
1280 }
1281 
1282 StringRef ScriptParser::readParenLiteral() {
1283   expect("(");
1284   bool orig = inExpr;
1285   inExpr = false;
1286   StringRef tok = next();
1287   inExpr = orig;
1288   expect(")");
1289   return tok;
1290 }
1291 
1292 static void checkIfExists(const OutputSection &osec, StringRef location) {
1293   if (osec.location.empty() && script->errorOnMissingSection)
1294     error(location + ": undefined section " + osec.name);
1295 }
1296 
1297 static bool isValidSymbolName(StringRef s) {
1298   auto valid = [](char c) {
1299     return isAlnum(c) || c == '$' || c == '.' || c == '_';
1300   };
1301   return !s.empty() && !isDigit(s[0]) && llvm::all_of(s, valid);
1302 }
1303 
1304 Expr ScriptParser::readPrimary() {
1305   if (peek() == "(")
1306     return readParenExpr();
1307 
1308   if (consume("~")) {
1309     Expr e = readPrimary();
1310     return [=] { return ~e().getValue(); };
1311   }
1312   if (consume("!")) {
1313     Expr e = readPrimary();
1314     return [=] { return !e().getValue(); };
1315   }
1316   if (consume("-")) {
1317     Expr e = readPrimary();
1318     return [=] { return -e().getValue(); };
1319   }
1320 
1321   StringRef tok = next();
1322   std::string location = getCurrentLocation();
1323 
1324   // Built-in functions are parsed here.
1325   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1326   if (tok == "ABSOLUTE") {
1327     Expr inner = readParenExpr();
1328     return [=] {
1329       ExprValue i = inner();
1330       i.forceAbsolute = true;
1331       return i;
1332     };
1333   }
1334   if (tok == "ADDR") {
1335     StringRef name = readParenLiteral();
1336     OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1337     osec->usedInExpression = true;
1338     return [=]() -> ExprValue {
1339       checkIfExists(*osec, location);
1340       return {osec, false, 0, location};
1341     };
1342   }
1343   if (tok == "ALIGN") {
1344     expect("(");
1345     Expr e = readExpr();
1346     if (consume(")")) {
1347       e = checkAlignment(e, location);
1348       return [=] { return alignTo(script->getDot(), e().getValue()); };
1349     }
1350     expect(",");
1351     Expr e2 = checkAlignment(readExpr(), location);
1352     expect(")");
1353     return [=] {
1354       ExprValue v = e();
1355       v.alignment = e2().getValue();
1356       return v;
1357     };
1358   }
1359   if (tok == "ALIGNOF") {
1360     StringRef name = readParenLiteral();
1361     OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1362     return [=] {
1363       checkIfExists(*osec, location);
1364       return osec->alignment;
1365     };
1366   }
1367   if (tok == "ASSERT")
1368     return readAssert();
1369   if (tok == "CONSTANT")
1370     return readConstant();
1371   if (tok == "DATA_SEGMENT_ALIGN") {
1372     expect("(");
1373     Expr e = readExpr();
1374     expect(",");
1375     readExpr();
1376     expect(")");
1377     seenDataAlign = true;
1378     return [=] {
1379       return alignTo(script->getDot(), std::max((uint64_t)1, e().getValue()));
1380     };
1381   }
1382   if (tok == "DATA_SEGMENT_END") {
1383     expect("(");
1384     expect(".");
1385     expect(")");
1386     return [] { return script->getDot(); };
1387   }
1388   if (tok == "DATA_SEGMENT_RELRO_END") {
1389     // GNU linkers implements more complicated logic to handle
1390     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1391     // just align to the next page boundary for simplicity.
1392     expect("(");
1393     readExpr();
1394     expect(",");
1395     readExpr();
1396     expect(")");
1397     seenRelroEnd = true;
1398     Expr e = getPageSize();
1399     return [=] { return alignTo(script->getDot(), e().getValue()); };
1400   }
1401   if (tok == "DEFINED") {
1402     StringRef name = unquote(readParenLiteral());
1403     return [=] {
1404       Symbol *b = symtab->find(name);
1405       return (b && b->isDefined()) ? 1 : 0;
1406     };
1407   }
1408   if (tok == "LENGTH") {
1409     StringRef name = readParenLiteral();
1410     if (script->memoryRegions.count(name) == 0) {
1411       setError("memory region not defined: " + name);
1412       return [] { return 0; };
1413     }
1414     return script->memoryRegions[name]->length;
1415   }
1416   if (tok == "LOADADDR") {
1417     StringRef name = readParenLiteral();
1418     OutputSection *osec = &script->getOrCreateOutputSection(name)->osec;
1419     osec->usedInExpression = true;
1420     return [=] {
1421       checkIfExists(*osec, location);
1422       return osec->getLMA();
1423     };
1424   }
1425   if (tok == "LOG2CEIL") {
1426     expect("(");
1427     Expr a = readExpr();
1428     expect(")");
1429     return [=] {
1430       // LOG2CEIL(0) is defined to be 0.
1431       return llvm::Log2_64_Ceil(std::max(a().getValue(), UINT64_C(1)));
1432     };
1433   }
1434   if (tok == "MAX" || tok == "MIN") {
1435     expect("(");
1436     Expr a = readExpr();
1437     expect(",");
1438     Expr b = readExpr();
1439     expect(")");
1440     if (tok == "MIN")
1441       return [=] { return std::min(a().getValue(), b().getValue()); };
1442     return [=] { return std::max(a().getValue(), b().getValue()); };
1443   }
1444   if (tok == "ORIGIN") {
1445     StringRef name = readParenLiteral();
1446     if (script->memoryRegions.count(name) == 0) {
1447       setError("memory region not defined: " + name);
1448       return [] { return 0; };
1449     }
1450     return script->memoryRegions[name]->origin;
1451   }
1452   if (tok == "SEGMENT_START") {
1453     expect("(");
1454     skip();
1455     expect(",");
1456     Expr e = readExpr();
1457     expect(")");
1458     return [=] { return e(); };
1459   }
1460   if (tok == "SIZEOF") {
1461     StringRef name = readParenLiteral();
1462     OutputSection *cmd = &script->getOrCreateOutputSection(name)->osec;
1463     // Linker script does not create an output section if its content is empty.
1464     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1465     // be empty.
1466     return [=] { return cmd->size; };
1467   }
1468   if (tok == "SIZEOF_HEADERS")
1469     return [=] { return elf::getHeaderSize(); };
1470 
1471   // Tok is the dot.
1472   if (tok == ".")
1473     return [=] { return script->getSymbolValue(tok, location); };
1474 
1475   // Tok is a literal number.
1476   if (Optional<uint64_t> val = parseInt(tok))
1477     return [=] { return *val; };
1478 
1479   // Tok is a symbol name.
1480   if (tok.startswith("\""))
1481     tok = unquote(tok);
1482   else if (!isValidSymbolName(tok))
1483     setError("malformed number: " + tok);
1484   script->referencedSymbols.push_back(tok);
1485   return [=] { return script->getSymbolValue(tok, location); };
1486 }
1487 
1488 Expr ScriptParser::readTernary(Expr cond) {
1489   Expr l = readExpr();
1490   expect(":");
1491   Expr r = readExpr();
1492   return [=] { return cond().getValue() ? l() : r(); };
1493 }
1494 
1495 Expr ScriptParser::readParenExpr() {
1496   expect("(");
1497   Expr e = readExpr();
1498   expect(")");
1499   return e;
1500 }
1501 
1502 SmallVector<StringRef, 0> ScriptParser::readOutputSectionPhdrs() {
1503   SmallVector<StringRef, 0> phdrs;
1504   while (!errorCount() && peek().startswith(":")) {
1505     StringRef tok = next();
1506     phdrs.push_back((tok.size() == 1) ? next() : tok.substr(1));
1507   }
1508   return phdrs;
1509 }
1510 
1511 // Read a program header type name. The next token must be a
1512 // name of a program header type or a constant (e.g. "0x3").
1513 unsigned ScriptParser::readPhdrType() {
1514   StringRef tok = next();
1515   if (Optional<uint64_t> val = parseInt(tok))
1516     return *val;
1517 
1518   unsigned ret = StringSwitch<unsigned>(tok)
1519                      .Case("PT_NULL", PT_NULL)
1520                      .Case("PT_LOAD", PT_LOAD)
1521                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1522                      .Case("PT_INTERP", PT_INTERP)
1523                      .Case("PT_NOTE", PT_NOTE)
1524                      .Case("PT_SHLIB", PT_SHLIB)
1525                      .Case("PT_PHDR", PT_PHDR)
1526                      .Case("PT_TLS", PT_TLS)
1527                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1528                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1529                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1530                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1531                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1532                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1533                      .Default(-1);
1534 
1535   if (ret == (unsigned)-1) {
1536     setError("invalid program header type: " + tok);
1537     return PT_NULL;
1538   }
1539   return ret;
1540 }
1541 
1542 // Reads an anonymous version declaration.
1543 void ScriptParser::readAnonymousDeclaration() {
1544   SmallVector<SymbolVersion, 0> locals;
1545   SmallVector<SymbolVersion, 0> globals;
1546   std::tie(locals, globals) = readSymbols();
1547   for (const SymbolVersion &pat : locals)
1548     config->versionDefinitions[VER_NDX_LOCAL].localPatterns.push_back(pat);
1549   for (const SymbolVersion &pat : globals)
1550     config->versionDefinitions[VER_NDX_GLOBAL].nonLocalPatterns.push_back(pat);
1551 
1552   expect(";");
1553 }
1554 
1555 // Reads a non-anonymous version definition,
1556 // e.g. "VerStr { global: foo; bar; local: *; };".
1557 void ScriptParser::readVersionDeclaration(StringRef verStr) {
1558   // Read a symbol list.
1559   SmallVector<SymbolVersion, 0> locals;
1560   SmallVector<SymbolVersion, 0> globals;
1561   std::tie(locals, globals) = readSymbols();
1562 
1563   // Create a new version definition and add that to the global symbols.
1564   VersionDefinition ver;
1565   ver.name = verStr;
1566   ver.nonLocalPatterns = std::move(globals);
1567   ver.localPatterns = std::move(locals);
1568   ver.id = config->versionDefinitions.size();
1569   config->versionDefinitions.push_back(ver);
1570 
1571   // Each version may have a parent version. For example, "Ver2"
1572   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1573   // as a parent. This version hierarchy is, probably against your
1574   // instinct, purely for hint; the runtime doesn't care about it
1575   // at all. In LLD, we simply ignore it.
1576   if (next() != ";")
1577     expect(";");
1578 }
1579 
1580 bool elf::hasWildcard(StringRef s) {
1581   return s.find_first_of("?*[") != StringRef::npos;
1582 }
1583 
1584 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1585 std::pair<SmallVector<SymbolVersion, 0>, SmallVector<SymbolVersion, 0>>
1586 ScriptParser::readSymbols() {
1587   SmallVector<SymbolVersion, 0> locals;
1588   SmallVector<SymbolVersion, 0> globals;
1589   SmallVector<SymbolVersion, 0> *v = &globals;
1590 
1591   while (!errorCount()) {
1592     if (consume("}"))
1593       break;
1594     if (consumeLabel("local")) {
1595       v = &locals;
1596       continue;
1597     }
1598     if (consumeLabel("global")) {
1599       v = &globals;
1600       continue;
1601     }
1602 
1603     if (consume("extern")) {
1604       SmallVector<SymbolVersion, 0> ext = readVersionExtern();
1605       v->insert(v->end(), ext.begin(), ext.end());
1606     } else {
1607       StringRef tok = next();
1608       v->push_back({unquote(tok), false, hasWildcard(tok)});
1609     }
1610     expect(";");
1611   }
1612   return {locals, globals};
1613 }
1614 
1615 // Reads an "extern C++" directive, e.g.,
1616 // "extern "C++" { ns::*; "f(int, double)"; };"
1617 //
1618 // The last semicolon is optional. E.g. this is OK:
1619 // "extern "C++" { ns::*; "f(int, double)" };"
1620 SmallVector<SymbolVersion, 0> ScriptParser::readVersionExtern() {
1621   StringRef tok = next();
1622   bool isCXX = tok == "\"C++\"";
1623   if (!isCXX && tok != "\"C\"")
1624     setError("Unknown language");
1625   expect("{");
1626 
1627   SmallVector<SymbolVersion, 0> ret;
1628   while (!errorCount() && peek() != "}") {
1629     StringRef tok = next();
1630     ret.push_back(
1631         {unquote(tok), isCXX, !tok.startswith("\"") && hasWildcard(tok)});
1632     if (consume("}"))
1633       return ret;
1634     expect(";");
1635   }
1636 
1637   expect("}");
1638   return ret;
1639 }
1640 
1641 Expr ScriptParser::readMemoryAssignment(StringRef s1, StringRef s2,
1642                                         StringRef s3) {
1643   if (!consume(s1) && !consume(s2) && !consume(s3)) {
1644     setError("expected one of: " + s1 + ", " + s2 + ", or " + s3);
1645     return [] { return 0; };
1646   }
1647   expect("=");
1648   return readExpr();
1649 }
1650 
1651 // Parse the MEMORY command as specified in:
1652 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1653 //
1654 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1655 void ScriptParser::readMemory() {
1656   expect("{");
1657   while (!errorCount() && !consume("}")) {
1658     StringRef tok = next();
1659     if (tok == "INCLUDE") {
1660       readInclude();
1661       continue;
1662     }
1663 
1664     uint32_t flags = 0;
1665     uint32_t invFlags = 0;
1666     uint32_t negFlags = 0;
1667     uint32_t negInvFlags = 0;
1668     if (consume("(")) {
1669       readMemoryAttributes(flags, invFlags, negFlags, negInvFlags);
1670       expect(")");
1671     }
1672     expect(":");
1673 
1674     Expr origin = readMemoryAssignment("ORIGIN", "org", "o");
1675     expect(",");
1676     Expr length = readMemoryAssignment("LENGTH", "len", "l");
1677 
1678     // Add the memory region to the region map.
1679     MemoryRegion *mr = make<MemoryRegion>(tok, origin, length, flags, invFlags,
1680                                           negFlags, negInvFlags);
1681     if (!script->memoryRegions.insert({tok, mr}).second)
1682       setError("region '" + tok + "' already defined");
1683   }
1684 }
1685 
1686 // This function parses the attributes used to match against section
1687 // flags when placing output sections in a memory region. These flags
1688 // are only used when an explicit memory region name is not used.
1689 void ScriptParser::readMemoryAttributes(uint32_t &flags, uint32_t &invFlags,
1690                                         uint32_t &negFlags,
1691                                         uint32_t &negInvFlags) {
1692   bool invert = false;
1693 
1694   for (char c : next().lower()) {
1695     if (c == '!') {
1696       invert = !invert;
1697       std::swap(flags, negFlags);
1698       std::swap(invFlags, negInvFlags);
1699       continue;
1700     }
1701     if (c == 'w')
1702       flags |= SHF_WRITE;
1703     else if (c == 'x')
1704       flags |= SHF_EXECINSTR;
1705     else if (c == 'a')
1706       flags |= SHF_ALLOC;
1707     else if (c == 'r')
1708       invFlags |= SHF_WRITE;
1709     else
1710       setError("invalid memory region attribute");
1711   }
1712 
1713   if (invert) {
1714     std::swap(flags, negFlags);
1715     std::swap(invFlags, negInvFlags);
1716   }
1717 }
1718 
1719 void elf::readLinkerScript(MemoryBufferRef mb) {
1720   llvm::TimeTraceScope timeScope("Read linker script",
1721                                  mb.getBufferIdentifier());
1722   ScriptParser(mb).readLinkerScript();
1723 }
1724 
1725 void elf::readVersionScript(MemoryBufferRef mb) {
1726   llvm::TimeTraceScope timeScope("Read version script",
1727                                  mb.getBufferIdentifier());
1728   ScriptParser(mb).readVersionScript();
1729 }
1730 
1731 void elf::readDynamicList(MemoryBufferRef mb) {
1732   llvm::TimeTraceScope timeScope("Read dynamic list", mb.getBufferIdentifier());
1733   ScriptParser(mb).readDynamicList();
1734 }
1735 
1736 void elf::readDefsym(StringRef name, MemoryBufferRef mb) {
1737   llvm::TimeTraceScope timeScope("Read defsym input", name);
1738   ScriptParser(mb).readDefsym(name);
1739 }
1740