Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lld/ELF/ScriptParser.cpp
Warning:line 1506, column 12
Potential memory leak

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ScriptParser.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D LLD_VENDOR="Debian" -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lld/ELF -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lld/ELF -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lld/include -I tools/lld/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lld/ELF/ScriptParser.cpp

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lld/ELF/ScriptParser.cpp

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

/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/std_function.h

1// Implementation of std::function -*- C++ -*-
2
3// Copyright (C) 2004-2020 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file include/bits/std_function.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{functional}
28 */
29
30#ifndef _GLIBCXX_STD_FUNCTION_H1
31#define _GLIBCXX_STD_FUNCTION_H1 1
32
33#pragma GCC system_header
34
35#if __cplusplus201703L < 201103L
36# include <bits/c++0x_warning.h>
37#else
38
39#if __cpp_rtti199711L
40# include <typeinfo>
41#endif
42#include <bits/stl_function.h>
43#include <bits/invoke.h>
44#include <bits/refwrap.h>
45#include <bits/functexcept.h>
46
47namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
48{
49_GLIBCXX_BEGIN_NAMESPACE_VERSION
50
51 /**
52 * @brief Exception class thrown when class template function's
53 * operator() is called with an empty target.
54 * @ingroup exceptions
55 */
56 class bad_function_call : public std::exception
57 {
58 public:
59 virtual ~bad_function_call() noexcept;
60
61 const char* what() const noexcept;
62 };
63
64 /**
65 * Trait identifying "location-invariant" types, meaning that the
66 * address of the object (or any of its members) will not escape.
67 * Trivially copyable types are location-invariant and users can
68 * specialize this trait for other types.
69 */
70 template<typename _Tp>
71 struct __is_location_invariant
72 : is_trivially_copyable<_Tp>::type
73 { };
74
75 class _Undefined_class;
76
77 union _Nocopy_types
78 {
79 void* _M_object;
80 const void* _M_const_object;
81 void (*_M_function_pointer)();
82 void (_Undefined_class::*_M_member_pointer)();
83 };
84
85 union [[gnu::may_alias]] _Any_data
86 {
87 void* _M_access() { return &_M_pod_data[0]; }
88 const void* _M_access() const { return &_M_pod_data[0]; }
89
90 template<typename _Tp>
91 _Tp&
92 _M_access()
93 { return *static_cast<_Tp*>(_M_access()); }
94
95 template<typename _Tp>
96 const _Tp&
97 _M_access() const
98 { return *static_cast<const _Tp*>(_M_access()); }
99
100 _Nocopy_types _M_unused;
101 char _M_pod_data[sizeof(_Nocopy_types)];
102 };
103
104 enum _Manager_operation
105 {
106 __get_type_info,
107 __get_functor_ptr,
108 __clone_functor,
109 __destroy_functor
110 };
111
112 template<typename _Signature>
113 class function;
114
115 /// Base class of all polymorphic function object wrappers.
116 class _Function_base
117 {
118 public:
119 static const size_t _M_max_size = sizeof(_Nocopy_types);
120 static const size_t _M_max_align = __alignof__(_Nocopy_types);
121
122 template<typename _Functor>
123 class _Base_manager
124 {
125 protected:
126 static const bool __stored_locally =
127 (__is_location_invariant<_Functor>::value
128 && sizeof(_Functor) <= _M_max_size
129 && __alignof__(_Functor) <= _M_max_align
130 && (_M_max_align % __alignof__(_Functor) == 0));
131
132 typedef integral_constant<bool, __stored_locally> _Local_storage;
133
134 // Retrieve a pointer to the function object
135 static _Functor*
136 _M_get_pointer(const _Any_data& __source)
137 {
138 if _GLIBCXX17_CONSTEXPRconstexpr (__stored_locally)
139 {
140 const _Functor& __f = __source._M_access<_Functor>();
141 return const_cast<_Functor*>(std::__addressof(__f));
142 }
143 else // have stored a pointer
144 return __source._M_access<_Functor*>();
145 }
146
147 // Clone a location-invariant function object that fits within
148 // an _Any_data structure.
149 static void
150 _M_clone(_Any_data& __dest, const _Any_data& __source, true_type)
151 {
152 ::new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
153 }
154
155 // Clone a function object that is not location-invariant or
156 // that cannot fit into an _Any_data structure.
157 static void
158 _M_clone(_Any_data& __dest, const _Any_data& __source, false_type)
159 {
160 __dest._M_access<_Functor*>() =
161 new _Functor(*__source._M_access<const _Functor*>());
53
Memory is allocated
162 }
163
164 // Destroying a location-invariant object may still require
165 // destruction.
166 static void
167 _M_destroy(_Any_data& __victim, true_type)
168 {
169 __victim._M_access<_Functor>().~_Functor();
170 }
171
172 // Destroying an object located on the heap.
173 static void
174 _M_destroy(_Any_data& __victim, false_type)
175 {
176 delete __victim._M_access<_Functor*>();
177 }
178
179 public:
180 static bool
181 _M_manager(_Any_data& __dest, const _Any_data& __source,
182 _Manager_operation __op)
183 {
184 switch (__op)
51
Control jumps to 'case __clone_functor:' at line 195
185 {
186#if __cpp_rtti199711L
187 case __get_type_info:
188 __dest._M_access<const type_info*>() = &typeid(_Functor);
189 break;
190#endif
191 case __get_functor_ptr:
192 __dest._M_access<_Functor*>() = _M_get_pointer(__source);
193 break;
194
195 case __clone_functor:
196 _M_clone(__dest, __source, _Local_storage());
52
Calling '_Base_manager::_M_clone'
54
Returned allocated memory
197 break;
198
199 case __destroy_functor:
200 _M_destroy(__dest, _Local_storage());
201 break;
202 }
203 return false;
55
Execution continues on line 203
204 }
205
206 static void
207 _M_init_functor(_Any_data& __functor, _Functor&& __f)
208 { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
209
210 template<typename _Signature>
211 static bool
212 _M_not_empty_function(const function<_Signature>& __f)
213 { return static_cast<bool>(__f); }
214
215 template<typename _Tp>
216 static bool
217 _M_not_empty_function(_Tp* __fp)
218 { return __fp != nullptr; }
219
220 template<typename _Class, typename _Tp>
221 static bool
222 _M_not_empty_function(_Tp _Class::* __mp)
223 { return __mp != nullptr; }
224
225 template<typename _Tp>
226 static bool
227 _M_not_empty_function(const _Tp&)
228 { return true; }
229
230 private:
231 static void
232 _M_init_functor(_Any_data& __functor, _Functor&& __f, true_type)
233 { ::new (__functor._M_access()) _Functor(std::move(__f)); }
234
235 static void
236 _M_init_functor(_Any_data& __functor, _Functor&& __f, false_type)
237 { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); }
238 };
239
240 _Function_base() : _M_manager(nullptr) { }
241
242 ~_Function_base()
243 {
244 if (_M_manager)
245 _M_manager(_M_functor, _M_functor, __destroy_functor);
246 }
247
248 bool _M_empty() const { return !_M_manager; }
249
250 typedef bool (*_Manager_type)(_Any_data&, const _Any_data&,
251 _Manager_operation);
252
253 _Any_data _M_functor;
254 _Manager_type _M_manager;
255 };
256
257 template<typename _Signature, typename _Functor>
258 class _Function_handler;
259
260 template<typename _Res, typename _Functor, typename... _ArgTypes>
261 class _Function_handler<_Res(_ArgTypes...), _Functor>
262 : public _Function_base::_Base_manager<_Functor>
263 {
264 typedef _Function_base::_Base_manager<_Functor> _Base;
265
266 public:
267 static bool
268 _M_manager(_Any_data& __dest, const _Any_data& __source,
269 _Manager_operation __op)
270 {
271 switch (__op)
49
Control jumps to the 'default' case at line 282
272 {
273#if __cpp_rtti199711L
274 case __get_type_info:
275 __dest._M_access<const type_info*>() = &typeid(_Functor);
276 break;
277#endif
278 case __get_functor_ptr:
279 __dest._M_access<_Functor*>() = _Base::_M_get_pointer(__source);
280 break;
281
282 default:
283 _Base::_M_manager(__dest, __source, __op);
50
Calling '_Base_manager::_M_manager'
56
Returned allocated memory
284 }
285 return false;
286 }
287
288 static _Res
289 _M_invoke(const _Any_data& __functor, _ArgTypes&&... __args)
290 {
291 return std::__invoke_r<_Res>(*_Base::_M_get_pointer(__functor),
292 std::forward<_ArgTypes>(__args)...);
293 }
294 };
295
296 /**
297 * @brief Primary class template for std::function.
298 * @ingroup functors
299 *
300 * Polymorphic function wrapper.
301 */
302 template<typename _Res, typename... _ArgTypes>
303 class function<_Res(_ArgTypes...)>
304 : public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>,
305 private _Function_base
306 {
307 template<typename _Func,
308 typename _Res2 = __invoke_result<_Func&, _ArgTypes...>>
309 struct _Callable
310 : __is_invocable_impl<_Res2, _Res>::type
311 { };
312
313 // Used so the return type convertibility checks aren't done when
314 // performing overload resolution for copy construction/assignment.
315 template<typename _Tp>
316 struct _Callable<function, _Tp> : false_type { };
317
318 template<typename _Cond, typename _Tp>
319 using _Requires = typename enable_if<_Cond::value, _Tp>::type;
320
321 public:
322 typedef _Res result_type;
323
324 // [3.7.2.1] construct/copy/destroy
325
326 /**
327 * @brief Default construct creates an empty function call wrapper.
328 * @post @c !(bool)*this
329 */
330 function() noexcept
331 : _Function_base() { }
332
333 /**
334 * @brief Creates an empty function call wrapper.
335 * @post @c !(bool)*this
336 */
337 function(nullptr_t) noexcept
338 : _Function_base() { }
339
340 /**
341 * @brief %Function copy constructor.
342 * @param __x A %function object with identical call signature.
343 * @post @c bool(*this) == bool(__x)
344 *
345 * The newly-created %function contains a copy of the target of @a
346 * __x (if it has one).
347 */
348 function(const function& __x);
349
350 /**
351 * @brief %Function move constructor.
352 * @param __x A %function object rvalue with identical call signature.
353 *
354 * The newly-created %function contains the target of @a __x
355 * (if it has one).
356 */
357 function(function&& __x) noexcept : _Function_base()
358 {
359 __x.swap(*this);
360 }
361
362 /**
363 * @brief Builds a %function that targets a copy of the incoming
364 * function object.
365 * @param __f A %function object that is callable with parameters of
366 * type @c T1, @c T2, ..., @c TN and returns a value convertible
367 * to @c Res.
368 *
369 * The newly-created %function object will target a copy of
370 * @a __f. If @a __f is @c reference_wrapper<F>, then this function
371 * object will contain a reference to the function object @c
372 * __f.get(). If @a __f is a NULL function pointer or NULL
373 * pointer-to-member, the newly-created object will be empty.
374 *
375 * If @a __f is a non-NULL function pointer or an object of type @c
376 * reference_wrapper<F>, this function will not throw.
377 */
378 template<typename _Functor,
379 typename = _Requires<__not_<is_same<_Functor, function>>, void>,
380 typename = _Requires<_Callable<_Functor>, void>>
381 function(_Functor);
382
383 /**
384 * @brief %Function assignment operator.
385 * @param __x A %function with identical call signature.
386 * @post @c (bool)*this == (bool)x
387 * @returns @c *this
388 *
389 * The target of @a __x is copied to @c *this. If @a __x has no
390 * target, then @c *this will be empty.
391 *
392 * If @a __x targets a function pointer or a reference to a function
393 * object, then this operation will not throw an %exception.
394 */
395 function&
396 operator=(const function& __x)
397 {
398 function(__x).swap(*this);
399 return *this;
400 }
401
402 /**
403 * @brief %Function move-assignment operator.
404 * @param __x A %function rvalue with identical call signature.
405 * @returns @c *this
406 *
407 * The target of @a __x is moved to @c *this. If @a __x has no
408 * target, then @c *this will be empty.
409 *
410 * If @a __x targets a function pointer or a reference to a function
411 * object, then this operation will not throw an %exception.
412 */
413 function&
414 operator=(function&& __x) noexcept
415 {
416 function(std::move(__x)).swap(*this);
417 return *this;
418 }
419
420 /**
421 * @brief %Function assignment to zero.
422 * @post @c !(bool)*this
423 * @returns @c *this
424 *
425 * The target of @c *this is deallocated, leaving it empty.
426 */
427 function&
428 operator=(nullptr_t) noexcept
429 {
430 if (_M_manager)
431 {
432 _M_manager(_M_functor, _M_functor, __destroy_functor);
433 _M_manager = nullptr;
434 _M_invoker = nullptr;
435 }
436 return *this;
437 }
438
439 /**
440 * @brief %Function assignment to a new target.
441 * @param __f A %function object that is callable with parameters of
442 * type @c T1, @c T2, ..., @c TN and returns a value convertible
443 * to @c Res.
444 * @return @c *this
445 *
446 * This %function object wrapper will target a copy of @a
447 * __f. If @a __f is @c reference_wrapper<F>, then this function
448 * object will contain a reference to the function object @c
449 * __f.get(). If @a __f is a NULL function pointer or NULL
450 * pointer-to-member, @c this object will be empty.
451 *
452 * If @a __f is a non-NULL function pointer or an object of type @c
453 * reference_wrapper<F>, this function will not throw.
454 */
455 template<typename _Functor>
456 _Requires<_Callable<typename decay<_Functor>::type>, function&>
457 operator=(_Functor&& __f)
458 {
459 function(std::forward<_Functor>(__f)).swap(*this);
460 return *this;
461 }
462
463 /// @overload
464 template<typename _Functor>
465 function&
466 operator=(reference_wrapper<_Functor> __f) noexcept
467 {
468 function(__f).swap(*this);
469 return *this;
470 }
471
472 // [3.7.2.2] function modifiers
473
474 /**
475 * @brief Swap the targets of two %function objects.
476 * @param __x A %function with identical call signature.
477 *
478 * Swap the targets of @c this function object and @a __f. This
479 * function will not throw an %exception.
480 */
481 void swap(function& __x) noexcept
482 {
483 std::swap(_M_functor, __x._M_functor);
484 std::swap(_M_manager, __x._M_manager);
485 std::swap(_M_invoker, __x._M_invoker);
486 }
487
488 // [3.7.2.3] function capacity
489
490 /**
491 * @brief Determine if the %function wrapper has a target.
492 *
493 * @return @c true when this %function object contains a target,
494 * or @c false when it is empty.
495 *
496 * This function will not throw an %exception.
497 */
498 explicit operator bool() const noexcept
499 { return !_M_empty(); }
500
501 // [3.7.2.4] function invocation
502
503 /**
504 * @brief Invokes the function targeted by @c *this.
505 * @returns the result of the target.
506 * @throws bad_function_call when @c !(bool)*this
507 *
508 * The function call operator invokes the target function object
509 * stored by @c this.
510 */
511 _Res operator()(_ArgTypes... __args) const;
512
513#if __cpp_rtti199711L
514 // [3.7.2.5] function target access
515 /**
516 * @brief Determine the type of the target of this function object
517 * wrapper.
518 *
519 * @returns the type identifier of the target function object, or
520 * @c typeid(void) if @c !(bool)*this.
521 *
522 * This function will not throw an %exception.
523 */
524 const type_info& target_type() const noexcept;
525
526 /**
527 * @brief Access the stored target function object.
528 *
529 * @return Returns a pointer to the stored target function object,
530 * if @c typeid(_Functor).equals(target_type()); otherwise, a NULL
531 * pointer.
532 *
533 * This function does not throw exceptions.
534 *
535 * @{
536 */
537 template<typename _Functor> _Functor* target() noexcept;
538
539 template<typename _Functor> const _Functor* target() const noexcept;
540 // @}
541#endif
542
543 private:
544 using _Invoker_type = _Res (*)(const _Any_data&, _ArgTypes&&...);
545 _Invoker_type _M_invoker;
546 };
547
548#if __cpp_deduction_guides201703L >= 201606
549 template<typename>
550 struct __function_guide_helper
551 { };
552
553 template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
554 struct __function_guide_helper<
555 _Res (_Tp::*) (_Args...) noexcept(_Nx)
556 >
557 { using type = _Res(_Args...); };
558
559 template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
560 struct __function_guide_helper<
561 _Res (_Tp::*) (_Args...) & noexcept(_Nx)
562 >
563 { using type = _Res(_Args...); };
564
565 template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
566 struct __function_guide_helper<
567 _Res (_Tp::*) (_Args...) const noexcept(_Nx)
568 >
569 { using type = _Res(_Args...); };
570
571 template<typename _Res, typename _Tp, bool _Nx, typename... _Args>
572 struct __function_guide_helper<
573 _Res (_Tp::*) (_Args...) const & noexcept(_Nx)
574 >
575 { using type = _Res(_Args...); };
576
577 template<typename _Res, typename... _ArgTypes>
578 function(_Res(*)(_ArgTypes...)) -> function<_Res(_ArgTypes...)>;
579
580 template<typename _Functor, typename _Signature = typename
581 __function_guide_helper<decltype(&_Functor::operator())>::type>
582 function(_Functor) -> function<_Signature>;
583#endif
584
585 // Out-of-line member definitions.
586 template<typename _Res, typename... _ArgTypes>
587 function<_Res(_ArgTypes...)>::
588 function(const function& __x)
589 : _Function_base()
590 {
591 if (static_cast<bool>(__x))
47
Taking true branch
592 {
593 __x._M_manager(_M_functor, __x._M_functor, __clone_functor);
48
Calling '_Function_handler::_M_manager'
57
Returned allocated memory
594 _M_invoker = __x._M_invoker;
595 _M_manager = __x._M_manager;
596 }
597 }
598
599 template<typename _Res, typename... _ArgTypes>
600 template<typename _Functor, typename, typename>
601 function<_Res(_ArgTypes...)>::
602 function(_Functor __f)
603 : _Function_base()
604 {
605 typedef _Function_handler<_Res(_ArgTypes...), _Functor> _My_handler;
606
607 if (_My_handler::_M_not_empty_function(__f))
608 {
609 _My_handler::_M_init_functor(_M_functor, std::move(__f));
610 _M_invoker = &_My_handler::_M_invoke;
611 _M_manager = &_My_handler::_M_manager;
612 }
613 }
614
615 template<typename _Res, typename... _ArgTypes>
616 _Res
617 function<_Res(_ArgTypes...)>::
618 operator()(_ArgTypes... __args) const
619 {
620 if (_M_empty())
621 __throw_bad_function_call();
622 return _M_invoker(_M_functor, std::forward<_ArgTypes>(__args)...);
623 }
624
625#if __cpp_rtti199711L
626 template<typename _Res, typename... _ArgTypes>
627 const type_info&
628 function<_Res(_ArgTypes...)>::
629 target_type() const noexcept
630 {
631 if (_M_manager)
632 {
633 _Any_data __typeinfo_result;
634 _M_manager(__typeinfo_result, _M_functor, __get_type_info);
635 return *__typeinfo_result._M_access<const type_info*>();
636 }
637 else
638 return typeid(void);
639 }
640
641 template<typename _Res, typename... _ArgTypes>
642 template<typename _Functor>
643 _Functor*
644 function<_Res(_ArgTypes...)>::
645 target() noexcept
646 {
647 const function* __const_this = this;
648 const _Functor* __func = __const_this->template target<_Functor>();
649 return const_cast<_Functor*>(__func);
650 }
651
652 template<typename _Res, typename... _ArgTypes>
653 template<typename _Functor>
654 const _Functor*
655 function<_Res(_ArgTypes...)>::
656 target() const noexcept
657 {
658 if (typeid(_Functor) == target_type() && _M_manager)
659 {
660 _Any_data __ptr;
661 _M_manager(__ptr, _M_functor, __get_functor_ptr);
662 return __ptr._M_access<const _Functor*>();
663 }
664 else
665 return nullptr;
666 }
667#endif
668
669 // [20.7.15.2.6] null pointer comparisons
670
671 /**
672 * @brief Compares a polymorphic function object wrapper against 0
673 * (the NULL pointer).
674 * @returns @c true if the wrapper has no target, @c false otherwise
675 *
676 * This function will not throw an %exception.
677 */
678 template<typename _Res, typename... _Args>
679 inline bool
680 operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
681 { return !static_cast<bool>(__f); }
682
683#if __cpp_impl_three_way_comparison < 201907L
684 /// @overload
685 template<typename _Res, typename... _Args>
686 inline bool
687 operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
688 { return !static_cast<bool>(__f); }
689
690 /**
691 * @brief Compares a polymorphic function object wrapper against 0
692 * (the NULL pointer).
693 * @returns @c false if the wrapper has no target, @c true otherwise
694 *
695 * This function will not throw an %exception.
696 */
697 template<typename _Res, typename... _Args>
698 inline bool
699 operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
700 { return static_cast<bool>(__f); }
701
702 /// @overload
703 template<typename _Res, typename... _Args>
704 inline bool
705 operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
706 { return static_cast<bool>(__f); }
707#endif
708
709 // [20.7.15.2.7] specialized algorithms
710
711 /**
712 * @brief Swap the targets of two polymorphic function object wrappers.
713 *
714 * This function will not throw an %exception.
715 */
716 // _GLIBCXX_RESOLVE_LIB_DEFECTS
717 // 2062. Effect contradictions w/o no-throw guarantee of std::function swaps
718 template<typename _Res, typename... _Args>
719 inline void
720 swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y) noexcept
721 { __x.swap(__y); }
722
723#if __cplusplus201703L >= 201703L
724 namespace __detail::__variant
725 {
726 template<typename> struct _Never_valueless_alt; // see <variant>
727
728 // Provide the strong exception-safety guarantee when emplacing a
729 // function into a variant.
730 template<typename _Signature>
731 struct _Never_valueless_alt<std::function<_Signature>>
732 : std::true_type
733 { };
734 } // namespace __detail::__variant
735#endif // C++17
736
737_GLIBCXX_END_NAMESPACE_VERSION
738} // namespace std
739
740#endif // C++11
741#endif // _GLIBCXX_STD_FUNCTION_H