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