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