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