Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h
Warning:line 275, column 9
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 ErrnoModeling.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 -relaxed-aliasing -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 _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Checkers -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/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/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp

1//=== ErrnoModeling.cpp -----------------------------------------*- C++ -*-===//
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 defines a checker `ErrnoModeling`, which is used to make the system
10// value 'errno' available to other checkers.
11// The 'errno' value is stored at a special memory region that is accessible
12// through the `errno_modeling` namespace. The memory region is either the
13// region of `errno` itself if it is a variable, otherwise an artifically
14// created region (in the system memory space). If `errno` is defined by using
15// a function which returns the address of it (this is always the case if it is
16// not a variable) this function is recognized and evaluated. In this way
17// `errno` becomes visible to the analysis and checkers can change its value.
18//
19//===----------------------------------------------------------------------===//
20
21#include "ErrnoModeling.h"
22#include "clang/AST/ParentMapContext.h"
23#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
24#include "clang/StaticAnalyzer/Core/Checker.h"
25#include "clang/StaticAnalyzer/Core/CheckerManager.h"
26#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
29#include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
30#include "llvm/ADT/STLExtras.h"
31
32using namespace clang;
33using namespace ento;
34
35namespace {
36
37// Name of the "errno" variable.
38// FIXME: Is there a system where it is not called "errno" but is a variable?
39const char *ErrnoVarName = "errno";
40// Names of functions that return a location of the "errno" value.
41// FIXME: Are there other similar function names?
42const char *ErrnoLocationFuncNames[] = {"__errno_location", "___errno",
43 "__errno", "_errno", "__error"};
44
45class ErrnoModeling
46 : public Checker<check::ASTDecl<TranslationUnitDecl>, check::BeginFunction,
47 check::LiveSymbols, eval::Call> {
48public:
49 void checkASTDecl(const TranslationUnitDecl *D, AnalysisManager &Mgr,
50 BugReporter &BR) const;
51 void checkBeginFunction(CheckerContext &C) const;
52 void checkLiveSymbols(ProgramStateRef State, SymbolReaper &SR) const;
53 bool evalCall(const CallEvent &Call, CheckerContext &C) const;
54
55 // The declaration of an "errno" variable or "errno location" function.
56 mutable const Decl *ErrnoDecl = nullptr;
57
58private:
59 // FIXME: Names from `ErrnoLocationFuncNames` are used to build this set.
60 CallDescriptionSet ErrnoLocationCalls{{"__errno_location", 0, 0},
61 {"___errno", 0, 0},
62 {"__errno", 0, 0},
63 {"_errno", 0, 0},
64 {"__error", 0, 0}};
65};
66
67} // namespace
68
69/// Store a MemRegion that contains the 'errno' integer value.
70/// The value is null if the 'errno' value was not recognized in the AST.
71REGISTER_TRAIT_WITH_PROGRAMSTATE(ErrnoRegion, const MemRegion *)namespace { class ErrnoRegion {}; using ErrnoRegionTy = const
MemRegion *; } namespace clang { namespace ento { template <
> struct ProgramStateTrait<ErrnoRegion> : public ProgramStatePartialTrait
<ErrnoRegionTy> { static void *GDMIndex() { static int Index
; return &Index; } }; } }
72
73REGISTER_TRAIT_WITH_PROGRAMSTATE(ErrnoState, errno_modeling::ErrnoCheckState)namespace { class ErrnoState {}; using ErrnoStateTy = errno_modeling
::ErrnoCheckState; } namespace clang { namespace ento { template
<> struct ProgramStateTrait<ErrnoState> : public
ProgramStatePartialTrait<ErrnoStateTy> { static void *
GDMIndex() { static int Index; return &Index; } }; } }
74
75/// Search for a variable called "errno" in the AST.
76/// Return nullptr if not found.
77static const VarDecl *getErrnoVar(ASTContext &ACtx) {
78 IdentifierInfo &II = ACtx.Idents.get(ErrnoVarName);
79 auto LookupRes = ACtx.getTranslationUnitDecl()->lookup(&II);
80 auto Found = llvm::find_if(LookupRes, [&ACtx](const Decl *D) {
81 if (auto *VD = dyn_cast<VarDecl>(D))
82 return ACtx.getSourceManager().isInSystemHeader(VD->getLocation()) &&
83 VD->hasExternalStorage() &&
84 VD->getType().getCanonicalType() == ACtx.IntTy;
85 return false;
86 });
87 if (Found == LookupRes.end())
88 return nullptr;
89
90 return cast<VarDecl>(*Found);
91}
92
93/// Search for a function with a specific name that is used to return a pointer
94/// to "errno".
95/// Return nullptr if no such function was found.
96static const FunctionDecl *getErrnoFunc(ASTContext &ACtx) {
97 SmallVector<const Decl *> LookupRes;
98 for (StringRef ErrnoName : ErrnoLocationFuncNames) {
99 IdentifierInfo &II = ACtx.Idents.get(ErrnoName);
100 llvm::append_range(LookupRes, ACtx.getTranslationUnitDecl()->lookup(&II));
101 }
102
103 auto Found = llvm::find_if(LookupRes, [&ACtx](const Decl *D) {
104 if (auto *FD = dyn_cast<FunctionDecl>(D))
105 return ACtx.getSourceManager().isInSystemHeader(FD->getLocation()) &&
106 FD->isExternC() && FD->getNumParams() == 0 &&
107 FD->getReturnType().getCanonicalType() ==
108 ACtx.getPointerType(ACtx.IntTy);
109 return false;
110 });
111 if (Found == LookupRes.end())
112 return nullptr;
113
114 return cast<FunctionDecl>(*Found);
115}
116
117void ErrnoModeling::checkASTDecl(const TranslationUnitDecl *D,
118 AnalysisManager &Mgr, BugReporter &BR) const {
119 // Try to find an usable `errno` value.
120 // It can be an external variable called "errno" or a function that returns a
121 // pointer to the "errno" value. This function can have different names.
122 // The actual case is dependent on the C library implementation, we
123 // can only search for a match in one of these variations.
124 // We assume that exactly one of these cases might be true.
125 ErrnoDecl = getErrnoVar(Mgr.getASTContext());
126 if (!ErrnoDecl)
127 ErrnoDecl = getErrnoFunc(Mgr.getASTContext());
128}
129
130void ErrnoModeling::checkBeginFunction(CheckerContext &C) const {
131 if (!C.inTopFrame())
132 return;
133
134 ASTContext &ACtx = C.getASTContext();
135 ProgramStateRef State = C.getState();
136
137 if (const auto *ErrnoVar = dyn_cast_or_null<VarDecl>(ErrnoDecl)) {
138 // There is an external 'errno' variable.
139 // Use its memory region.
140 // The memory region for an 'errno'-like variable is allocated in system
141 // space by MemRegionManager.
142 const MemRegion *ErrnoR =
143 State->getRegion(ErrnoVar, C.getLocationContext());
144 assert(ErrnoR && "Memory region should exist for the 'errno' variable.")(static_cast <bool> (ErrnoR && "Memory region should exist for the 'errno' variable."
) ? void (0) : __assert_fail ("ErrnoR && \"Memory region should exist for the 'errno' variable.\""
, "clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp", 144,
__extension__ __PRETTY_FUNCTION__))
;
145 State = State->set<ErrnoRegion>(ErrnoR);
146 State =
147 errno_modeling::setErrnoValue(State, C, 0, errno_modeling::Irrelevant);
148 C.addTransition(State);
149 } else if (ErrnoDecl) {
150 assert(isa<FunctionDecl>(ErrnoDecl) && "Invalid errno location function.")(static_cast <bool> (isa<FunctionDecl>(ErrnoDecl)
&& "Invalid errno location function.") ? void (0) : __assert_fail
("isa<FunctionDecl>(ErrnoDecl) && \"Invalid errno location function.\""
, "clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp", 150,
__extension__ __PRETTY_FUNCTION__))
;
151 // There is a function that returns the location of 'errno'.
152 // We must create a memory region for it in system space.
153 // Currently a symbolic region is used with an artifical symbol.
154 // FIXME: It is better to have a custom (new) kind of MemRegion for such
155 // cases.
156 SValBuilder &SVB = C.getSValBuilder();
157 MemRegionManager &RMgr = C.getStateManager().getRegionManager();
158
159 const MemSpaceRegion *GlobalSystemSpace =
160 RMgr.getGlobalsRegion(MemRegion::GlobalSystemSpaceRegionKind);
161
162 // Create an artifical symbol for the region.
163 // It is not possible to associate a statement or expression in this case.
164 const SymbolConjured *Sym = SVB.conjureSymbol(
165 nullptr, C.getLocationContext(),
166 ACtx.getLValueReferenceType(ACtx.IntTy), C.blockCount(), &ErrnoDecl);
167
168 // The symbolic region is untyped, create a typed sub-region in it.
169 // The ElementRegion is used to make the errno region a typed region.
170 const MemRegion *ErrnoR = RMgr.getElementRegion(
171 ACtx.IntTy, SVB.makeZeroArrayIndex(),
172 RMgr.getSymbolicRegion(Sym, GlobalSystemSpace), C.getASTContext());
173 State = State->set<ErrnoRegion>(ErrnoR);
174 State =
175 errno_modeling::setErrnoValue(State, C, 0, errno_modeling::Irrelevant);
176 C.addTransition(State);
177 }
178}
179
180bool ErrnoModeling::evalCall(const CallEvent &Call, CheckerContext &C) const {
181 // Return location of "errno" at a call to an "errno address returning"
182 // function.
183 if (ErrnoLocationCalls.contains(Call)) {
184 ProgramStateRef State = C.getState();
185
186 const MemRegion *ErrnoR = State->get<ErrnoRegion>();
187 if (!ErrnoR)
188 return false;
189
190 State = State->BindExpr(Call.getOriginExpr(), C.getLocationContext(),
191 loc::MemRegionVal{ErrnoR});
192 C.addTransition(State);
193 return true;
194 }
195
196 return false;
197}
198
199void ErrnoModeling::checkLiveSymbols(ProgramStateRef State,
200 SymbolReaper &SR) const {
201 // The special errno region should never garbage collected.
202 if (const auto *ErrnoR = State->get<ErrnoRegion>())
203 SR.markLive(ErrnoR);
204}
205
206namespace clang {
207namespace ento {
208namespace errno_modeling {
209
210Optional<SVal> getErrnoValue(ProgramStateRef State) {
211 const MemRegion *ErrnoR = State->get<ErrnoRegion>();
212 if (!ErrnoR)
213 return {};
214 QualType IntTy = State->getAnalysisManager().getASTContext().IntTy;
215 return State->getSVal(ErrnoR, IntTy);
216}
217
218ProgramStateRef setErrnoValue(ProgramStateRef State,
219 const LocationContext *LCtx, SVal Value,
220 ErrnoCheckState EState) {
221 const MemRegion *ErrnoR = State->get<ErrnoRegion>();
222 if (!ErrnoR)
223 return State;
224 // First set the errno value, the old state is still available at 'checkBind'
225 // or 'checkLocation' for errno value.
226 State = State->bindLoc(loc::MemRegionVal{ErrnoR}, Value, LCtx);
227 return State->set<ErrnoState>(EState);
228}
229
230ProgramStateRef setErrnoValue(ProgramStateRef State, CheckerContext &C,
231 uint64_t Value, ErrnoCheckState EState) {
232 const MemRegion *ErrnoR = State->get<ErrnoRegion>();
233 if (!ErrnoR)
234 return State;
235 State = State->bindLoc(
236 loc::MemRegionVal{ErrnoR},
237 C.getSValBuilder().makeIntVal(Value, C.getASTContext().IntTy),
238 C.getLocationContext());
239 return State->set<ErrnoState>(EState);
240}
241
242Optional<Loc> getErrnoLoc(ProgramStateRef State) {
243 const MemRegion *ErrnoR = State->get<ErrnoRegion>();
244 if (!ErrnoR)
245 return {};
246 return loc::MemRegionVal{ErrnoR};
247}
248
249ProgramStateRef setErrnoState(ProgramStateRef State, ErrnoCheckState EState) {
250 return State->set<ErrnoState>(EState);
251}
252
253ErrnoCheckState getErrnoState(ProgramStateRef State) {
254 return State->get<ErrnoState>();
255}
256
257bool isErrno(const Decl *D) {
258 if (const auto *VD = dyn_cast_or_null<VarDecl>(D))
259 if (const IdentifierInfo *II = VD->getIdentifier())
260 return II->getName() == ErrnoVarName;
261 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D))
262 if (const IdentifierInfo *II = FD->getIdentifier())
263 return llvm::is_contained(ErrnoLocationFuncNames, II->getName());
264 return false;
265}
266
267const char *describeErrnoCheckState(ErrnoCheckState CS) {
268 assert(CS == errno_modeling::MustNotBeChecked &&(static_cast <bool> (CS == errno_modeling::MustNotBeChecked
&& "Errno description not applicable.") ? void (0) :
__assert_fail ("CS == errno_modeling::MustNotBeChecked && \"Errno description not applicable.\""
, "clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp", 269,
__extension__ __PRETTY_FUNCTION__))
269 "Errno description not applicable.")(static_cast <bool> (CS == errno_modeling::MustNotBeChecked
&& "Errno description not applicable.") ? void (0) :
__assert_fail ("CS == errno_modeling::MustNotBeChecked && \"Errno description not applicable.\""
, "clang/lib/StaticAnalyzer/Checkers/ErrnoModeling.cpp", 269,
__extension__ __PRETTY_FUNCTION__))
;
270 return "may be undefined after the call and should not be used";
271}
272
273const NoteTag *getErrnoNoteTag(CheckerContext &C, const std::string &Message) {
274 return C.getNoteTag([Message](PathSensitiveBugReport &BR) -> std::string {
2
Calling 'CheckerContext::getNoteTag'
275 const MemRegion *ErrnoR = BR.getErrorNode()->getState()->get<ErrnoRegion>();
276 if (ErrnoR && BR.isInteresting(ErrnoR)) {
277 BR.markNotInteresting(ErrnoR);
278 return Message;
279 }
280 return "";
281 });
282}
283
284ProgramStateRef setErrnoForStdSuccess(ProgramStateRef State,
285 CheckerContext &C) {
286 return setErrnoState(State, MustNotBeChecked);
287}
288
289ProgramStateRef setErrnoForStdFailure(ProgramStateRef State, CheckerContext &C,
290 NonLoc ErrnoSym) {
291 SValBuilder &SVB = C.getSValBuilder();
292 NonLoc ZeroVal = SVB.makeZeroVal(C.getASTContext().IntTy).castAs<NonLoc>();
293 DefinedOrUnknownSVal Cond =
294 SVB.evalBinOp(State, BO_NE, ErrnoSym, ZeroVal, SVB.getConditionType())
295 .castAs<DefinedOrUnknownSVal>();
296 State = State->assume(Cond, true);
297 if (!State)
298 return nullptr;
299 return setErrnoValue(State, C.getLocationContext(), ErrnoSym, Irrelevant);
300}
301
302const NoteTag *getNoteTagForStdSuccess(CheckerContext &C, llvm::StringRef Fn) {
303 return getErrnoNoteTag(
1
Calling 'getErrnoNoteTag'
304 C, (Twine("Assuming that function '") + Twine(Fn) +
305 Twine("' is successful, in this case the value 'errno' ") +
306 Twine(describeErrnoCheckState(MustNotBeChecked)))
307 .str());
308}
309
310} // namespace errno_modeling
311} // namespace ento
312} // namespace clang
313
314void ento::registerErrnoModeling(CheckerManager &mgr) {
315 mgr.registerChecker<ErrnoModeling>();
316}
317
318bool ento::shouldRegisterErrnoModeling(const CheckerManager &mgr) {
319 return true;
320}

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h

1//== CheckerContext.h - Context info for path-sensitive checkers--*- C++ -*--=//
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 defines CheckerContext that provides contextual info for
10// path-sensitive checkers.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H
15#define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CHECKERCONTEXT_H
16
17#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
19
20namespace clang {
21namespace ento {
22
23class CheckerContext {
24 ExprEngine &Eng;
25 /// The current exploded(symbolic execution) graph node.
26 ExplodedNode *Pred;
27 /// The flag is true if the (state of the execution) has been modified
28 /// by the checker using this context. For example, a new transition has been
29 /// added or a bug report issued.
30 bool Changed;
31 /// The tagged location, which is used to generate all new nodes.
32 const ProgramPoint Location;
33 NodeBuilder &NB;
34
35public:
36 /// If we are post visiting a call, this flag will be set if the
37 /// call was inlined. In all other cases it will be false.
38 const bool wasInlined;
39
40 CheckerContext(NodeBuilder &builder,
41 ExprEngine &eng,
42 ExplodedNode *pred,
43 const ProgramPoint &loc,
44 bool wasInlined = false)
45 : Eng(eng),
46 Pred(pred),
47 Changed(false),
48 Location(loc),
49 NB(builder),
50 wasInlined(wasInlined) {
51 assert(Pred->getState() &&(static_cast <bool> (Pred->getState() && "We should not call the checkers on an empty state."
) ? void (0) : __assert_fail ("Pred->getState() && \"We should not call the checkers on an empty state.\""
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
, 52, __extension__ __PRETTY_FUNCTION__))
52 "We should not call the checkers on an empty state.")(static_cast <bool> (Pred->getState() && "We should not call the checkers on an empty state."
) ? void (0) : __assert_fail ("Pred->getState() && \"We should not call the checkers on an empty state.\""
, "clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
, 52, __extension__ __PRETTY_FUNCTION__))
;
53 }
54
55 AnalysisManager &getAnalysisManager() {
56 return Eng.getAnalysisManager();
57 }
58
59 ConstraintManager &getConstraintManager() {
60 return Eng.getConstraintManager();
61 }
62
63 StoreManager &getStoreManager() {
64 return Eng.getStoreManager();
65 }
66
67 /// Returns the previous node in the exploded graph, which includes
68 /// the state of the program before the checker ran. Note, checkers should
69 /// not retain the node in their state since the nodes might get invalidated.
70 ExplodedNode *getPredecessor() { return Pred; }
71 const ProgramStateRef &getState() const { return Pred->getState(); }
72
73 /// Check if the checker changed the state of the execution; ex: added
74 /// a new transition or a bug report.
75 bool isDifferent() { return Changed; }
76
77 /// Returns the number of times the current block has been visited
78 /// along the analyzed path.
79 unsigned blockCount() const {
80 return NB.getContext().blockCount();
81 }
82
83 ASTContext &getASTContext() {
84 return Eng.getContext();
85 }
86
87 const ASTContext &getASTContext() const { return Eng.getContext(); }
88
89 const LangOptions &getLangOpts() const {
90 return Eng.getContext().getLangOpts();
91 }
92
93 const LocationContext *getLocationContext() const {
94 return Pred->getLocationContext();
95 }
96
97 const StackFrameContext *getStackFrame() const {
98 return Pred->getStackFrame();
99 }
100
101 /// Return true if the current LocationContext has no caller context.
102 bool inTopFrame() const { return getLocationContext()->inTopFrame(); }
103
104 BugReporter &getBugReporter() {
105 return Eng.getBugReporter();
106 }
107
108 const SourceManager &getSourceManager() {
109 return getBugReporter().getSourceManager();
110 }
111
112 Preprocessor &getPreprocessor() { return getBugReporter().getPreprocessor(); }
113
114 SValBuilder &getSValBuilder() {
115 return Eng.getSValBuilder();
116 }
117
118 SymbolManager &getSymbolManager() {
119 return getSValBuilder().getSymbolManager();
120 }
121
122 ProgramStateManager &getStateManager() {
123 return Eng.getStateManager();
124 }
125
126 AnalysisDeclContext *getCurrentAnalysisDeclContext() const {
127 return Pred->getLocationContext()->getAnalysisDeclContext();
128 }
129
130 /// Get the blockID.
131 unsigned getBlockID() const {
132 return NB.getContext().getBlock()->getBlockID();
133 }
134
135 /// If the given node corresponds to a PostStore program point,
136 /// retrieve the location region as it was uttered in the code.
137 ///
138 /// This utility can be useful for generating extensive diagnostics, for
139 /// example, for finding variables that the given symbol was assigned to.
140 static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) {
141 ProgramPoint L = N->getLocation();
142 if (Optional<PostStore> PSL = L.getAs<PostStore>())
143 return reinterpret_cast<const MemRegion*>(PSL->getLocationValue());
144 return nullptr;
145 }
146
147 /// Get the value of arbitrary expressions at this point in the path.
148 SVal getSVal(const Stmt *S) const {
149 return Pred->getSVal(S);
150 }
151
152 /// Returns true if the value of \p E is greater than or equal to \p
153 /// Val under unsigned comparison
154 bool isGreaterOrEqual(const Expr *E, unsigned long long Val);
155
156 /// Returns true if the value of \p E is negative.
157 bool isNegative(const Expr *E);
158
159 /// Generates a new transition in the program state graph
160 /// (ExplodedGraph). Uses the default CheckerContext predecessor node.
161 ///
162 /// @param State The state of the generated node. If not specified, the state
163 /// will not be changed, but the new node will have the checker's tag.
164 /// @param Tag The tag is used to uniquely identify the creation site. If no
165 /// tag is specified, a default tag, unique to the given checker,
166 /// will be used. Tags are used to prevent states generated at
167 /// different sites from caching out.
168 ExplodedNode *addTransition(ProgramStateRef State = nullptr,
169 const ProgramPointTag *Tag = nullptr) {
170 return addTransitionImpl(State ? State : getState(), false, nullptr, Tag);
171 }
172
173 /// Generates a new transition with the given predecessor.
174 /// Allows checkers to generate a chain of nodes.
175 ///
176 /// @param State The state of the generated node.
177 /// @param Pred The transition will be generated from the specified Pred node
178 /// to the newly generated node.
179 /// @param Tag The tag to uniquely identify the creation site.
180 ExplodedNode *addTransition(ProgramStateRef State, ExplodedNode *Pred,
181 const ProgramPointTag *Tag = nullptr) {
182 return addTransitionImpl(State, false, Pred, Tag);
183 }
184
185 /// Generate a sink node. Generating a sink stops exploration of the
186 /// given path. To create a sink node for the purpose of reporting an error,
187 /// checkers should use generateErrorNode() instead.
188 ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred,
189 const ProgramPointTag *Tag = nullptr) {
190 return addTransitionImpl(State ? State : getState(), true, Pred, Tag);
191 }
192
193 /// Add a sink node to the current path of execution, halting analysis.
194 void addSink(ProgramStateRef State = nullptr,
195 const ProgramPointTag *Tag = nullptr) {
196 if (!State)
197 State = getState();
198 addTransition(State, generateSink(State, getPredecessor()));
199 }
200
201 /// Generate a transition to a node that will be used to report
202 /// an error. This node will be a sink. That is, it will stop exploration of
203 /// the given path.
204 ///
205 /// @param State The state of the generated node.
206 /// @param Tag The tag to uniquely identify the creation site. If null,
207 /// the default tag for the checker will be used.
208 ExplodedNode *generateErrorNode(ProgramStateRef State = nullptr,
209 const ProgramPointTag *Tag = nullptr) {
210 return generateSink(State, Pred,
211 (Tag ? Tag : Location.getTag()));
212 }
213
214 /// Generate a transition to a node that will be used to report
215 /// an error. This node will not be a sink. That is, exploration will
216 /// continue along this path.
217 ///
218 /// @param State The state of the generated node.
219 /// @param Tag The tag to uniquely identify the creation site. If null,
220 /// the default tag for the checker will be used.
221 ExplodedNode *
222 generateNonFatalErrorNode(ProgramStateRef State = nullptr,
223 const ProgramPointTag *Tag = nullptr) {
224 return addTransition(State, (Tag ? Tag : Location.getTag()));
225 }
226
227 /// Generate a transition to a node that will be used to report
228 /// an error. This node will not be a sink. That is, exploration will
229 /// continue along this path.
230 ///
231 /// @param State The state of the generated node.
232 /// @param Pred The transition will be generated from the specified Pred node
233 /// to the newly generated node.
234 /// @param Tag The tag to uniquely identify the creation site. If null,
235 /// the default tag for the checker will be used.
236 ExplodedNode *
237 generateNonFatalErrorNode(ProgramStateRef State,
238 ExplodedNode *Pred,
239 const ProgramPointTag *Tag = nullptr) {
240 return addTransition(State, Pred, (Tag ? Tag : Location.getTag()));
241 }
242
243 /// Emit the diagnostics report.
244 void emitReport(std::unique_ptr<BugReport> R) {
245 Changed = true;
246 Eng.getBugReporter().emitReport(std::move(R));
247 }
248
249 /// Produce a program point tag that displays an additional path note
250 /// to the user. This is a lightweight alternative to the
251 /// BugReporterVisitor mechanism: instead of visiting the bug report
252 /// node-by-node to restore the sequence of events that led to discovering
253 /// a bug, you can add notes as you add your transitions.
254 ///
255 /// @param Cb Callback with 'BugReporterContext &, BugReport &' parameters.
256 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
257 /// to omit the note from the report if it would make the displayed
258 /// bug path significantly shorter.
259 LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull))
260 const NoteTag *getNoteTag(NoteTag::Callback &&Cb, bool IsPrunable = false) {
261 return Eng.getDataTags().make<NoteTag>(std::move(Cb), IsPrunable);
262 }
263
264 /// A shorthand version of getNoteTag that doesn't require you to accept
265 /// the 'BugReporterContext' argument when you don't need it.
266 ///
267 /// @param Cb Callback only with 'BugReport &' parameter.
268 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
269 /// to omit the note from the report if it would make the displayed
270 /// bug path significantly shorter.
271 const NoteTag
272 *getNoteTag(std::function<std::string(PathSensitiveBugReport &)> &&Cb,
273 bool IsPrunable = false) {
274 return getNoteTag(
275 [Cb](BugReporterContext &,
3
Calling copy constructor for 'function<std::basic_string<char> (clang::ento::PathSensitiveBugReport &)>'
15
Returning from copy constructor for 'function<std::basic_string<char> (clang::ento::PathSensitiveBugReport &)>'
16
Potential memory leak
276 PathSensitiveBugReport &BR) { return Cb(BR); },
277 IsPrunable);
278 }
279
280 /// A shorthand version of getNoteTag that doesn't require you to accept
281 /// the arguments when you don't need it.
282 ///
283 /// @param Cb Callback without parameters.
284 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
285 /// to omit the note from the report if it would make the displayed
286 /// bug path significantly shorter.
287 const NoteTag *getNoteTag(std::function<std::string()> &&Cb,
288 bool IsPrunable = false) {
289 return getNoteTag([Cb](BugReporterContext &,
290 PathSensitiveBugReport &) { return Cb(); },
291 IsPrunable);
292 }
293
294 /// A shorthand version of getNoteTag that accepts a plain note.
295 ///
296 /// @param Note The note.
297 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
298 /// to omit the note from the report if it would make the displayed
299 /// bug path significantly shorter.
300 const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) {
301 return getNoteTag(
302 [Note](BugReporterContext &,
303 PathSensitiveBugReport &) { return std::string(Note); },
304 IsPrunable);
305 }
306
307 /// A shorthand version of getNoteTag that accepts a lambda with stream for
308 /// note.
309 ///
310 /// @param Cb Callback with 'BugReport &' and 'llvm::raw_ostream &'.
311 /// @param IsPrunable Whether the note is prunable. It allows BugReporter
312 /// to omit the note from the report if it would make the displayed
313 /// bug path significantly shorter.
314 const NoteTag *getNoteTag(
315 std::function<void(PathSensitiveBugReport &BR, llvm::raw_ostream &OS)> &&Cb,
316 bool IsPrunable = false) {
317 return getNoteTag(
318 [Cb](PathSensitiveBugReport &BR) -> std::string {
319 llvm::SmallString<128> Str;
320 llvm::raw_svector_ostream OS(Str);
321 Cb(BR, OS);
322 return std::string(OS.str());
323 },
324 IsPrunable);
325 }
326
327 /// Returns the word that should be used to refer to the declaration
328 /// in the report.
329 StringRef getDeclDescription(const Decl *D);
330
331 /// Get the declaration of the called function (path-sensitive).
332 const FunctionDecl *getCalleeDecl(const CallExpr *CE) const;
333
334 /// Get the name of the called function (path-sensitive).
335 StringRef getCalleeName(const FunctionDecl *FunDecl) const;
336
337 /// Get the identifier of the called function (path-sensitive).
338 const IdentifierInfo *getCalleeIdentifier(const CallExpr *CE) const {
339 const FunctionDecl *FunDecl = getCalleeDecl(CE);
340 if (FunDecl)
341 return FunDecl->getIdentifier();
342 else
343 return nullptr;
344 }
345
346 /// Get the name of the called function (path-sensitive).
347 StringRef getCalleeName(const CallExpr *CE) const {
348 const FunctionDecl *FunDecl = getCalleeDecl(CE);
349 return getCalleeName(FunDecl);
350 }
351
352 /// Returns true if the callee is an externally-visible function in the
353 /// top-level namespace, such as \c malloc.
354 ///
355 /// If a name is provided, the function must additionally match the given
356 /// name.
357 ///
358 /// Note that this deliberately excludes C++ library functions in the \c std
359 /// namespace, but will include C library functions accessed through the
360 /// \c std namespace. This also does not check if the function is declared
361 /// as 'extern "C"', or if it uses C++ name mangling.
362 static bool isCLibraryFunction(const FunctionDecl *FD,
363 StringRef Name = StringRef());
364
365 /// Depending on wither the location corresponds to a macro, return
366 /// either the macro name or the token spelling.
367 ///
368 /// This could be useful when checkers' logic depends on whether a function
369 /// is called with a given macro argument. For example:
370 /// s = socket(AF_INET,..)
371 /// If AF_INET is a macro, the result should be treated as a source of taint.
372 ///
373 /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName().
374 StringRef getMacroNameOrSpelling(SourceLocation &Loc);
375
376private:
377 ExplodedNode *addTransitionImpl(ProgramStateRef State,
378 bool MarkAsSink,
379 ExplodedNode *P = nullptr,
380 const ProgramPointTag *Tag = nullptr) {
381 // The analyzer may stop exploring if it sees a state it has previously
382 // visited ("cache out"). The early return here is a defensive check to
383 // prevent accidental caching out by checker API clients. Unless there is a
384 // tag or the client checker has requested that the generated node be
385 // marked as a sink, we assume that a client requesting a transition to a
386 // state that is the same as the predecessor state has made a mistake. We
387 // return the predecessor rather than cache out.
388 //
389 // TODO: We could potentially change the return to an assertion to alert
390 // clients to their mistake, but several checkers (including
391 // DereferenceChecker, CallAndMessageChecker, and DynamicTypePropagation)
392 // rely upon the defensive behavior and would need to be updated.
393 if (!State || (State == Pred->getState() && !Tag && !MarkAsSink))
394 return Pred;
395
396 Changed = true;
397 const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location);
398 if (!P)
399 P = Pred;
400
401 ExplodedNode *node;
402 if (MarkAsSink)
403 node = NB.generateSink(LocalLoc, State, P);
404 else
405 node = NB.generateNode(LocalLoc, State, P);
406 return node;
407 }
408};
409
410} // end GR namespace
411
412} // end clang namespace
413
414#endif

/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*>());
10
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)
8
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());
9
Calling '_Base_manager::_M_clone'
11
Returned allocated memory
197 break;
198
199 case __destroy_functor:
200 _M_destroy(__dest, _Local_storage());
201 break;
202 }
203 return false;
12
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)
6
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);
7
Calling '_Base_manager::_M_manager'
13
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))
4
Taking true branch
592 {
593 __x._M_manager(_M_functor, __x._M_functor, __clone_functor);
5
Calling '_Function_handler::_M_manager'
14
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