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