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