1 //===- CallEvent.h - Wrapper for all function and method calls --*- 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 /// \file This file defines CallEvent and its subclasses, which represent path-
10 /// sensitive instances of different kinds of function and method calls
11 /// (C, C++, and Objective-C).
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
16 #define LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
17
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/IdentifierTable.h"
28 #include "clang/Basic/LLVM.h"
29 #include "clang/Basic/SourceLocation.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
32 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/IntrusiveRefCntPtr.h"
37 #include "llvm/ADT/PointerIntPair.h"
38 #include "llvm/ADT/PointerUnion.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/ADT/iterator_range.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include <cassert>
47 #include <limits>
48 #include <optional>
49 #include <utility>
50
51 namespace clang {
52
53 class LocationContext;
54 class ProgramPoint;
55 class ProgramPointTag;
56 class StackFrameContext;
57
58 namespace ento {
59
60 enum CallEventKind {
61 CE_Function,
62 CE_CXXStaticOperator,
63 CE_CXXMember,
64 CE_CXXMemberOperator,
65 CE_CXXDestructor,
66 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
67 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
68 CE_CXXConstructor,
69 CE_CXXInheritedConstructor,
70 CE_BEG_CXX_CONSTRUCTOR_CALLS = CE_CXXConstructor,
71 CE_END_CXX_CONSTRUCTOR_CALLS = CE_CXXInheritedConstructor,
72 CE_CXXAllocator,
73 CE_CXXDeallocator,
74 CE_BEG_FUNCTION_CALLS = CE_Function,
75 CE_END_FUNCTION_CALLS = CE_CXXDeallocator,
76 CE_Block,
77 CE_ObjCMessage
78 };
79
80 class CallEvent;
81
82 template <typename T = CallEvent>
83 class CallEventRef : public IntrusiveRefCntPtr<const T> {
84 public:
CallEventRef(const T * Call)85 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
CallEventRef(const CallEventRef & Orig)86 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
87
88 // The copy assignment operator is defined as deleted pending further
89 // motivation.
90 CallEventRef &operator=(const CallEventRef &) = delete;
91
cloneWithState(ProgramStateRef State)92 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
93 return this->get()->template cloneWithState<T>(State);
94 }
95
96 // Allow implicit conversions to a superclass type, since CallEventRef
97 // behaves like a pointer-to-const.
98 template <typename SuperT> operator CallEventRef<SuperT>() const {
99 return this->get();
100 }
101 };
102
103 /// \class RuntimeDefinition
104 /// Defines the runtime definition of the called function.
105 ///
106 /// Encapsulates the information we have about which Decl will be used
107 /// when the call is executed on the given path. When dealing with dynamic
108 /// dispatch, the information is based on DynamicTypeInfo and might not be
109 /// precise.
110 class RuntimeDefinition {
111 /// The Declaration of the function which could be called at runtime.
112 /// NULL if not available.
113 const Decl *D = nullptr;
114
115 /// The region representing an object (ObjC/C++) on which the method is
116 /// called. With dynamic dispatch, the method definition depends on the
117 /// runtime type of this object. NULL when the DynamicTypeInfo is
118 /// precise.
119 const MemRegion *R = nullptr;
120
121 /// A definition is foreign if it has been imported and newly created by the
122 /// ASTImporter. This can be true only if CTU is enabled.
123 const bool Foreign = false;
124
125 public:
126 RuntimeDefinition() = default;
RuntimeDefinition(const Decl * InD)127 RuntimeDefinition(const Decl *InD) : D(InD) {}
RuntimeDefinition(const Decl * InD,bool Foreign)128 RuntimeDefinition(const Decl *InD, bool Foreign) : D(InD), Foreign(Foreign) {}
RuntimeDefinition(const Decl * InD,const MemRegion * InR)129 RuntimeDefinition(const Decl *InD, const MemRegion *InR) : D(InD), R(InR) {}
130
getDecl()131 const Decl *getDecl() { return D; }
isForeign()132 bool isForeign() const { return Foreign; }
133
134 /// Check if the definition we have is precise.
135 /// If not, it is possible that the call dispatches to another definition at
136 /// execution time.
mayHaveOtherDefinitions()137 bool mayHaveOtherDefinitions() { return R != nullptr; }
138
139 /// When other definitions are possible, returns the region whose runtime type
140 /// determines the method definition.
getDispatchRegion()141 const MemRegion *getDispatchRegion() { return R; }
142 };
143
144 /// Represents an abstract call to a function or method along a
145 /// particular path.
146 ///
147 /// CallEvents are created through the factory methods of CallEventManager.
148 ///
149 /// CallEvents should always be cheap to create and destroy. In order for
150 /// CallEventManager to be able to re-use CallEvent-sized memory blocks,
151 /// subclasses of CallEvent may not add any data members to the base class.
152 /// Use the "Data" and "Location" fields instead.
153 class CallEvent {
154 public:
155 using Kind = CallEventKind;
156
157 private:
158 ProgramStateRef State;
159 const LocationContext *LCtx;
160 llvm::PointerUnion<const Expr *, const Decl *> Origin;
161 CFGBlock::ConstCFGElementRef ElemRef = {nullptr, 0};
162 mutable std::optional<bool> Foreign; // Set by CTU analysis.
163
164 protected:
165 // This is user data for subclasses.
166 const void *Data;
167
168 // This is user data for subclasses.
169 // This should come right before RefCount, so that the two fields can be
170 // packed together on LP64 platforms.
171 SourceLocation Location;
172
173 private:
174 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
175
176 mutable unsigned RefCount = 0;
177
Retain()178 void Retain() const { ++RefCount; }
179 void Release() const;
180
181 protected:
182 friend class CallEventManager;
183
CallEvent(const Expr * E,ProgramStateRef state,const LocationContext * lctx,CFGBlock::ConstCFGElementRef ElemRef)184 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx,
185 CFGBlock::ConstCFGElementRef ElemRef)
186 : State(std::move(state)), LCtx(lctx), Origin(E), ElemRef(ElemRef) {}
187
CallEvent(const Decl * D,ProgramStateRef state,const LocationContext * lctx,CFGBlock::ConstCFGElementRef ElemRef)188 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx,
189 CFGBlock::ConstCFGElementRef ElemRef)
190 : State(std::move(state)), LCtx(lctx), Origin(D), ElemRef(ElemRef) {}
191
192 // DO NOT MAKE PUBLIC
CallEvent(const CallEvent & Original)193 CallEvent(const CallEvent &Original)
194 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
195 ElemRef(Original.ElemRef), Data(Original.Data),
196 Location(Original.Location) {}
197
198 /// Copies this CallEvent, with vtable intact, into a new block of memory.
199 virtual void cloneTo(void *Dest) const = 0;
200
201 /// Get the value of arbitrary expressions at this point in the path.
getSVal(const Stmt * S)202 SVal getSVal(const Stmt *S) const {
203 return getState()->getSVal(S, getLocationContext());
204 }
205
206 using ValueList = SmallVectorImpl<SVal>;
207
208 /// Used to specify non-argument regions that will be invalidated as a
209 /// result of this call.
210 virtual void
getExtraInvalidatedValues(ValueList & Values,RegionAndSymbolInvalidationTraits * ETraits)211 getExtraInvalidatedValues(ValueList &Values,
212 RegionAndSymbolInvalidationTraits *ETraits) const {}
213
214 public:
215 CallEvent &operator=(const CallEvent &) = delete;
216 virtual ~CallEvent() = default;
217
218 /// Returns the kind of call this is.
219 virtual Kind getKind() const = 0;
220 virtual StringRef getKindAsString() const = 0;
221
222 /// Returns the declaration of the function or method that will be
223 /// called. May be null.
getDecl()224 virtual const Decl *getDecl() const {
225 return Origin.dyn_cast<const Decl *>();
226 }
227
isForeign()228 bool isForeign() const {
229 assert(Foreign && "Foreign must be set before querying");
230 return *Foreign;
231 }
setForeign(bool B)232 void setForeign(bool B) const { Foreign = B; }
233
234 /// The state in which the call is being evaluated.
getState()235 const ProgramStateRef &getState() const { return State; }
236
237 /// The context in which the call is being evaluated.
getLocationContext()238 const LocationContext *getLocationContext() const { return LCtx; }
239
getCFGElementRef()240 const CFGBlock::ConstCFGElementRef &getCFGElementRef() const {
241 return ElemRef;
242 }
243
244 /// Returns the definition of the function or method that will be
245 /// called.
246 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
247
248 /// Returns the expression whose value will be the result of this call.
249 /// May be null.
getOriginExpr()250 virtual const Expr *getOriginExpr() const {
251 return Origin.dyn_cast<const Expr *>();
252 }
253
254 /// Returns the number of arguments (explicit and implicit).
255 ///
256 /// Note that this may be greater than the number of parameters in the
257 /// callee's declaration, and that it may include arguments not written in
258 /// the source.
259 virtual unsigned getNumArgs() const = 0;
260
261 /// Returns true if the callee is known to be from a system header.
isInSystemHeader()262 bool isInSystemHeader() const {
263 const Decl *D = getDecl();
264 if (!D)
265 return false;
266
267 SourceLocation Loc = D->getLocation();
268 if (Loc.isValid()) {
269 const SourceManager &SM =
270 getState()->getStateManager().getContext().getSourceManager();
271 return SM.isInSystemHeader(D->getLocation());
272 }
273
274 // Special case for implicitly-declared global operator new/delete.
275 // These should be considered system functions.
276 if (const auto *FD = dyn_cast<FunctionDecl>(D))
277 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
278
279 return false;
280 }
281
282 /// Returns a source range for the entire call, suitable for
283 /// outputting in diagnostics.
getSourceRange()284 virtual SourceRange getSourceRange() const {
285 return getOriginExpr()->getSourceRange();
286 }
287
288 /// Returns the value of a given argument at the time of the call.
289 virtual SVal getArgSVal(unsigned Index) const;
290
291 /// Returns the expression associated with a given argument.
292 /// May be null if this expression does not appear in the source.
getArgExpr(unsigned Index)293 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
294
295 /// Returns the source range for errors associated with this argument.
296 ///
297 /// May be invalid if the argument is not written in the source.
298 virtual SourceRange getArgSourceRange(unsigned Index) const;
299
300 /// Returns the result type, adjusted for references.
301 QualType getResultType() const;
302
303 /// Returns the return value of the call.
304 ///
305 /// This should only be called if the CallEvent was created using a state in
306 /// which the return value has already been bound to the origin expression.
307 SVal getReturnValue() const;
308
309 /// Returns true if the type of any of the non-null arguments satisfies
310 /// the condition.
311 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
312
313 /// Returns true if any of the arguments appear to represent callbacks.
314 bool hasNonZeroCallbackArg() const;
315
316 /// Returns true if any of the arguments is void*.
317 bool hasVoidPointerToNonConstArg() const;
318
319 /// Returns true if any of the arguments are known to escape to long-
320 /// term storage, even if this method will not modify them.
321 // NOTE: The exact semantics of this are still being defined!
322 // We don't really want a list of hardcoded exceptions in the long run,
323 // but we don't want duplicated lists of known APIs in the short term either.
argumentsMayEscape()324 virtual bool argumentsMayEscape() const { return hasNonZeroCallbackArg(); }
325
326 /// Returns true if the callee is an externally-visible function in the
327 /// top-level namespace, such as \c malloc.
328 ///
329 /// You can use this call to determine that a particular function really is
330 /// a library function and not, say, a C++ member function with the same name.
331 ///
332 /// If a name is provided, the function must additionally match the given
333 /// name.
334 ///
335 /// Note that this deliberately excludes C++ library functions in the \c std
336 /// namespace, but will include C library functions accessed through the
337 /// \c std namespace. This also does not check if the function is declared
338 /// as 'extern "C"', or if it uses C++ name mangling.
339 // FIXME: Add a helper for checking namespaces.
340 // FIXME: Move this down to AnyFunctionCall once checkers have more
341 // precise callbacks.
342 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
343
344 /// Returns the name of the callee, if its name is a simple identifier.
345 ///
346 /// Note that this will fail for Objective-C methods, blocks, and C++
347 /// overloaded operators. The former is named by a Selector rather than a
348 /// simple identifier, and the latter two do not have names.
349 // FIXME: Move this down to AnyFunctionCall once checkers have more
350 // precise callbacks.
getCalleeIdentifier()351 const IdentifierInfo *getCalleeIdentifier() const {
352 const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
353 if (!ND)
354 return nullptr;
355 return ND->getIdentifier();
356 }
357
358 /// Returns an appropriate ProgramPoint for this call.
359 ProgramPoint getProgramPoint(bool IsPreVisit = false,
360 const ProgramPointTag *Tag = nullptr) const;
361
362 /// Returns a new state with all argument regions invalidated.
363 ///
364 /// This accepts an alternate state in case some processing has already
365 /// occurred.
366 ProgramStateRef invalidateRegions(unsigned BlockCount,
367 ProgramStateRef Orig = nullptr) const;
368
369 using FrameBindingTy = std::pair<SVal, SVal>;
370 using BindingsTy = SmallVectorImpl<FrameBindingTy>;
371
372 /// Populates the given SmallVector with the bindings in the callee's stack
373 /// frame at the start of this call.
374 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
375 BindingsTy &Bindings) const = 0;
376
377 /// Returns a copy of this CallEvent, but using the given state.
378 template <typename T>
379 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
380
381 /// Returns a copy of this CallEvent, but using the given state.
cloneWithState(ProgramStateRef NewState)382 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
383 return cloneWithState<CallEvent>(NewState);
384 }
385
386 /// Returns true if this is a statement is a function or method call
387 /// of some kind.
388 static bool isCallStmt(const Stmt *S);
389
390 /// Returns the result type of a function or method declaration.
391 ///
392 /// This will return a null QualType if the result type cannot be determined.
393 static QualType getDeclaredResultType(const Decl *D);
394
395 /// Returns true if the given decl is known to be variadic.
396 ///
397 /// \p D must not be null.
398 static bool isVariadic(const Decl *D);
399
400 /// Returns AnalysisDeclContext for the callee stack frame.
401 /// Currently may fail; returns null on failure.
402 AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
403
404 /// Returns the callee stack frame. That stack frame will only be entered
405 /// during analysis if the call is inlined, but it may still be useful
406 /// in intermediate calculations even if the call isn't inlined.
407 /// May fail; returns null on failure.
408 const StackFrameContext *getCalleeStackFrame(unsigned BlockCount) const;
409
410 /// Returns memory location for a parameter variable within the callee stack
411 /// frame. The behavior is undefined if the block count is different from the
412 /// one that is there when call happens. May fail; returns null on failure.
413 const ParamVarRegion *getParameterLocation(unsigned Index,
414 unsigned BlockCount) const;
415
416 /// Returns true if on the current path, the argument was constructed by
417 /// calling a C++ constructor over it. This is an internal detail of the
418 /// analysis which doesn't necessarily represent the program semantics:
419 /// if we are supposed to construct an argument directly, we may still
420 /// not do that because we don't know how (i.e., construction context is
421 /// unavailable in the CFG or not supported by the analyzer).
isArgumentConstructedDirectly(unsigned Index)422 bool isArgumentConstructedDirectly(unsigned Index) const {
423 // This assumes that the object was not yet removed from the state.
424 return ExprEngine::getObjectUnderConstruction(
425 getState(), {getOriginExpr(), Index}, getLocationContext())
426 .has_value();
427 }
428
429 /// Some calls have parameter numbering mismatched from argument numbering.
430 /// This function converts an argument index to the corresponding
431 /// parameter index. Returns std::nullopt is the argument doesn't correspond
432 /// to any parameter variable.
433 virtual std::optional<unsigned>
getAdjustedParameterIndex(unsigned ASTArgumentIndex)434 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
435 return ASTArgumentIndex;
436 }
437
438 /// Some call event sub-classes conveniently adjust mismatching AST indices
439 /// to match parameter indices. This function converts an argument index
440 /// as understood by CallEvent to the argument index as understood by the AST.
getASTArgumentIndex(unsigned CallArgumentIndex)441 virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
442 return CallArgumentIndex;
443 }
444
445 /// Returns the construction context of the call, if it is a C++ constructor
446 /// call or a call of a function returning a C++ class instance. Otherwise
447 /// return nullptr.
448 const ConstructionContext *getConstructionContext() const;
449
450 /// If the call returns a C++ record type then the region of its return value
451 /// can be retrieved from its construction context.
452 std::optional<SVal> getReturnValueUnderConstruction() const;
453
454 // Returns the CallEvent representing the caller of this function
455 const CallEventRef<> getCaller() const;
456
457 // Returns true if the function was called from a standard library function.
458 // If not or could not get the caller (it may be a top level function)
459 // returns false.
460 bool isCalledFromSystemHeader() const;
461
462 // Iterator access to formal parameters and their types.
463 private:
464 struct GetTypeFn {
operatorGetTypeFn465 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
466 };
467
468 public:
469 /// Return call's formal parameters.
470 ///
471 /// Remember that the number of formal parameters may not match the number
472 /// of arguments for all calls. However, the first parameter will always
473 /// correspond with the argument value returned by \c getArgSVal(0).
474 virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
475
476 using param_type_iterator =
477 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
478
479 /// Returns an iterator over the types of the call's formal parameters.
480 ///
481 /// This uses the callee decl found by default name lookup rather than the
482 /// definition because it represents a public interface, and probably has
483 /// more annotations.
param_type_begin()484 param_type_iterator param_type_begin() const {
485 return llvm::map_iterator(parameters().begin(), GetTypeFn());
486 }
487 /// \sa param_type_begin()
param_type_end()488 param_type_iterator param_type_end() const {
489 return llvm::map_iterator(parameters().end(), GetTypeFn());
490 }
491
492 // For debugging purposes only
493 void dump(raw_ostream &Out) const;
494 void dump() const;
495 };
496
497 /// Represents a call to any sort of function that might have a
498 /// FunctionDecl.
499 class AnyFunctionCall : public CallEvent {
500 protected:
AnyFunctionCall(const Expr * E,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)501 AnyFunctionCall(const Expr *E, ProgramStateRef St,
502 const LocationContext *LCtx,
503 CFGBlock::ConstCFGElementRef ElemRef)
504 : CallEvent(E, St, LCtx, ElemRef) {}
AnyFunctionCall(const Decl * D,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)505 AnyFunctionCall(const Decl *D, ProgramStateRef St,
506 const LocationContext *LCtx,
507 CFGBlock::ConstCFGElementRef ElemRef)
508 : CallEvent(D, St, LCtx, ElemRef) {}
509 AnyFunctionCall(const AnyFunctionCall &Other) = default;
510
511 public:
512 // This function is overridden by subclasses, but they must return
513 // a FunctionDecl.
getDecl()514 const FunctionDecl *getDecl() const override {
515 return cast<FunctionDecl>(CallEvent::getDecl());
516 }
517
518 RuntimeDefinition getRuntimeDefinition() const override;
519
520 bool argumentsMayEscape() const override;
521
522 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
523 BindingsTy &Bindings) const override;
524
525 ArrayRef<ParmVarDecl *> parameters() const override;
526
classof(const CallEvent * CA)527 static bool classof(const CallEvent *CA) {
528 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
529 CA->getKind() <= CE_END_FUNCTION_CALLS;
530 }
531 };
532
533 /// Represents a C function or static C++ member function call.
534 ///
535 /// Example: \c fun()
536 class SimpleFunctionCall : public AnyFunctionCall {
537 friend class CallEventManager;
538
539 protected:
SimpleFunctionCall(const CallExpr * CE,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)540 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
541 const LocationContext *LCtx,
542 CFGBlock::ConstCFGElementRef ElemRef)
543 : AnyFunctionCall(CE, St, LCtx, ElemRef) {}
544 SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
545
cloneTo(void * Dest)546 void cloneTo(void *Dest) const override {
547 new (Dest) SimpleFunctionCall(*this);
548 }
549
550 public:
getOriginExpr()551 const CallExpr *getOriginExpr() const override {
552 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
553 }
554
555 const FunctionDecl *getDecl() const override;
556
557 RuntimeDefinition getRuntimeDefinition() const override;
558
getNumArgs()559 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
560
getArgExpr(unsigned Index)561 const Expr *getArgExpr(unsigned Index) const override {
562 return getOriginExpr()->getArg(Index);
563 }
564
getKind()565 Kind getKind() const override { return CE_Function; }
getKindAsString()566 StringRef getKindAsString() const override { return "SimpleFunctionCall"; }
567
classof(const CallEvent * CA)568 static bool classof(const CallEvent *CA) {
569 return CA->getKind() == CE_Function;
570 }
571 };
572
573 /// Represents a call to a block.
574 ///
575 /// Example: <tt>^{ statement-body }()</tt>
576 class BlockCall : public CallEvent {
577 friend class CallEventManager;
578
579 protected:
BlockCall(const CallExpr * CE,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)580 BlockCall(const CallExpr *CE, ProgramStateRef St, const LocationContext *LCtx,
581 CFGBlock::ConstCFGElementRef ElemRef)
582 : CallEvent(CE, St, LCtx, ElemRef) {}
583 BlockCall(const BlockCall &Other) = default;
584
cloneTo(void * Dest)585 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
586
587 void getExtraInvalidatedValues(
588 ValueList &Values,
589 RegionAndSymbolInvalidationTraits *ETraits) const override;
590
591 public:
getOriginExpr()592 const CallExpr *getOriginExpr() const override {
593 return cast<CallExpr>(CallEvent::getOriginExpr());
594 }
595
getNumArgs()596 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
597
getArgExpr(unsigned Index)598 const Expr *getArgExpr(unsigned Index) const override {
599 return getOriginExpr()->getArg(Index);
600 }
601
602 /// Returns the region associated with this instance of the block.
603 ///
604 /// This may be NULL if the block's origin is unknown.
605 const BlockDataRegion *getBlockRegion() const;
606
getDecl()607 const BlockDecl *getDecl() const override {
608 const BlockDataRegion *BR = getBlockRegion();
609 if (!BR)
610 return nullptr;
611 return BR->getDecl();
612 }
613
isConversionFromLambda()614 bool isConversionFromLambda() const {
615 const BlockDecl *BD = getDecl();
616 if (!BD)
617 return false;
618
619 return BD->isConversionFromLambda();
620 }
621
622 /// For a block converted from a C++ lambda, returns the block
623 /// VarRegion for the variable holding the captured C++ lambda record.
getRegionStoringCapturedLambda()624 const VarRegion *getRegionStoringCapturedLambda() const {
625 assert(isConversionFromLambda());
626 const BlockDataRegion *BR = getBlockRegion();
627 assert(BR && "Block converted from lambda must have a block region");
628
629 auto ReferencedVars = BR->referenced_vars();
630 assert(!ReferencedVars.empty());
631 return ReferencedVars.begin().getCapturedRegion();
632 }
633
getRuntimeDefinition()634 RuntimeDefinition getRuntimeDefinition() const override {
635 if (!isConversionFromLambda())
636 return RuntimeDefinition(getDecl());
637
638 // Clang converts lambdas to blocks with an implicit user-defined
639 // conversion operator method on the lambda record that looks (roughly)
640 // like:
641 //
642 // typedef R(^block_type)(P1, P2, ...);
643 // operator block_type() const {
644 // auto Lambda = *this;
645 // return ^(P1 p1, P2 p2, ...){
646 // /* return Lambda(p1, p2, ...); */
647 // };
648 // }
649 //
650 // Here R is the return type of the lambda and P1, P2, ... are
651 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
652 // that is initialized to a copy of the lambda.
653 //
654 // Sema leaves the body of a lambda-converted block empty (it is
655 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
656 // the block body and analyze the operator() method on the captured lambda.
657 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
658 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
659 CXXMethodDecl *LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
660
661 return RuntimeDefinition(LambdaCallOperator);
662 }
663
argumentsMayEscape()664 bool argumentsMayEscape() const override { return true; }
665
666 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
667 BindingsTy &Bindings) const override;
668
669 ArrayRef<ParmVarDecl *> parameters() const override;
670
getKind()671 Kind getKind() const override { return CE_Block; }
getKindAsString()672 StringRef getKindAsString() const override { return "BlockCall"; }
673
classof(const CallEvent * CA)674 static bool classof(const CallEvent *CA) { return CA->getKind() == CE_Block; }
675 };
676
677 /// Represents a non-static C++ member function call, no matter how
678 /// it is written.
679 class CXXInstanceCall : public AnyFunctionCall {
680 protected:
CXXInstanceCall(const CallExpr * CE,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)681 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
682 const LocationContext *LCtx,
683 CFGBlock::ConstCFGElementRef ElemRef)
684 : AnyFunctionCall(CE, St, LCtx, ElemRef) {}
CXXInstanceCall(const FunctionDecl * D,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)685 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
686 const LocationContext *LCtx,
687 CFGBlock::ConstCFGElementRef ElemRef)
688 : AnyFunctionCall(D, St, LCtx, ElemRef) {}
689 CXXInstanceCall(const CXXInstanceCall &Other) = default;
690
691 void getExtraInvalidatedValues(
692 ValueList &Values,
693 RegionAndSymbolInvalidationTraits *ETraits) const override;
694
695 /// Returns the decl refered to by the "dynamic type" of the current object
696 /// and if the class can be a sub-class or not.
697 /// If the Pointer is null, the flag has no meaning.
698 std::pair<const CXXRecordDecl *, bool> getDeclForDynamicType() const;
699
700 public:
701 /// Returns the expression representing the implicit 'this' object.
getCXXThisExpr()702 virtual const Expr *getCXXThisExpr() const { return nullptr; }
703
704 /// Returns the value of the implicit 'this' object.
705 virtual SVal getCXXThisVal() const;
706
707 const FunctionDecl *getDecl() const override;
708
709 RuntimeDefinition getRuntimeDefinition() const override;
710
711 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
712 BindingsTy &Bindings) const override;
713
classof(const CallEvent * CA)714 static bool classof(const CallEvent *CA) {
715 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
716 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
717 }
718 };
719
720 /// Represents a static C++ operator call.
721 ///
722 /// "A" in this example.
723 /// However, "B" and "C" are represented by SimpleFunctionCall.
724 /// \code
725 /// struct S {
726 /// int pad;
727 /// static void operator()(int x, int y);
728 /// };
729 /// S s{10};
730 /// void (*fptr)(int, int) = &S::operator();
731 ///
732 /// s(1, 2); // A
733 /// S::operator()(1, 2); // B
734 /// fptr(1, 2); // C
735 /// \endcode
736 class CXXStaticOperatorCall : public SimpleFunctionCall {
737 friend class CallEventManager;
738
739 protected:
CXXStaticOperatorCall(const CXXOperatorCallExpr * CE,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)740 CXXStaticOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
741 const LocationContext *LCtx,
742 CFGBlock::ConstCFGElementRef ElemRef)
743 : SimpleFunctionCall(CE, St, LCtx, ElemRef) {}
744 CXXStaticOperatorCall(const CXXStaticOperatorCall &Other) = default;
745
cloneTo(void * Dest)746 void cloneTo(void *Dest) const override {
747 new (Dest) CXXStaticOperatorCall(*this);
748 }
749
750 public:
getOriginExpr()751 const CXXOperatorCallExpr *getOriginExpr() const override {
752 return cast<CXXOperatorCallExpr>(SimpleFunctionCall::getOriginExpr());
753 }
754
getNumArgs()755 unsigned getNumArgs() const override {
756 // Ignore the object parameter that is not used for static member functions.
757 assert(getOriginExpr()->getNumArgs() > 0);
758 return getOriginExpr()->getNumArgs() - 1;
759 }
760
getArgExpr(unsigned Index)761 const Expr *getArgExpr(unsigned Index) const override {
762 // Ignore the object parameter that is not used for static member functions.
763 return getOriginExpr()->getArg(Index + 1);
764 }
765
766 std::optional<unsigned>
getAdjustedParameterIndex(unsigned ASTArgumentIndex)767 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
768 // Ignore the object parameter that is not used for static member functions.
769 if (ASTArgumentIndex == 0)
770 return std::nullopt;
771 return ASTArgumentIndex - 1;
772 }
773
getASTArgumentIndex(unsigned CallArgumentIndex)774 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
775 // Account for the object parameter for the static member function.
776 return CallArgumentIndex + 1;
777 }
778
getOverloadedOperator()779 OverloadedOperatorKind getOverloadedOperator() const {
780 return getOriginExpr()->getOperator();
781 }
782
getKind()783 Kind getKind() const override { return CE_CXXStaticOperator; }
getKindAsString()784 StringRef getKindAsString() const override { return "CXXStaticOperatorCall"; }
785
classof(const CallEvent * CA)786 static bool classof(const CallEvent *CA) {
787 return CA->getKind() == CE_CXXStaticOperator;
788 }
789 };
790
791 /// Represents a non-static C++ member function call.
792 ///
793 /// Example: \c obj.fun()
794 class CXXMemberCall : public CXXInstanceCall {
795 friend class CallEventManager;
796
797 protected:
CXXMemberCall(const CXXMemberCallExpr * CE,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)798 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
799 const LocationContext *LCtx,
800 CFGBlock::ConstCFGElementRef ElemRef)
801 : CXXInstanceCall(CE, St, LCtx, ElemRef) {}
802 CXXMemberCall(const CXXMemberCall &Other) = default;
803
cloneTo(void * Dest)804 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
805
806 public:
getOriginExpr()807 const CXXMemberCallExpr *getOriginExpr() const override {
808 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
809 }
810
getNumArgs()811 unsigned getNumArgs() const override {
812 if (const CallExpr *CE = getOriginExpr())
813 return CE->getNumArgs();
814 return 0;
815 }
816
getArgExpr(unsigned Index)817 const Expr *getArgExpr(unsigned Index) const override {
818 return getOriginExpr()->getArg(Index);
819 }
820
821 const Expr *getCXXThisExpr() const override;
822
823 RuntimeDefinition getRuntimeDefinition() const override;
824
getKind()825 Kind getKind() const override { return CE_CXXMember; }
getKindAsString()826 StringRef getKindAsString() const override { return "CXXMemberCall"; }
827
classof(const CallEvent * CA)828 static bool classof(const CallEvent *CA) {
829 return CA->getKind() == CE_CXXMember;
830 }
831 };
832
833 /// Represents a C++ overloaded operator call where the operator is
834 /// implemented as a non-static member function.
835 ///
836 /// Example: <tt>iter + 1</tt>
837 class CXXMemberOperatorCall : public CXXInstanceCall {
838 friend class CallEventManager;
839
840 protected:
CXXMemberOperatorCall(const CXXOperatorCallExpr * CE,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)841 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
842 const LocationContext *LCtx,
843 CFGBlock::ConstCFGElementRef ElemRef)
844 : CXXInstanceCall(CE, St, LCtx, ElemRef) {}
845 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
846
cloneTo(void * Dest)847 void cloneTo(void *Dest) const override {
848 new (Dest) CXXMemberOperatorCall(*this);
849 }
850
851 public:
getOriginExpr()852 const CXXOperatorCallExpr *getOriginExpr() const override {
853 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
854 }
855
getNumArgs()856 unsigned getNumArgs() const override {
857 return getOriginExpr()->getNumArgs() - 1;
858 }
859
getArgExpr(unsigned Index)860 const Expr *getArgExpr(unsigned Index) const override {
861 return getOriginExpr()->getArg(Index + 1);
862 }
863
864 const Expr *getCXXThisExpr() const override;
865
getKind()866 Kind getKind() const override { return CE_CXXMemberOperator; }
getKindAsString()867 StringRef getKindAsString() const override { return "CXXMemberOperatorCall"; }
868
classof(const CallEvent * CA)869 static bool classof(const CallEvent *CA) {
870 return CA->getKind() == CE_CXXMemberOperator;
871 }
872
873 std::optional<unsigned>
getAdjustedParameterIndex(unsigned ASTArgumentIndex)874 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
875 // For member operator calls argument 0 on the expression corresponds
876 // to implicit this-parameter on the declaration.
877 return (ASTArgumentIndex > 0)
878 ? std::optional<unsigned>(ASTArgumentIndex - 1)
879 : std::nullopt;
880 }
881
getASTArgumentIndex(unsigned CallArgumentIndex)882 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
883 // For member operator calls argument 0 on the expression corresponds
884 // to implicit this-parameter on the declaration.
885 return CallArgumentIndex + 1;
886 }
887
getOverloadedOperator()888 OverloadedOperatorKind getOverloadedOperator() const {
889 return getOriginExpr()->getOperator();
890 }
891 };
892
893 /// Represents an implicit call to a C++ destructor.
894 ///
895 /// This can occur at the end of a scope (for automatic objects), at the end
896 /// of a full-expression (for temporaries), or as part of a delete.
897 class CXXDestructorCall : public CXXInstanceCall {
898 friend class CallEventManager;
899
900 protected:
901 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
902
903 /// Creates an implicit destructor.
904 ///
905 /// \param DD The destructor that will be called.
906 /// \param Trigger The statement whose completion causes this destructor call.
907 /// \param Target The object region to be destructed.
908 /// \param St The path-sensitive state at this point in the program.
909 /// \param LCtx The location context at this point in the program.
910 /// \param ElemRef The reference to this destructor in the CFG.
911 ///
912 /// FIXME: Eventually we want to drop \param Target and deduce it from
913 /// \param ElemRef. To do that we need to migrate the logic for target
914 /// region lookup from ExprEngine::ProcessImplicitDtor() and make it
915 /// independent from ExprEngine.
CXXDestructorCall(const CXXDestructorDecl * DD,const Stmt * Trigger,const MemRegion * Target,bool IsBaseDestructor,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)916 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
917 const MemRegion *Target, bool IsBaseDestructor,
918 ProgramStateRef St, const LocationContext *LCtx,
919 CFGBlock::ConstCFGElementRef ElemRef)
920 : CXXInstanceCall(DD, St, LCtx, ElemRef) {
921 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
922 Location = Trigger->getEndLoc();
923 }
924
925 CXXDestructorCall(const CXXDestructorCall &Other) = default;
926
cloneTo(void * Dest)927 void cloneTo(void *Dest) const override {
928 new (Dest) CXXDestructorCall(*this);
929 }
930
931 public:
getSourceRange()932 SourceRange getSourceRange() const override { return Location; }
getNumArgs()933 unsigned getNumArgs() const override { return 0; }
934
935 RuntimeDefinition getRuntimeDefinition() const override;
936
937 /// Returns the value of the implicit 'this' object.
938 SVal getCXXThisVal() const override;
939
940 /// Returns true if this is a call to a base class destructor.
isBaseDestructor()941 bool isBaseDestructor() const {
942 return DtorDataTy::getFromOpaqueValue(Data).getInt();
943 }
944
getKind()945 Kind getKind() const override { return CE_CXXDestructor; }
getKindAsString()946 StringRef getKindAsString() const override { return "CXXDestructorCall"; }
947
classof(const CallEvent * CA)948 static bool classof(const CallEvent *CA) {
949 return CA->getKind() == CE_CXXDestructor;
950 }
951 };
952
953 /// Represents any constructor invocation. This includes regular constructors
954 /// and inherited constructors.
955 class AnyCXXConstructorCall : public AnyFunctionCall {
956 protected:
AnyCXXConstructorCall(const Expr * E,const MemRegion * Target,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)957 AnyCXXConstructorCall(const Expr *E, const MemRegion *Target,
958 ProgramStateRef St, const LocationContext *LCtx,
959 CFGBlock::ConstCFGElementRef ElemRef)
960 : AnyFunctionCall(E, St, LCtx, ElemRef) {
961 assert(E && (isa<CXXConstructExpr>(E) || isa<CXXInheritedCtorInitExpr>(E)));
962 // Target may be null when the region is unknown.
963 Data = Target;
964 }
965
966 void getExtraInvalidatedValues(
967 ValueList &Values,
968 RegionAndSymbolInvalidationTraits *ETraits) const override;
969
970 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
971 BindingsTy &Bindings) const override;
972
973 public:
974 /// Returns the value of the implicit 'this' object.
975 SVal getCXXThisVal() const;
976
classof(const CallEvent * Call)977 static bool classof(const CallEvent *Call) {
978 return Call->getKind() >= CE_BEG_CXX_CONSTRUCTOR_CALLS &&
979 Call->getKind() <= CE_END_CXX_CONSTRUCTOR_CALLS;
980 }
981 };
982
983 /// Represents a call to a C++ constructor.
984 ///
985 /// Example: \c T(1)
986 class CXXConstructorCall : public AnyCXXConstructorCall {
987 friend class CallEventManager;
988
989 protected:
990 /// Creates a constructor call.
991 ///
992 /// \param CE The constructor expression as written in the source.
993 /// \param Target The region where the object should be constructed. If NULL,
994 /// a new symbolic region will be used.
995 /// \param St The path-sensitive state at this point in the program.
996 /// \param LCtx The location context at this point in the program.
997 /// \param ElemRef The reference to this constructor in the CFG.
998 ///
999 /// FIXME: Eventually we want to drop \param Target and deduce it from
1000 /// \param ElemRef.
CXXConstructorCall(const CXXConstructExpr * CE,const MemRegion * Target,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1001 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
1002 ProgramStateRef St, const LocationContext *LCtx,
1003 CFGBlock::ConstCFGElementRef ElemRef)
1004 : AnyCXXConstructorCall(CE, Target, St, LCtx, ElemRef) {}
1005
1006 CXXConstructorCall(const CXXConstructorCall &Other) = default;
1007
cloneTo(void * Dest)1008 void cloneTo(void *Dest) const override {
1009 new (Dest) CXXConstructorCall(*this);
1010 }
1011
1012 public:
getOriginExpr()1013 const CXXConstructExpr *getOriginExpr() const override {
1014 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
1015 }
1016
getDecl()1017 const CXXConstructorDecl *getDecl() const override {
1018 return getOriginExpr()->getConstructor();
1019 }
1020
getNumArgs()1021 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
1022
getArgExpr(unsigned Index)1023 const Expr *getArgExpr(unsigned Index) const override {
1024 return getOriginExpr()->getArg(Index);
1025 }
1026
getKind()1027 Kind getKind() const override { return CE_CXXConstructor; }
getKindAsString()1028 StringRef getKindAsString() const override { return "CXXConstructorCall"; }
1029
classof(const CallEvent * CA)1030 static bool classof(const CallEvent *CA) {
1031 return CA->getKind() == CE_CXXConstructor;
1032 }
1033 };
1034
1035 /// Represents a call to a C++ inherited constructor.
1036 ///
1037 /// Example: \c class T : public S { using S::S; }; T(1);
1038 ///
1039 // Note, it is difficult to model the parameters. This is one of the reasons
1040 // why we skip analysis of inheriting constructors as top-level functions.
1041 // CXXInheritedCtorInitExpr doesn't take arguments and doesn't model parameter
1042 // initialization because there is none: the arguments in the outer
1043 // CXXConstructExpr directly initialize the parameters of the base class
1044 // constructor, and no copies are made. (Making a copy of the parameter is
1045 // incorrect, at least if it's done in an observable way.) The derived class
1046 // constructor doesn't even exist in the formal model.
1047 /// E.g., in:
1048 ///
1049 /// struct X { X *p = this; ~X() {} };
1050 /// struct A { A(X x) : b(x.p == &x) {} bool b; };
1051 /// struct B : A { using A::A; };
1052 /// B b = X{};
1053 ///
1054 /// ... b.b is initialized to true.
1055 class CXXInheritedConstructorCall : public AnyCXXConstructorCall {
1056 friend class CallEventManager;
1057
1058 protected:
CXXInheritedConstructorCall(const CXXInheritedCtorInitExpr * CE,const MemRegion * Target,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1059 CXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *CE,
1060 const MemRegion *Target, ProgramStateRef St,
1061 const LocationContext *LCtx,
1062 CFGBlock::ConstCFGElementRef ElemRef)
1063 : AnyCXXConstructorCall(CE, Target, St, LCtx, ElemRef) {}
1064
1065 CXXInheritedConstructorCall(const CXXInheritedConstructorCall &Other) =
1066 default;
1067
cloneTo(void * Dest)1068 void cloneTo(void *Dest) const override {
1069 new (Dest) CXXInheritedConstructorCall(*this);
1070 }
1071
1072 public:
getOriginExpr()1073 const CXXInheritedCtorInitExpr *getOriginExpr() const override {
1074 return cast<CXXInheritedCtorInitExpr>(AnyFunctionCall::getOriginExpr());
1075 }
1076
getDecl()1077 const CXXConstructorDecl *getDecl() const override {
1078 return getOriginExpr()->getConstructor();
1079 }
1080
1081 /// Obtain the stack frame of the inheriting constructor. Argument expressions
1082 /// can be found on the call site of that stack frame.
1083 const StackFrameContext *getInheritingStackFrame() const;
1084
1085 /// Obtain the CXXConstructExpr for the sub-class that inherited the current
1086 /// constructor (possibly indirectly). It's the statement that contains
1087 /// argument expressions.
getInheritingConstructor()1088 const CXXConstructExpr *getInheritingConstructor() const {
1089 return cast<CXXConstructExpr>(getInheritingStackFrame()->getCallSite());
1090 }
1091
getNumArgs()1092 unsigned getNumArgs() const override {
1093 return getInheritingConstructor()->getNumArgs();
1094 }
1095
getArgExpr(unsigned Index)1096 const Expr *getArgExpr(unsigned Index) const override {
1097 return getInheritingConstructor()->getArg(Index);
1098 }
1099
getArgSVal(unsigned Index)1100 SVal getArgSVal(unsigned Index) const override {
1101 return getState()->getSVal(
1102 getArgExpr(Index),
1103 getInheritingStackFrame()->getParent()->getStackFrame());
1104 }
1105
getKind()1106 Kind getKind() const override { return CE_CXXInheritedConstructor; }
getKindAsString()1107 StringRef getKindAsString() const override {
1108 return "CXXInheritedConstructorCall";
1109 }
1110
classof(const CallEvent * CA)1111 static bool classof(const CallEvent *CA) {
1112 return CA->getKind() == CE_CXXInheritedConstructor;
1113 }
1114 };
1115
1116 /// Represents the memory allocation call in a C++ new-expression.
1117 ///
1118 /// This is a call to "operator new".
1119 class CXXAllocatorCall : public AnyFunctionCall {
1120 friend class CallEventManager;
1121
1122 protected:
CXXAllocatorCall(const CXXNewExpr * E,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1123 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
1124 const LocationContext *LCtx,
1125 CFGBlock::ConstCFGElementRef ElemRef)
1126 : AnyFunctionCall(E, St, LCtx, ElemRef) {}
1127 CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
1128
cloneTo(void * Dest)1129 void cloneTo(void *Dest) const override {
1130 new (Dest) CXXAllocatorCall(*this);
1131 }
1132
1133 public:
getOriginExpr()1134 const CXXNewExpr *getOriginExpr() const override {
1135 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
1136 }
1137
getDecl()1138 const FunctionDecl *getDecl() const override {
1139 return getOriginExpr()->getOperatorNew();
1140 }
1141
getObjectUnderConstruction()1142 SVal getObjectUnderConstruction() const {
1143 return *ExprEngine::getObjectUnderConstruction(getState(), getOriginExpr(),
1144 getLocationContext());
1145 }
1146
1147 /// Number of non-placement arguments to the call. It is equal to 2 for
1148 /// C++17 aligned operator new() calls that have alignment implicitly
1149 /// passed as the second argument, and to 1 for other operator new() calls.
getNumImplicitArgs()1150 unsigned getNumImplicitArgs() const {
1151 return getOriginExpr()->getNumImplicitArgs();
1152 }
1153
getNumArgs()1154 unsigned getNumArgs() const override {
1155 return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
1156 }
1157
isArray()1158 bool isArray() const { return getOriginExpr()->isArray(); }
1159
getArraySizeExpr()1160 std::optional<const clang::Expr *> getArraySizeExpr() const {
1161 return getOriginExpr()->getArraySize();
1162 }
1163
getArraySizeVal()1164 SVal getArraySizeVal() const {
1165 assert(isArray() && "The allocator call doesn't allocate and array!");
1166
1167 return getState()->getSVal(*getArraySizeExpr(), getLocationContext());
1168 }
1169
getArgExpr(unsigned Index)1170 const Expr *getArgExpr(unsigned Index) const override {
1171 // The first argument of an allocator call is the size of the allocation.
1172 if (Index < getNumImplicitArgs())
1173 return nullptr;
1174 return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs());
1175 }
1176
1177 /// Number of placement arguments to the operator new() call. For example,
1178 /// standard std::nothrow operator new and standard placement new both have
1179 /// 1 implicit argument (size) and 1 placement argument, while regular
1180 /// operator new() has 1 implicit argument and 0 placement arguments.
getPlacementArgExpr(unsigned Index)1181 const Expr *getPlacementArgExpr(unsigned Index) const {
1182 return getOriginExpr()->getPlacementArg(Index);
1183 }
1184
getKind()1185 Kind getKind() const override { return CE_CXXAllocator; }
getKindAsString()1186 StringRef getKindAsString() const override { return "CXXAllocatorCall"; }
1187
classof(const CallEvent * CE)1188 static bool classof(const CallEvent *CE) {
1189 return CE->getKind() == CE_CXXAllocator;
1190 }
1191 };
1192
1193 /// Represents the memory deallocation call in a C++ delete-expression.
1194 ///
1195 /// This is a call to "operator delete".
1196 // FIXME: CXXDeleteExpr isn't present for custom delete operators, or even for
1197 // some those that are in the standard library, like the no-throw or align_val
1198 // versions.
1199 // Some pointers:
1200 // http://lists.llvm.org/pipermail/cfe-dev/2020-April/065080.html
1201 // clang/test/Analysis/cxx-dynamic-memory-analysis-order.cpp
1202 // clang/unittests/StaticAnalyzer/CallEventTest.cpp
1203 class CXXDeallocatorCall : public AnyFunctionCall {
1204 friend class CallEventManager;
1205
1206 protected:
CXXDeallocatorCall(const CXXDeleteExpr * E,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1207 CXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef St,
1208 const LocationContext *LCtx,
1209 CFGBlock::ConstCFGElementRef ElemRef)
1210 : AnyFunctionCall(E, St, LCtx, ElemRef) {}
1211 CXXDeallocatorCall(const CXXDeallocatorCall &Other) = default;
1212
cloneTo(void * Dest)1213 void cloneTo(void *Dest) const override {
1214 new (Dest) CXXDeallocatorCall(*this);
1215 }
1216
1217 public:
getOriginExpr()1218 const CXXDeleteExpr *getOriginExpr() const override {
1219 return cast<CXXDeleteExpr>(AnyFunctionCall::getOriginExpr());
1220 }
1221
getDecl()1222 const FunctionDecl *getDecl() const override {
1223 return getOriginExpr()->getOperatorDelete();
1224 }
1225
getNumArgs()1226 unsigned getNumArgs() const override { return getDecl()->getNumParams(); }
1227
getArgExpr(unsigned Index)1228 const Expr *getArgExpr(unsigned Index) const override {
1229 // CXXDeleteExpr's only have a single argument.
1230 return getOriginExpr()->getArgument();
1231 }
1232
getKind()1233 Kind getKind() const override { return CE_CXXDeallocator; }
getKindAsString()1234 StringRef getKindAsString() const override { return "CXXDeallocatorCall"; }
1235
classof(const CallEvent * CE)1236 static bool classof(const CallEvent *CE) {
1237 return CE->getKind() == CE_CXXDeallocator;
1238 }
1239 };
1240
1241 /// Represents the ways an Objective-C message send can occur.
1242 //
1243 // Note to maintainers: OCM_Message should always be last, since it does not
1244 // need to fit in the Data field's low bits.
1245 enum ObjCMessageKind { OCM_PropertyAccess, OCM_Subscript, OCM_Message };
1246
1247 /// Represents any expression that calls an Objective-C method.
1248 ///
1249 /// This includes all of the kinds listed in ObjCMessageKind.
1250 class ObjCMethodCall : public CallEvent {
1251 friend class CallEventManager;
1252
1253 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
1254
1255 protected:
ObjCMethodCall(const ObjCMessageExpr * Msg,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1256 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
1257 const LocationContext *LCtx,
1258 CFGBlock::ConstCFGElementRef ElemRef)
1259 : CallEvent(Msg, St, LCtx, ElemRef) {
1260 Data = nullptr;
1261 }
1262
1263 ObjCMethodCall(const ObjCMethodCall &Other) = default;
1264
cloneTo(void * Dest)1265 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
1266
1267 void getExtraInvalidatedValues(
1268 ValueList &Values,
1269 RegionAndSymbolInvalidationTraits *ETraits) const override;
1270
1271 /// Check if the selector may have multiple definitions (may have overrides).
1272 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
1273 Selector Sel) const;
1274
1275 public:
getOriginExpr()1276 const ObjCMessageExpr *getOriginExpr() const override {
1277 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
1278 }
1279
getDecl()1280 const ObjCMethodDecl *getDecl() const override {
1281 return getOriginExpr()->getMethodDecl();
1282 }
1283
getNumArgs()1284 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
1285
getArgExpr(unsigned Index)1286 const Expr *getArgExpr(unsigned Index) const override {
1287 return getOriginExpr()->getArg(Index);
1288 }
1289
isInstanceMessage()1290 bool isInstanceMessage() const {
1291 return getOriginExpr()->isInstanceMessage();
1292 }
1293
getMethodFamily()1294 ObjCMethodFamily getMethodFamily() const {
1295 return getOriginExpr()->getMethodFamily();
1296 }
1297
getSelector()1298 Selector getSelector() const { return getOriginExpr()->getSelector(); }
1299
1300 SourceRange getSourceRange() const override;
1301
1302 /// Returns the value of the receiver at the time of this call.
1303 SVal getReceiverSVal() const;
1304
1305 /// Get the interface for the receiver.
1306 ///
1307 /// This works whether this is an instance message or a class message.
1308 /// However, it currently just uses the static type of the receiver.
getReceiverInterface()1309 const ObjCInterfaceDecl *getReceiverInterface() const {
1310 return getOriginExpr()->getReceiverInterface();
1311 }
1312
1313 /// Checks if the receiver refers to 'self' or 'super'.
1314 bool isReceiverSelfOrSuper() const;
1315
1316 /// Returns how the message was written in the source (property access,
1317 /// subscript, or explicit message send).
1318 ObjCMessageKind getMessageKind() const;
1319
1320 /// Returns true if this property access or subscript is a setter (has the
1321 /// form of an assignment).
isSetter()1322 bool isSetter() const {
1323 switch (getMessageKind()) {
1324 case OCM_Message:
1325 llvm_unreachable("This is not a pseudo-object access!");
1326 case OCM_PropertyAccess:
1327 return getNumArgs() > 0;
1328 case OCM_Subscript:
1329 return getNumArgs() > 1;
1330 }
1331 llvm_unreachable("Unknown message kind");
1332 }
1333
1334 // Returns the property accessed by this method, either explicitly via
1335 // property syntax or implicitly via a getter or setter method. Returns
1336 // nullptr if the call is not a prooperty access.
1337 const ObjCPropertyDecl *getAccessedProperty() const;
1338
1339 RuntimeDefinition getRuntimeDefinition() const override;
1340
1341 bool argumentsMayEscape() const override;
1342
1343 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1344 BindingsTy &Bindings) const override;
1345
1346 ArrayRef<ParmVarDecl *> parameters() const override;
1347
getKind()1348 Kind getKind() const override { return CE_ObjCMessage; }
getKindAsString()1349 StringRef getKindAsString() const override { return "ObjCMethodCall"; }
1350
classof(const CallEvent * CA)1351 static bool classof(const CallEvent *CA) {
1352 return CA->getKind() == CE_ObjCMessage;
1353 }
1354 };
1355
1356 /// Manages the lifetime of CallEvent objects.
1357 ///
1358 /// CallEventManager provides a way to create arbitrary CallEvents "on the
1359 /// stack" as if they were value objects by keeping a cache of CallEvent-sized
1360 /// memory blocks. The CallEvents created by CallEventManager are only valid
1361 /// for the lifetime of the OwnedCallEvent that holds them; right now these
1362 /// objects cannot be copied and ownership cannot be transferred.
1363 class CallEventManager {
1364 friend class CallEvent;
1365
1366 llvm::BumpPtrAllocator &Alloc;
1367 SmallVector<void *, 8> Cache;
1368
1369 using CallEventTemplateTy = SimpleFunctionCall;
1370
reclaim(const void * Memory)1371 void reclaim(const void *Memory) {
1372 Cache.push_back(const_cast<void *>(Memory));
1373 }
1374
1375 /// Returns memory that can be initialized as a CallEvent.
allocate()1376 void *allocate() {
1377 if (Cache.empty())
1378 return Alloc.Allocate<CallEventTemplateTy>();
1379 else
1380 return Cache.pop_back_val();
1381 }
1382
1383 template <typename T, typename Arg>
create(Arg A,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1384 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx,
1385 CFGBlock::ConstCFGElementRef ElemRef) {
1386 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1387 "CallEvent subclasses are not all the same size");
1388 return new (allocate()) T(A, St, LCtx, ElemRef);
1389 }
1390
1391 template <typename T, typename Arg1, typename Arg2>
create(Arg1 A1,Arg2 A2,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1392 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx,
1393 CFGBlock::ConstCFGElementRef ElemRef) {
1394 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1395 "CallEvent subclasses are not all the same size");
1396 return new (allocate()) T(A1, A2, St, LCtx, ElemRef);
1397 }
1398
1399 template <typename T, typename Arg1, typename Arg2, typename Arg3>
create(Arg1 A1,Arg2 A2,Arg3 A3,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1400 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1401 const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef) {
1402 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1403 "CallEvent subclasses are not all the same size");
1404 return new (allocate()) T(A1, A2, A3, St, LCtx, ElemRef);
1405 }
1406
1407 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1408 typename Arg4>
create(Arg1 A1,Arg2 A2,Arg3 A3,Arg4 A4,ProgramStateRef St,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1409 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1410 const LocationContext *LCtx, CFGBlock::ConstCFGElementRef ElemRef) {
1411 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1412 "CallEvent subclasses are not all the same size");
1413 return new (allocate()) T(A1, A2, A3, A4, St, LCtx, ElemRef);
1414 }
1415
1416 public:
CallEventManager(llvm::BumpPtrAllocator & alloc)1417 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1418
1419 /// Gets an outside caller given a callee context.
1420 CallEventRef<> getCaller(const StackFrameContext *CalleeCtx,
1421 ProgramStateRef State);
1422
1423 /// Gets a call event for a function call, Objective-C method call,
1424 /// a 'new', or a 'delete' call.
1425 CallEventRef<> getCall(const Stmt *S, ProgramStateRef State,
1426 const LocationContext *LC,
1427 CFGBlock::ConstCFGElementRef ElemRef);
1428
1429 CallEventRef<> getSimpleCall(const CallExpr *E, ProgramStateRef State,
1430 const LocationContext *LCtx,
1431 CFGBlock::ConstCFGElementRef ElemRef);
1432
1433 CallEventRef<ObjCMethodCall>
getObjCMethodCall(const ObjCMessageExpr * E,ProgramStateRef State,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1434 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1435 const LocationContext *LCtx,
1436 CFGBlock::ConstCFGElementRef ElemRef) {
1437 return create<ObjCMethodCall>(E, State, LCtx, ElemRef);
1438 }
1439
1440 CallEventRef<CXXConstructorCall>
getCXXConstructorCall(const CXXConstructExpr * E,const MemRegion * Target,ProgramStateRef State,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1441 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1442 ProgramStateRef State, const LocationContext *LCtx,
1443 CFGBlock::ConstCFGElementRef ElemRef) {
1444 return create<CXXConstructorCall>(E, Target, State, LCtx, ElemRef);
1445 }
1446
1447 CallEventRef<CXXInheritedConstructorCall>
getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr * E,const MemRegion * Target,ProgramStateRef State,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1448 getCXXInheritedConstructorCall(const CXXInheritedCtorInitExpr *E,
1449 const MemRegion *Target, ProgramStateRef State,
1450 const LocationContext *LCtx,
1451 CFGBlock::ConstCFGElementRef ElemRef) {
1452 return create<CXXInheritedConstructorCall>(E, Target, State, LCtx, ElemRef);
1453 }
1454
1455 CallEventRef<CXXDestructorCall>
getCXXDestructorCall(const CXXDestructorDecl * DD,const Stmt * Trigger,const MemRegion * Target,bool IsBase,ProgramStateRef State,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1456 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1457 const MemRegion *Target, bool IsBase,
1458 ProgramStateRef State, const LocationContext *LCtx,
1459 CFGBlock::ConstCFGElementRef ElemRef) {
1460 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx,
1461 ElemRef);
1462 }
1463
1464 CallEventRef<CXXAllocatorCall>
getCXXAllocatorCall(const CXXNewExpr * E,ProgramStateRef State,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1465 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1466 const LocationContext *LCtx,
1467 CFGBlock::ConstCFGElementRef ElemRef) {
1468 return create<CXXAllocatorCall>(E, State, LCtx, ElemRef);
1469 }
1470
1471 CallEventRef<CXXDeallocatorCall>
getCXXDeallocatorCall(const CXXDeleteExpr * E,ProgramStateRef State,const LocationContext * LCtx,CFGBlock::ConstCFGElementRef ElemRef)1472 getCXXDeallocatorCall(const CXXDeleteExpr *E, ProgramStateRef State,
1473 const LocationContext *LCtx,
1474 CFGBlock::ConstCFGElementRef ElemRef) {
1475 return create<CXXDeallocatorCall>(E, State, LCtx, ElemRef);
1476 }
1477 };
1478
1479 template <typename T>
cloneWithState(ProgramStateRef NewState)1480 CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1481 assert(isa<T>(*this) && "Cloning to unrelated type");
1482 static_assert(sizeof(T) == sizeof(CallEvent),
1483 "Subclasses may not add fields");
1484
1485 if (NewState == State)
1486 return cast<T>(this);
1487
1488 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1489 T *Copy = static_cast<T *>(Mgr.allocate());
1490 cloneTo(Copy);
1491 assert(Copy->getKind() == this->getKind() && "Bad copy");
1492
1493 Copy->State = NewState;
1494 return Copy;
1495 }
1496
Release()1497 inline void CallEvent::Release() const {
1498 assert(RefCount > 0 && "Reference count is already zero.");
1499 --RefCount;
1500
1501 if (RefCount > 0)
1502 return;
1503
1504 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1505 Mgr.reclaim(this);
1506
1507 this->~CallEvent();
1508 }
1509
1510 } // namespace ento
1511
1512 } // namespace clang
1513
1514 namespace llvm {
1515
1516 // Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1517 template <class T> struct simplify_type<clang::ento::CallEventRef<T>> {
1518 using SimpleType = const T *;
1519
1520 static SimpleType getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1521 return Val.get();
1522 }
1523 };
1524
1525 } // namespace llvm
1526
1527 #endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
1528