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