Bug Summary

File:build/source/lld/ELF/ScriptParser.cpp
Warning:line 1509, 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/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -D LLD_VENDOR="Debian" -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lld/ELF -I /build/source/lld/ELF -I /build/source/lld/include -I tools/lld/include -I include -I /build/source/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-17/lib/clang/17/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/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -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/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -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-2023-05-10-133810-16478-1 -x c++ /build/source/lld/ELF/ScriptParser.cpp

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

/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