File: | build/source/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h |
Warning: | line 306, column 23 Potential memory leak |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===- CastValueChecker - Model implementation of custom RTTIs --*- 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 CastValueChecker which models casts of custom RTTIs. | ||||||
10 | // | ||||||
11 | // TODO list: | ||||||
12 | // - It only allows one succesful cast between two types however in the wild | ||||||
13 | // the object could be casted to multiple types. | ||||||
14 | // - It needs to check the most likely type information from the dynamic type | ||||||
15 | // map to increase precision of dynamic casting. | ||||||
16 | // | ||||||
17 | //===----------------------------------------------------------------------===// | ||||||
18 | |||||||
19 | #include "clang/AST/DeclTemplate.h" | ||||||
20 | #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" | ||||||
21 | #include "clang/StaticAnalyzer/Core/Checker.h" | ||||||
22 | #include "clang/StaticAnalyzer/Core/CheckerManager.h" | ||||||
23 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h" | ||||||
24 | #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" | ||||||
25 | #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" | ||||||
26 | #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" | ||||||
27 | #include <optional> | ||||||
28 | #include <utility> | ||||||
29 | |||||||
30 | using namespace clang; | ||||||
31 | using namespace ento; | ||||||
32 | |||||||
33 | namespace { | ||||||
34 | class CastValueChecker : public Checker<check::DeadSymbols, eval::Call> { | ||||||
35 | enum class CallKind { Function, Method, InstanceOf }; | ||||||
36 | |||||||
37 | using CastCheck = | ||||||
38 | std::function<void(const CastValueChecker *, const CallEvent &Call, | ||||||
39 | DefinedOrUnknownSVal, CheckerContext &)>; | ||||||
40 | |||||||
41 | public: | ||||||
42 | // We have five cases to evaluate a cast: | ||||||
43 | // 1) The parameter is non-null, the return value is non-null. | ||||||
44 | // 2) The parameter is non-null, the return value is null. | ||||||
45 | // 3) The parameter is null, the return value is null. | ||||||
46 | // cast: 1; dyn_cast: 1, 2; cast_or_null: 1, 3; dyn_cast_or_null: 1, 2, 3. | ||||||
47 | // | ||||||
48 | // 4) castAs: Has no parameter, the return value is non-null. | ||||||
49 | // 5) getAs: Has no parameter, the return value is null or non-null. | ||||||
50 | // | ||||||
51 | // We have two cases to check the parameter is an instance of the given type. | ||||||
52 | // 1) isa: The parameter is non-null, returns boolean. | ||||||
53 | // 2) isa_and_nonnull: The parameter is null or non-null, returns boolean. | ||||||
54 | bool evalCall(const CallEvent &Call, CheckerContext &C) const; | ||||||
55 | void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; | ||||||
56 | |||||||
57 | private: | ||||||
58 | // These are known in the LLVM project. The pairs are in the following form: | ||||||
59 | // {{{namespace, call}, argument-count}, {callback, kind}} | ||||||
60 | const CallDescriptionMap<std::pair<CastCheck, CallKind>> CDM = { | ||||||
61 | {{{"llvm", "cast"}, 1}, | ||||||
62 | {&CastValueChecker::evalCast, CallKind::Function}}, | ||||||
63 | {{{"llvm", "dyn_cast"}, 1}, | ||||||
64 | {&CastValueChecker::evalDynCast, CallKind::Function}}, | ||||||
65 | {{{"llvm", "cast_or_null"}, 1}, | ||||||
66 | {&CastValueChecker::evalCastOrNull, CallKind::Function}}, | ||||||
67 | {{{"llvm", "dyn_cast_or_null"}, 1}, | ||||||
68 | {&CastValueChecker::evalDynCastOrNull, CallKind::Function}}, | ||||||
69 | {{{"clang", "castAs"}, 0}, | ||||||
70 | {&CastValueChecker::evalCastAs, CallKind::Method}}, | ||||||
71 | {{{"clang", "getAs"}, 0}, | ||||||
72 | {&CastValueChecker::evalGetAs, CallKind::Method}}, | ||||||
73 | {{{"llvm", "isa"}, 1}, | ||||||
74 | {&CastValueChecker::evalIsa, CallKind::InstanceOf}}, | ||||||
75 | {{{"llvm", "isa_and_nonnull"}, 1}, | ||||||
76 | {&CastValueChecker::evalIsaAndNonNull, CallKind::InstanceOf}}}; | ||||||
77 | |||||||
78 | void evalCast(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
79 | CheckerContext &C) const; | ||||||
80 | void evalDynCast(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
81 | CheckerContext &C) const; | ||||||
82 | void evalCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
83 | CheckerContext &C) const; | ||||||
84 | void evalDynCastOrNull(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
85 | CheckerContext &C) const; | ||||||
86 | void evalCastAs(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
87 | CheckerContext &C) const; | ||||||
88 | void evalGetAs(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
89 | CheckerContext &C) const; | ||||||
90 | void evalIsa(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
91 | CheckerContext &C) const; | ||||||
92 | void evalIsaAndNonNull(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
93 | CheckerContext &C) const; | ||||||
94 | }; | ||||||
95 | } // namespace | ||||||
96 | |||||||
97 | static bool isInfeasibleCast(const DynamicCastInfo *CastInfo, | ||||||
98 | bool CastSucceeds) { | ||||||
99 | if (!CastInfo) | ||||||
100 | return false; | ||||||
101 | |||||||
102 | return CastSucceeds ? CastInfo->fails() : CastInfo->succeeds(); | ||||||
103 | } | ||||||
104 | |||||||
105 | static const NoteTag *getNoteTag(CheckerContext &C, | ||||||
106 | const DynamicCastInfo *CastInfo, | ||||||
107 | QualType CastToTy, const Expr *Object, | ||||||
108 | bool CastSucceeds, bool IsKnownCast) { | ||||||
109 | std::string CastToName = | ||||||
110 | CastInfo ? CastInfo->to()->getAsCXXRecordDecl()->getNameAsString() | ||||||
111 | : CastToTy.getAsString(); | ||||||
112 | Object = Object->IgnoreParenImpCasts(); | ||||||
113 | |||||||
114 | return C.getNoteTag( | ||||||
115 | [=]() -> std::string { | ||||||
116 | SmallString<128> Msg; | ||||||
117 | llvm::raw_svector_ostream Out(Msg); | ||||||
118 | |||||||
119 | if (!IsKnownCast) | ||||||
120 | Out << "Assuming "; | ||||||
121 | |||||||
122 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Object)) { | ||||||
123 | Out << '\'' << DRE->getDecl()->getDeclName() << '\''; | ||||||
124 | } else if (const auto *ME = dyn_cast<MemberExpr>(Object)) { | ||||||
125 | Out << (IsKnownCast ? "Field '" : "field '") | ||||||
126 | << ME->getMemberDecl()->getDeclName() << '\''; | ||||||
127 | } else { | ||||||
128 | Out << (IsKnownCast ? "The object" : "the object"); | ||||||
129 | } | ||||||
130 | |||||||
131 | Out << ' ' << (CastSucceeds ? "is a" : "is not a") << " '" << CastToName | ||||||
132 | << '\''; | ||||||
133 | |||||||
134 | return std::string(Out.str()); | ||||||
135 | }, | ||||||
136 | /*IsPrunable=*/true); | ||||||
137 | } | ||||||
138 | |||||||
139 | static const NoteTag *getNoteTag(CheckerContext &C, | ||||||
140 | SmallVector<QualType, 4> CastToTyVec, | ||||||
141 | const Expr *Object, | ||||||
142 | bool IsKnownCast) { | ||||||
143 | Object = Object->IgnoreParenImpCasts(); | ||||||
144 | |||||||
145 | return C.getNoteTag( | ||||||
146 | [=]() -> std::string { | ||||||
147 | SmallString<128> Msg; | ||||||
148 | llvm::raw_svector_ostream Out(Msg); | ||||||
149 | |||||||
150 | if (!IsKnownCast) | ||||||
151 | Out << "Assuming "; | ||||||
152 | |||||||
153 | if (const auto *DRE = dyn_cast<DeclRefExpr>(Object)) { | ||||||
154 | Out << '\'' << DRE->getDecl()->getNameAsString() << '\''; | ||||||
155 | } else if (const auto *ME = dyn_cast<MemberExpr>(Object)) { | ||||||
156 | Out << (IsKnownCast ? "Field '" : "field '") | ||||||
157 | << ME->getMemberDecl()->getNameAsString() << '\''; | ||||||
158 | } else { | ||||||
159 | Out << (IsKnownCast ? "The object" : "the object"); | ||||||
160 | } | ||||||
161 | Out << " is"; | ||||||
162 | |||||||
163 | bool First = true; | ||||||
164 | for (QualType CastToTy: CastToTyVec) { | ||||||
165 | std::string CastToName = | ||||||
166 | CastToTy->getAsCXXRecordDecl() | ||||||
167 | ? CastToTy->getAsCXXRecordDecl()->getNameAsString() | ||||||
168 | : CastToTy.getAsString(); | ||||||
169 | Out << ' ' << ((CastToTyVec.size() == 1) ? "not" : | ||||||
170 | (First ? "neither" : "nor")) << " a '" << CastToName | ||||||
171 | << '\''; | ||||||
172 | First = false; | ||||||
173 | } | ||||||
174 | |||||||
175 | return std::string(Out.str()); | ||||||
176 | }, | ||||||
177 | /*IsPrunable=*/true); | ||||||
178 | } | ||||||
179 | |||||||
180 | //===----------------------------------------------------------------------===// | ||||||
181 | // Main logic to evaluate a cast. | ||||||
182 | //===----------------------------------------------------------------------===// | ||||||
183 | |||||||
184 | static QualType alignReferenceTypes(QualType toAlign, QualType alignTowards, | ||||||
185 | ASTContext &ACtx) { | ||||||
186 | if (alignTowards->isLValueReferenceType() && | ||||||
187 | alignTowards.isConstQualified()) { | ||||||
188 | toAlign.addConst(); | ||||||
189 | return ACtx.getLValueReferenceType(toAlign); | ||||||
190 | } else if (alignTowards->isLValueReferenceType()) | ||||||
191 | return ACtx.getLValueReferenceType(toAlign); | ||||||
192 | else if (alignTowards->isRValueReferenceType()) | ||||||
193 | return ACtx.getRValueReferenceType(toAlign); | ||||||
194 | |||||||
195 | llvm_unreachable("Must align towards a reference type!")::llvm::llvm_unreachable_internal("Must align towards a reference type!" , "clang/lib/StaticAnalyzer/Checkers/CastValueChecker.cpp", 195 ); | ||||||
196 | } | ||||||
197 | |||||||
198 | static void addCastTransition(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
199 | CheckerContext &C, bool IsNonNullParam, | ||||||
200 | bool IsNonNullReturn, | ||||||
201 | bool IsCheckedCast = false) { | ||||||
202 | ProgramStateRef State = C.getState()->assume(DV, IsNonNullParam); | ||||||
203 | if (!State) | ||||||
204 | return; | ||||||
205 | |||||||
206 | const Expr *Object; | ||||||
207 | QualType CastFromTy; | ||||||
208 | QualType CastToTy = Call.getResultType(); | ||||||
209 | |||||||
210 | if (Call.getNumArgs() > 0) { | ||||||
211 | Object = Call.getArgExpr(0); | ||||||
212 | CastFromTy = Call.parameters()[0]->getType(); | ||||||
213 | } else { | ||||||
214 | Object = cast<CXXInstanceCall>(&Call)->getCXXThisExpr(); | ||||||
215 | CastFromTy = Object->getType(); | ||||||
216 | if (CastToTy->isPointerType()) { | ||||||
217 | if (!CastFromTy->isPointerType()) | ||||||
218 | return; | ||||||
219 | } else { | ||||||
220 | if (!CastFromTy->isReferenceType()) | ||||||
221 | return; | ||||||
222 | |||||||
223 | CastFromTy = alignReferenceTypes(CastFromTy, CastToTy, C.getASTContext()); | ||||||
224 | } | ||||||
225 | } | ||||||
226 | |||||||
227 | const MemRegion *MR = DV.getAsRegion(); | ||||||
228 | const DynamicCastInfo *CastInfo = | ||||||
229 | getDynamicCastInfo(State, MR, CastFromTy, CastToTy); | ||||||
230 | |||||||
231 | // We assume that every checked cast succeeds. | ||||||
232 | bool CastSucceeds = IsCheckedCast || CastFromTy == CastToTy; | ||||||
233 | if (!CastSucceeds) { | ||||||
234 | if (CastInfo) | ||||||
235 | CastSucceeds = IsNonNullReturn && CastInfo->succeeds(); | ||||||
236 | else | ||||||
237 | CastSucceeds = IsNonNullReturn; | ||||||
238 | } | ||||||
239 | |||||||
240 | // Check for infeasible casts. | ||||||
241 | if (isInfeasibleCast(CastInfo, CastSucceeds)) { | ||||||
242 | C.generateSink(State, C.getPredecessor()); | ||||||
243 | return; | ||||||
244 | } | ||||||
245 | |||||||
246 | // Store the type and the cast information. | ||||||
247 | bool IsKnownCast = CastInfo || IsCheckedCast || CastFromTy == CastToTy; | ||||||
248 | if (!IsKnownCast || IsCheckedCast) | ||||||
249 | State = setDynamicTypeAndCastInfo(State, MR, CastFromTy, CastToTy, | ||||||
250 | CastSucceeds); | ||||||
251 | |||||||
252 | SVal V = CastSucceeds ? C.getSValBuilder().evalCast(DV, CastToTy, CastFromTy) | ||||||
253 | : C.getSValBuilder().makeNullWithType(CastToTy); | ||||||
254 | C.addTransition( | ||||||
255 | State->BindExpr(Call.getOriginExpr(), C.getLocationContext(), V, false), | ||||||
256 | getNoteTag(C, CastInfo, CastToTy, Object, CastSucceeds, IsKnownCast)); | ||||||
257 | } | ||||||
258 | |||||||
259 | static void addInstanceOfTransition(const CallEvent &Call, | ||||||
260 | DefinedOrUnknownSVal DV, | ||||||
261 | ProgramStateRef State, CheckerContext &C, | ||||||
262 | bool IsInstanceOf) { | ||||||
263 | const FunctionDecl *FD = Call.getDecl()->getAsFunction(); | ||||||
264 | QualType CastFromTy = Call.parameters()[0]->getType(); | ||||||
265 | SmallVector<QualType, 4> CastToTyVec; | ||||||
266 | for (unsigned idx = 0; idx < FD->getTemplateSpecializationArgs()->size() - 1; | ||||||
267 | ++idx) { | ||||||
268 | TemplateArgument CastToTempArg = | ||||||
269 | FD->getTemplateSpecializationArgs()->get(idx); | ||||||
270 | switch (CastToTempArg.getKind()) { | ||||||
271 | default: | ||||||
272 | return; | ||||||
273 | case TemplateArgument::Type: | ||||||
274 | CastToTyVec.push_back(CastToTempArg.getAsType()); | ||||||
275 | break; | ||||||
276 | case TemplateArgument::Pack: | ||||||
277 | for (TemplateArgument ArgInPack: CastToTempArg.pack_elements()) | ||||||
278 | CastToTyVec.push_back(ArgInPack.getAsType()); | ||||||
279 | break; | ||||||
280 | } | ||||||
281 | } | ||||||
282 | |||||||
283 | const MemRegion *MR = DV.getAsRegion(); | ||||||
284 | if (MR && CastFromTy->isReferenceType()) | ||||||
285 | MR = State->getSVal(DV.castAs<Loc>()).getAsRegion(); | ||||||
286 | |||||||
287 | bool Success = false; | ||||||
288 | bool IsAnyKnown = false; | ||||||
289 | for (QualType CastToTy: CastToTyVec) { | ||||||
290 | if (CastFromTy->isPointerType()) | ||||||
291 | CastToTy = C.getASTContext().getPointerType(CastToTy); | ||||||
292 | else if (CastFromTy->isReferenceType()) | ||||||
293 | CastToTy = alignReferenceTypes(CastToTy, CastFromTy, C.getASTContext()); | ||||||
294 | else | ||||||
295 | return; | ||||||
296 | |||||||
297 | const DynamicCastInfo *CastInfo = | ||||||
298 | getDynamicCastInfo(State, MR, CastFromTy, CastToTy); | ||||||
299 | |||||||
300 | bool CastSucceeds; | ||||||
301 | if (CastInfo) | ||||||
302 | CastSucceeds = IsInstanceOf && CastInfo->succeeds(); | ||||||
303 | else | ||||||
304 | CastSucceeds = IsInstanceOf || CastFromTy == CastToTy; | ||||||
305 | |||||||
306 | // Store the type and the cast information. | ||||||
307 | bool IsKnownCast = CastInfo || CastFromTy == CastToTy; | ||||||
308 | IsAnyKnown = IsAnyKnown || IsKnownCast; | ||||||
309 | ProgramStateRef NewState = State; | ||||||
310 | if (!IsKnownCast) | ||||||
311 | NewState = setDynamicTypeAndCastInfo(State, MR, CastFromTy, CastToTy, | ||||||
312 | IsInstanceOf); | ||||||
313 | |||||||
314 | if (CastSucceeds) { | ||||||
315 | Success = true; | ||||||
316 | C.addTransition( | ||||||
317 | NewState->BindExpr(Call.getOriginExpr(), C.getLocationContext(), | ||||||
318 | C.getSValBuilder().makeTruthVal(true)), | ||||||
319 | getNoteTag(C, CastInfo, CastToTy, Call.getArgExpr(0), true, | ||||||
320 | IsKnownCast)); | ||||||
321 | if (IsKnownCast) | ||||||
322 | return; | ||||||
323 | } else if (CastInfo && CastInfo->succeeds()) { | ||||||
324 | C.generateSink(NewState, C.getPredecessor()); | ||||||
325 | return; | ||||||
326 | } | ||||||
327 | } | ||||||
328 | |||||||
329 | if (!Success
| ||||||
330 | C.addTransition( | ||||||
331 | State->BindExpr(Call.getOriginExpr(), C.getLocationContext(), | ||||||
332 | C.getSValBuilder().makeTruthVal(false)), | ||||||
333 | getNoteTag(C, CastToTyVec, Call.getArgExpr(0), IsAnyKnown)); | ||||||
334 | } | ||||||
335 | } | ||||||
336 | |||||||
337 | //===----------------------------------------------------------------------===// | ||||||
338 | // Evaluating cast, dyn_cast, cast_or_null, dyn_cast_or_null. | ||||||
339 | //===----------------------------------------------------------------------===// | ||||||
340 | |||||||
341 | static void evalNonNullParamNonNullReturn(const CallEvent &Call, | ||||||
342 | DefinedOrUnknownSVal DV, | ||||||
343 | CheckerContext &C, | ||||||
344 | bool IsCheckedCast = false) { | ||||||
345 | addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, | ||||||
346 | /*IsNonNullReturn=*/true, IsCheckedCast); | ||||||
347 | } | ||||||
348 | |||||||
349 | static void evalNonNullParamNullReturn(const CallEvent &Call, | ||||||
350 | DefinedOrUnknownSVal DV, | ||||||
351 | CheckerContext &C) { | ||||||
352 | addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, | ||||||
353 | /*IsNonNullReturn=*/false); | ||||||
354 | } | ||||||
355 | |||||||
356 | static void evalNullParamNullReturn(const CallEvent &Call, | ||||||
357 | DefinedOrUnknownSVal DV, | ||||||
358 | CheckerContext &C) { | ||||||
359 | if (ProgramStateRef State = C.getState()->assume(DV, false)) | ||||||
360 | C.addTransition(State->BindExpr(Call.getOriginExpr(), | ||||||
361 | C.getLocationContext(), | ||||||
362 | C.getSValBuilder().makeNullWithType( | ||||||
363 | Call.getOriginExpr()->getType()), | ||||||
364 | false), | ||||||
365 | C.getNoteTag("Assuming null pointer is passed into cast", | ||||||
366 | /*IsPrunable=*/true)); | ||||||
367 | } | ||||||
368 | |||||||
369 | void CastValueChecker::evalCast(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
370 | CheckerContext &C) const { | ||||||
371 | evalNonNullParamNonNullReturn(Call, DV, C, /*IsCheckedCast=*/true); | ||||||
372 | } | ||||||
373 | |||||||
374 | void CastValueChecker::evalDynCast(const CallEvent &Call, | ||||||
375 | DefinedOrUnknownSVal DV, | ||||||
376 | CheckerContext &C) const { | ||||||
377 | evalNonNullParamNonNullReturn(Call, DV, C); | ||||||
378 | evalNonNullParamNullReturn(Call, DV, C); | ||||||
379 | } | ||||||
380 | |||||||
381 | void CastValueChecker::evalCastOrNull(const CallEvent &Call, | ||||||
382 | DefinedOrUnknownSVal DV, | ||||||
383 | CheckerContext &C) const { | ||||||
384 | evalNonNullParamNonNullReturn(Call, DV, C); | ||||||
385 | evalNullParamNullReturn(Call, DV, C); | ||||||
386 | } | ||||||
387 | |||||||
388 | void CastValueChecker::evalDynCastOrNull(const CallEvent &Call, | ||||||
389 | DefinedOrUnknownSVal DV, | ||||||
390 | CheckerContext &C) const { | ||||||
391 | evalNonNullParamNonNullReturn(Call, DV, C); | ||||||
392 | evalNonNullParamNullReturn(Call, DV, C); | ||||||
393 | evalNullParamNullReturn(Call, DV, C); | ||||||
394 | } | ||||||
395 | |||||||
396 | //===----------------------------------------------------------------------===// | ||||||
397 | // Evaluating castAs, getAs. | ||||||
398 | //===----------------------------------------------------------------------===// | ||||||
399 | |||||||
400 | static void evalZeroParamNonNullReturn(const CallEvent &Call, | ||||||
401 | DefinedOrUnknownSVal DV, | ||||||
402 | CheckerContext &C, | ||||||
403 | bool IsCheckedCast = false) { | ||||||
404 | addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, | ||||||
405 | /*IsNonNullReturn=*/true, IsCheckedCast); | ||||||
406 | } | ||||||
407 | |||||||
408 | static void evalZeroParamNullReturn(const CallEvent &Call, | ||||||
409 | DefinedOrUnknownSVal DV, | ||||||
410 | CheckerContext &C) { | ||||||
411 | addCastTransition(Call, DV, C, /*IsNonNullParam=*/true, | ||||||
412 | /*IsNonNullReturn=*/false); | ||||||
413 | } | ||||||
414 | |||||||
415 | void CastValueChecker::evalCastAs(const CallEvent &Call, | ||||||
416 | DefinedOrUnknownSVal DV, | ||||||
417 | CheckerContext &C) const { | ||||||
418 | evalZeroParamNonNullReturn(Call, DV, C, /*IsCheckedCast=*/true); | ||||||
419 | } | ||||||
420 | |||||||
421 | void CastValueChecker::evalGetAs(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
422 | CheckerContext &C) const { | ||||||
423 | evalZeroParamNonNullReturn(Call, DV, C); | ||||||
424 | evalZeroParamNullReturn(Call, DV, C); | ||||||
425 | } | ||||||
426 | |||||||
427 | //===----------------------------------------------------------------------===// | ||||||
428 | // Evaluating isa, isa_and_nonnull. | ||||||
429 | //===----------------------------------------------------------------------===// | ||||||
430 | |||||||
431 | void CastValueChecker::evalIsa(const CallEvent &Call, DefinedOrUnknownSVal DV, | ||||||
432 | CheckerContext &C) const { | ||||||
433 | ProgramStateRef NonNullState, NullState; | ||||||
434 | std::tie(NonNullState, NullState) = C.getState()->assume(DV); | ||||||
435 | |||||||
436 | if (NonNullState) { | ||||||
437 | addInstanceOfTransition(Call, DV, NonNullState, C, /*IsInstanceOf=*/true); | ||||||
438 | addInstanceOfTransition(Call, DV, NonNullState, C, /*IsInstanceOf=*/false); | ||||||
439 | } | ||||||
440 | |||||||
441 | if (NullState) { | ||||||
442 | C.generateSink(NullState, C.getPredecessor()); | ||||||
443 | } | ||||||
444 | } | ||||||
445 | |||||||
446 | void CastValueChecker::evalIsaAndNonNull(const CallEvent &Call, | ||||||
447 | DefinedOrUnknownSVal DV, | ||||||
448 | CheckerContext &C) const { | ||||||
449 | ProgramStateRef NonNullState, NullState; | ||||||
450 | std::tie(NonNullState, NullState) = C.getState()->assume(DV); | ||||||
451 | |||||||
452 | if (NonNullState) { | ||||||
| |||||||
453 | addInstanceOfTransition(Call, DV, NonNullState, C, /*IsInstanceOf=*/true); | ||||||
454 | addInstanceOfTransition(Call, DV, NonNullState, C, /*IsInstanceOf=*/false); | ||||||
455 | } | ||||||
456 | |||||||
457 | if (NullState) { | ||||||
458 | addInstanceOfTransition(Call, DV, NullState, C, /*IsInstanceOf=*/false); | ||||||
459 | } | ||||||
460 | } | ||||||
461 | |||||||
462 | //===----------------------------------------------------------------------===// | ||||||
463 | // Main logic to evaluate a call. | ||||||
464 | //===----------------------------------------------------------------------===// | ||||||
465 | |||||||
466 | bool CastValueChecker::evalCall(const CallEvent &Call, | ||||||
467 | CheckerContext &C) const { | ||||||
468 | const auto *Lookup = CDM.lookup(Call); | ||||||
469 | if (!Lookup) | ||||||
470 | return false; | ||||||
471 | |||||||
472 | const CastCheck &Check = Lookup->first; | ||||||
473 | CallKind Kind = Lookup->second; | ||||||
474 | |||||||
475 | std::optional<DefinedOrUnknownSVal> DV; | ||||||
476 | |||||||
477 | switch (Kind) { | ||||||
478 | case CallKind::Function: { | ||||||
479 | // We only model casts from pointers to pointers or from references | ||||||
480 | // to references. Other casts are most likely specialized and we | ||||||
481 | // cannot model them. | ||||||
482 | QualType ParamT = Call.parameters()[0]->getType(); | ||||||
483 | QualType ResultT = Call.getResultType(); | ||||||
484 | if (!(ParamT->isPointerType() && ResultT->isPointerType()) && | ||||||
485 | !(ParamT->isReferenceType() && ResultT->isReferenceType())) { | ||||||
486 | return false; | ||||||
487 | } | ||||||
488 | |||||||
489 | DV = Call.getArgSVal(0).getAs<DefinedOrUnknownSVal>(); | ||||||
490 | break; | ||||||
491 | } | ||||||
492 | case CallKind::InstanceOf: { | ||||||
493 | // We need to obtain the only template argument to determinte the type. | ||||||
494 | const FunctionDecl *FD = Call.getDecl()->getAsFunction(); | ||||||
495 | if (!FD || !FD->getTemplateSpecializationArgs()) | ||||||
496 | return false; | ||||||
497 | |||||||
498 | DV = Call.getArgSVal(0).getAs<DefinedOrUnknownSVal>(); | ||||||
499 | break; | ||||||
500 | } | ||||||
501 | case CallKind::Method: | ||||||
502 | const auto *InstanceCall = dyn_cast<CXXInstanceCall>(&Call); | ||||||
503 | if (!InstanceCall) | ||||||
504 | return false; | ||||||
505 | |||||||
506 | DV = InstanceCall->getCXXThisVal().getAs<DefinedOrUnknownSVal>(); | ||||||
507 | break; | ||||||
508 | } | ||||||
509 | |||||||
510 | if (!DV) | ||||||
511 | return false; | ||||||
512 | |||||||
513 | Check(this, Call, *DV, C); | ||||||
514 | return true; | ||||||
515 | } | ||||||
516 | |||||||
517 | void CastValueChecker::checkDeadSymbols(SymbolReaper &SR, | ||||||
518 | CheckerContext &C) const { | ||||||
519 | C.addTransition(removeDeadCasts(C.getState(), SR)); | ||||||
520 | } | ||||||
521 | |||||||
522 | void ento::registerCastValueChecker(CheckerManager &Mgr) { | ||||||
523 | Mgr.registerChecker<CastValueChecker>(); | ||||||
524 | } | ||||||
525 | |||||||
526 | bool ento::shouldRegisterCastValueChecker(const CheckerManager &mgr) { | ||||||
527 | return true; | ||||||
528 | } |
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 | #include <optional> | |||
20 | ||||
21 | namespace clang { | |||
22 | namespace ento { | |||
23 | ||||
24 | class CheckerContext { | |||
25 | ExprEngine &Eng; | |||
26 | /// The current exploded(symbolic execution) graph node. | |||
27 | ExplodedNode *Pred; | |||
28 | /// The flag is true if the (state of the execution) has been modified | |||
29 | /// by the checker using this context. For example, a new transition has been | |||
30 | /// added or a bug report issued. | |||
31 | bool Changed; | |||
32 | /// The tagged location, which is used to generate all new nodes. | |||
33 | const ProgramPoint Location; | |||
34 | NodeBuilder &NB; | |||
35 | ||||
36 | public: | |||
37 | /// If we are post visiting a call, this flag will be set if the | |||
38 | /// call was inlined. In all other cases it will be false. | |||
39 | const bool wasInlined; | |||
40 | ||||
41 | CheckerContext(NodeBuilder &builder, | |||
42 | ExprEngine &eng, | |||
43 | ExplodedNode *pred, | |||
44 | const ProgramPoint &loc, | |||
45 | bool wasInlined = false) | |||
46 | : Eng(eng), | |||
47 | Pred(pred), | |||
48 | Changed(false), | |||
49 | Location(loc), | |||
50 | NB(builder), | |||
51 | wasInlined(wasInlined) { | |||
52 | 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" , 53, __extension__ __PRETTY_FUNCTION__)) | |||
53 | "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" , 53, __extension__ __PRETTY_FUNCTION__)); | |||
54 | } | |||
55 | ||||
56 | AnalysisManager &getAnalysisManager() { | |||
57 | return Eng.getAnalysisManager(); | |||
58 | } | |||
59 | ||||
60 | ConstraintManager &getConstraintManager() { | |||
61 | return Eng.getConstraintManager(); | |||
62 | } | |||
63 | ||||
64 | StoreManager &getStoreManager() { | |||
65 | return Eng.getStoreManager(); | |||
66 | } | |||
67 | ||||
68 | /// Returns the previous node in the exploded graph, which includes | |||
69 | /// the state of the program before the checker ran. Note, checkers should | |||
70 | /// not retain the node in their state since the nodes might get invalidated. | |||
71 | ExplodedNode *getPredecessor() { return Pred; } | |||
72 | const ProgramStateRef &getState() const { return Pred->getState(); } | |||
73 | ||||
74 | /// Check if the checker changed the state of the execution; ex: added | |||
75 | /// a new transition or a bug report. | |||
76 | bool isDifferent() { return Changed; } | |||
77 | ||||
78 | /// Returns the number of times the current block has been visited | |||
79 | /// along the analyzed path. | |||
80 | unsigned blockCount() const { | |||
81 | return NB.getContext().blockCount(); | |||
82 | } | |||
83 | ||||
84 | ASTContext &getASTContext() { | |||
85 | return Eng.getContext(); | |||
86 | } | |||
87 | ||||
88 | const ASTContext &getASTContext() const { return Eng.getContext(); } | |||
89 | ||||
90 | const LangOptions &getLangOpts() const { | |||
91 | return Eng.getContext().getLangOpts(); | |||
92 | } | |||
93 | ||||
94 | const LocationContext *getLocationContext() const { | |||
95 | return Pred->getLocationContext(); | |||
96 | } | |||
97 | ||||
98 | const StackFrameContext *getStackFrame() const { | |||
99 | return Pred->getStackFrame(); | |||
100 | } | |||
101 | ||||
102 | /// Return true if the current LocationContext has no caller context. | |||
103 | bool inTopFrame() const { return getLocationContext()->inTopFrame(); } | |||
104 | ||||
105 | BugReporter &getBugReporter() { | |||
106 | return Eng.getBugReporter(); | |||
107 | } | |||
108 | ||||
109 | const SourceManager &getSourceManager() { | |||
110 | return getBugReporter().getSourceManager(); | |||
111 | } | |||
112 | ||||
113 | Preprocessor &getPreprocessor() { return getBugReporter().getPreprocessor(); } | |||
114 | ||||
115 | SValBuilder &getSValBuilder() { | |||
116 | return Eng.getSValBuilder(); | |||
117 | } | |||
118 | ||||
119 | SymbolManager &getSymbolManager() { | |||
120 | return getSValBuilder().getSymbolManager(); | |||
121 | } | |||
122 | ||||
123 | ProgramStateManager &getStateManager() { | |||
124 | return Eng.getStateManager(); | |||
125 | } | |||
126 | ||||
127 | AnalysisDeclContext *getCurrentAnalysisDeclContext() const { | |||
128 | return Pred->getLocationContext()->getAnalysisDeclContext(); | |||
129 | } | |||
130 | ||||
131 | /// Get the blockID. | |||
132 | unsigned getBlockID() const { | |||
133 | return NB.getContext().getBlock()->getBlockID(); | |||
134 | } | |||
135 | ||||
136 | /// If the given node corresponds to a PostStore program point, | |||
137 | /// retrieve the location region as it was uttered in the code. | |||
138 | /// | |||
139 | /// This utility can be useful for generating extensive diagnostics, for | |||
140 | /// example, for finding variables that the given symbol was assigned to. | |||
141 | static const MemRegion *getLocationRegionIfPostStore(const ExplodedNode *N) { | |||
142 | ProgramPoint L = N->getLocation(); | |||
143 | if (std::optional<PostStore> PSL = L.getAs<PostStore>()) | |||
144 | return reinterpret_cast<const MemRegion*>(PSL->getLocationValue()); | |||
145 | return nullptr; | |||
146 | } | |||
147 | ||||
148 | /// Get the value of arbitrary expressions at this point in the path. | |||
149 | SVal getSVal(const Stmt *S) const { | |||
150 | return Pred->getSVal(S); | |||
151 | } | |||
152 | ||||
153 | /// Returns true if the value of \p E is greater than or equal to \p | |||
154 | /// Val under unsigned comparison | |||
155 | bool isGreaterOrEqual(const Expr *E, unsigned long long Val); | |||
156 | ||||
157 | /// Returns true if the value of \p E is negative. | |||
158 | bool isNegative(const Expr *E); | |||
159 | ||||
160 | /// Generates a new transition in the program state graph | |||
161 | /// (ExplodedGraph). Uses the default CheckerContext predecessor node. | |||
162 | /// | |||
163 | /// @param State The state of the generated node. If not specified, the state | |||
164 | /// will not be changed, but the new node will have the checker's tag. | |||
165 | /// @param Tag The tag is used to uniquely identify the creation site. If no | |||
166 | /// tag is specified, a default tag, unique to the given checker, | |||
167 | /// will be used. Tags are used to prevent states generated at | |||
168 | /// different sites from caching out. | |||
169 | ExplodedNode *addTransition(ProgramStateRef State = nullptr, | |||
170 | const ProgramPointTag *Tag = nullptr) { | |||
171 | return addTransitionImpl(State ? State : getState(), false, nullptr, Tag); | |||
172 | } | |||
173 | ||||
174 | /// Generates a new transition with the given predecessor. | |||
175 | /// Allows checkers to generate a chain of nodes. | |||
176 | /// | |||
177 | /// @param State The state of the generated node. | |||
178 | /// @param Pred The transition will be generated from the specified Pred node | |||
179 | /// to the newly generated node. | |||
180 | /// @param Tag The tag to uniquely identify the creation site. | |||
181 | ExplodedNode *addTransition(ProgramStateRef State, ExplodedNode *Pred, | |||
182 | const ProgramPointTag *Tag = nullptr) { | |||
183 | return addTransitionImpl(State, false, Pred, Tag); | |||
184 | } | |||
185 | ||||
186 | /// Generate a sink node. Generating a sink stops exploration of the | |||
187 | /// given path. To create a sink node for the purpose of reporting an error, | |||
188 | /// checkers should use generateErrorNode() instead. | |||
189 | ExplodedNode *generateSink(ProgramStateRef State, ExplodedNode *Pred, | |||
190 | const ProgramPointTag *Tag = nullptr) { | |||
191 | return addTransitionImpl(State ? State : getState(), true, Pred, Tag); | |||
192 | } | |||
193 | ||||
194 | /// Add a sink node to the current path of execution, halting analysis. | |||
195 | void addSink(ProgramStateRef State = nullptr, | |||
196 | const ProgramPointTag *Tag = nullptr) { | |||
197 | if (!State) | |||
198 | State = getState(); | |||
199 | addTransition(State, generateSink(State, getPredecessor())); | |||
200 | } | |||
201 | ||||
202 | /// Generate a transition to a node that will be used to report | |||
203 | /// an error. This node will be a sink. That is, it will stop exploration of | |||
204 | /// the given path. | |||
205 | /// | |||
206 | /// @param State The state of the generated node. | |||
207 | /// @param Tag The tag to uniquely identify the creation site. If null, | |||
208 | /// the default tag for the checker will be used. | |||
209 | ExplodedNode *generateErrorNode(ProgramStateRef State = nullptr, | |||
210 | const ProgramPointTag *Tag = nullptr) { | |||
211 | return generateSink(State, Pred, | |||
212 | (Tag ? Tag : Location.getTag())); | |||
213 | } | |||
214 | ||||
215 | /// Generate a transition to a node that will be used to report | |||
216 | /// an error. This node will be a sink. That is, it will stop exploration of | |||
217 | /// the given path. | |||
218 | /// | |||
219 | /// @param State The state of the generated node. | |||
220 | /// @param Pred The transition will be generated from the specified Pred node | |||
221 | /// to the newly generated node. | |||
222 | /// @param Tag The tag to uniquely identify the creation site. If null, | |||
223 | /// the default tag for the checker will be used. | |||
224 | ExplodedNode *generateErrorNode(ProgramStateRef State, | |||
225 | ExplodedNode *Pred, | |||
226 | const ProgramPointTag *Tag = nullptr) { | |||
227 | return generateSink(State, Pred, | |||
228 | (Tag ? Tag : Location.getTag())); | |||
229 | } | |||
230 | ||||
231 | /// Generate a transition to a node that will be used to report | |||
232 | /// an error. This node will not be a sink. That is, exploration will | |||
233 | /// continue along this path. | |||
234 | /// | |||
235 | /// @param State The state of the generated node. | |||
236 | /// @param Tag The tag to uniquely identify the creation site. If null, | |||
237 | /// the default tag for the checker will be used. | |||
238 | ExplodedNode * | |||
239 | generateNonFatalErrorNode(ProgramStateRef State = nullptr, | |||
240 | const ProgramPointTag *Tag = nullptr) { | |||
241 | return addTransition(State, (Tag ? Tag : Location.getTag())); | |||
242 | } | |||
243 | ||||
244 | /// Generate a transition to a node that will be used to report | |||
245 | /// an error. This node will not be a sink. That is, exploration will | |||
246 | /// continue along this path. | |||
247 | /// | |||
248 | /// @param State The state of the generated node. | |||
249 | /// @param Pred The transition will be generated from the specified Pred node | |||
250 | /// to the newly generated node. | |||
251 | /// @param Tag The tag to uniquely identify the creation site. If null, | |||
252 | /// the default tag for the checker will be used. | |||
253 | ExplodedNode * | |||
254 | generateNonFatalErrorNode(ProgramStateRef State, | |||
255 | ExplodedNode *Pred, | |||
256 | const ProgramPointTag *Tag = nullptr) { | |||
257 | return addTransition(State, Pred, (Tag ? Tag : Location.getTag())); | |||
258 | } | |||
259 | ||||
260 | /// Emit the diagnostics report. | |||
261 | void emitReport(std::unique_ptr<BugReport> R) { | |||
262 | Changed = true; | |||
263 | Eng.getBugReporter().emitReport(std::move(R)); | |||
264 | } | |||
265 | ||||
266 | /// Produce a program point tag that displays an additional path note | |||
267 | /// to the user. This is a lightweight alternative to the | |||
268 | /// BugReporterVisitor mechanism: instead of visiting the bug report | |||
269 | /// node-by-node to restore the sequence of events that led to discovering | |||
270 | /// a bug, you can add notes as you add your transitions. | |||
271 | /// | |||
272 | /// @param Cb Callback with 'BugReporterContext &, BugReport &' parameters. | |||
273 | /// @param IsPrunable Whether the note is prunable. It allows BugReporter | |||
274 | /// to omit the note from the report if it would make the displayed | |||
275 | /// bug path significantly shorter. | |||
276 | LLVM_ATTRIBUTE_RETURNS_NONNULL__attribute__((returns_nonnull)) | |||
277 | const NoteTag *getNoteTag(NoteTag::Callback &&Cb, bool IsPrunable = false) { | |||
278 | return Eng.getDataTags().make<NoteTag>(std::move(Cb), IsPrunable); | |||
279 | } | |||
280 | ||||
281 | /// A shorthand version of getNoteTag that doesn't require you to accept | |||
282 | /// the 'BugReporterContext' argument when you don't need it. | |||
283 | /// | |||
284 | /// @param Cb Callback only with 'BugReport &' parameter. | |||
285 | /// @param IsPrunable Whether the note is prunable. It allows BugReporter | |||
286 | /// to omit the note from the report if it would make the displayed | |||
287 | /// bug path significantly shorter. | |||
288 | const NoteTag | |||
289 | *getNoteTag(std::function<std::string(PathSensitiveBugReport &)> &&Cb, | |||
290 | bool IsPrunable = false) { | |||
291 | return getNoteTag( | |||
292 | [Cb](BugReporterContext &, | |||
293 | PathSensitiveBugReport &BR) { return Cb(BR); }, | |||
294 | IsPrunable); | |||
295 | } | |||
296 | ||||
297 | /// A shorthand version of getNoteTag that doesn't require you to accept | |||
298 | /// the arguments when you don't need it. | |||
299 | /// | |||
300 | /// @param Cb Callback without parameters. | |||
301 | /// @param IsPrunable Whether the note is prunable. It allows BugReporter | |||
302 | /// to omit the note from the report if it would make the displayed | |||
303 | /// bug path significantly shorter. | |||
304 | const NoteTag *getNoteTag(std::function<std::string()> &&Cb, | |||
305 | bool IsPrunable = false) { | |||
306 | return getNoteTag([Cb](BugReporterContext &, | |||
| ||||
307 | PathSensitiveBugReport &) { return Cb(); }, | |||
308 | IsPrunable); | |||
309 | } | |||
310 | ||||
311 | /// A shorthand version of getNoteTag that accepts a plain note. | |||
312 | /// | |||
313 | /// @param Note The note. | |||
314 | /// @param IsPrunable Whether the note is prunable. It allows BugReporter | |||
315 | /// to omit the note from the report if it would make the displayed | |||
316 | /// bug path significantly shorter. | |||
317 | const NoteTag *getNoteTag(StringRef Note, bool IsPrunable = false) { | |||
318 | return getNoteTag( | |||
319 | [Note](BugReporterContext &, | |||
320 | PathSensitiveBugReport &) { return std::string(Note); }, | |||
321 | IsPrunable); | |||
322 | } | |||
323 | ||||
324 | /// A shorthand version of getNoteTag that accepts a lambda with stream for | |||
325 | /// note. | |||
326 | /// | |||
327 | /// @param Cb Callback with 'BugReport &' and 'llvm::raw_ostream &'. | |||
328 | /// @param IsPrunable Whether the note is prunable. It allows BugReporter | |||
329 | /// to omit the note from the report if it would make the displayed | |||
330 | /// bug path significantly shorter. | |||
331 | const NoteTag *getNoteTag( | |||
332 | std::function<void(PathSensitiveBugReport &BR, llvm::raw_ostream &OS)> &&Cb, | |||
333 | bool IsPrunable = false) { | |||
334 | return getNoteTag( | |||
335 | [Cb](PathSensitiveBugReport &BR) -> std::string { | |||
336 | llvm::SmallString<128> Str; | |||
337 | llvm::raw_svector_ostream OS(Str); | |||
338 | Cb(BR, OS); | |||
339 | return std::string(OS.str()); | |||
340 | }, | |||
341 | IsPrunable); | |||
342 | } | |||
343 | ||||
344 | /// Returns the word that should be used to refer to the declaration | |||
345 | /// in the report. | |||
346 | StringRef getDeclDescription(const Decl *D); | |||
347 | ||||
348 | /// Get the declaration of the called function (path-sensitive). | |||
349 | const FunctionDecl *getCalleeDecl(const CallExpr *CE) const; | |||
350 | ||||
351 | /// Get the name of the called function (path-sensitive). | |||
352 | StringRef getCalleeName(const FunctionDecl *FunDecl) const; | |||
353 | ||||
354 | /// Get the identifier of the called function (path-sensitive). | |||
355 | const IdentifierInfo *getCalleeIdentifier(const CallExpr *CE) const { | |||
356 | const FunctionDecl *FunDecl = getCalleeDecl(CE); | |||
357 | if (FunDecl) | |||
358 | return FunDecl->getIdentifier(); | |||
359 | else | |||
360 | return nullptr; | |||
361 | } | |||
362 | ||||
363 | /// Get the name of the called function (path-sensitive). | |||
364 | StringRef getCalleeName(const CallExpr *CE) const { | |||
365 | const FunctionDecl *FunDecl = getCalleeDecl(CE); | |||
366 | return getCalleeName(FunDecl); | |||
367 | } | |||
368 | ||||
369 | /// Returns true if the callee is an externally-visible function in the | |||
370 | /// top-level namespace, such as \c malloc. | |||
371 | /// | |||
372 | /// If a name is provided, the function must additionally match the given | |||
373 | /// name. | |||
374 | /// | |||
375 | /// Note that this deliberately excludes C++ library functions in the \c std | |||
376 | /// namespace, but will include C library functions accessed through the | |||
377 | /// \c std namespace. This also does not check if the function is declared | |||
378 | /// as 'extern "C"', or if it uses C++ name mangling. | |||
379 | static bool isCLibraryFunction(const FunctionDecl *FD, | |||
380 | StringRef Name = StringRef()); | |||
381 | ||||
382 | /// Depending on wither the location corresponds to a macro, return | |||
383 | /// either the macro name or the token spelling. | |||
384 | /// | |||
385 | /// This could be useful when checkers' logic depends on whether a function | |||
386 | /// is called with a given macro argument. For example: | |||
387 | /// s = socket(AF_INET,..) | |||
388 | /// If AF_INET is a macro, the result should be treated as a source of taint. | |||
389 | /// | |||
390 | /// \sa clang::Lexer::getSpelling(), clang::Lexer::getImmediateMacroName(). | |||
391 | StringRef getMacroNameOrSpelling(SourceLocation &Loc); | |||
392 | ||||
393 | private: | |||
394 | ExplodedNode *addTransitionImpl(ProgramStateRef State, | |||
395 | bool MarkAsSink, | |||
396 | ExplodedNode *P = nullptr, | |||
397 | const ProgramPointTag *Tag = nullptr) { | |||
398 | // The analyzer may stop exploring if it sees a state it has previously | |||
399 | // visited ("cache out"). The early return here is a defensive check to | |||
400 | // prevent accidental caching out by checker API clients. Unless there is a | |||
401 | // tag or the client checker has requested that the generated node be | |||
402 | // marked as a sink, we assume that a client requesting a transition to a | |||
403 | // state that is the same as the predecessor state has made a mistake. We | |||
404 | // return the predecessor rather than cache out. | |||
405 | // | |||
406 | // TODO: We could potentially change the return to an assertion to alert | |||
407 | // clients to their mistake, but several checkers (including | |||
408 | // DereferenceChecker, CallAndMessageChecker, and DynamicTypePropagation) | |||
409 | // rely upon the defensive behavior and would need to be updated. | |||
410 | if (!State || (State == Pred->getState() && !Tag && !MarkAsSink)) | |||
411 | return Pred; | |||
412 | ||||
413 | Changed = true; | |||
414 | const ProgramPoint &LocalLoc = (Tag ? Location.withTag(Tag) : Location); | |||
415 | if (!P) | |||
416 | P = Pred; | |||
417 | ||||
418 | ExplodedNode *node; | |||
419 | if (MarkAsSink) | |||
420 | node = NB.generateSink(LocalLoc, State, P); | |||
421 | else | |||
422 | node = NB.generateNode(LocalLoc, State, P); | |||
423 | return node; | |||
424 | } | |||
425 | }; | |||
426 | ||||
427 | } // end GR namespace | |||
428 | ||||
429 | } // end clang namespace | |||
430 | ||||
431 | #endif |
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 | |
47 | namespace 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*>()); |
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) |
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()); |
197 | break; |
198 | |
199 | case __destroy_functor: |
200 | _M_destroy(__dest, _Local_storage()); |
201 | break; |
202 | } |
203 | return false; |
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) |
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); |
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)) |
592 | { |
593 | __x._M_manager(_M_functor, __x._M_functor, __clone_functor); |
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 |