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