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/Support/Allocator.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include <cassert>
46#include <limits>
47#include <utility>
48
49namespace clang {
50
51class LocationContext;
52class ProgramPoint;
53class ProgramPointTag;
54class StackFrameContext;
55
56namespace ento {
57
58enum CallEventKind {
59 CE_Function,
60 CE_CXXMember,
61 CE_CXXMemberOperator,
62 CE_CXXDestructor,
63 CE_BEG_CXX_INSTANCE_CALLS = CE_CXXMember,
64 CE_END_CXX_INSTANCE_CALLS = CE_CXXDestructor,
65 CE_CXXConstructor,
66 CE_CXXAllocator,
67 CE_BEG_FUNCTION_CALLS = CE_Function,
68 CE_END_FUNCTION_CALLS = CE_CXXAllocator,
69 CE_Block,
70 CE_ObjCMessage
71};
72
73class CallEvent;
74
75/// This class represents a description of a function call using the number of
76/// arguments and the name of the function.
77class CallDescription {
78 friend CallEvent;
79
80 mutable IdentifierInfo *II = nullptr;
81 mutable bool IsLookupDone = false;
82 // The list of the qualified names used to identify the specified CallEvent,
83 // e.g. "{a, b}" represent the qualified names, like "a::b".
84 std::vector<const char *> QualifiedName;
85 unsigned RequiredArgs;
86
87public:
88 const static unsigned NoArgRequirement = std::numeric_limits<unsigned>::max();
89
90 /// Constructs a CallDescription object.
91 ///
92 /// @param QualifiedName The list of the name qualifiers of the function that
93 /// will be matched. The user is allowed to skip any of the qualifiers.
94 /// For example, {"std", "basic_string", "c_str"} would match both
95 /// std::basic_string<...>::c_str() and std::__1::basic_string<...>::c_str().
96 ///
97 /// @param RequiredArgs The number of arguments that is expected to match a
98 /// call. Omit this parameter to match every occurrence of call with a given
99 /// name regardless the number of arguments.
100 CallDescription(ArrayRef<const char *> QualifiedName,
101 unsigned RequiredArgs = NoArgRequirement)
102 : QualifiedName(QualifiedName), RequiredArgs(RequiredArgs) {}
103
104 /// Get the name of the function that this object matches.
105 StringRef getFunctionName() const { return QualifiedName.back(); }
106};
107
108template<typename T = CallEvent>
109class CallEventRef : public IntrusiveRefCntPtr<const T> {
110public:
111 CallEventRef(const T *Call) : IntrusiveRefCntPtr<const T>(Call) {}
112 CallEventRef(const CallEventRef &Orig) : IntrusiveRefCntPtr<const T>(Orig) {}
113
114 CallEventRef<T> cloneWithState(ProgramStateRef State) const {
115 return this->get()->template cloneWithState<T>(State);
116 }
117
118 // Allow implicit conversions to a superclass type, since CallEventRef
119 // behaves like a pointer-to-const.
120 template <typename SuperT>
121 operator CallEventRef<SuperT> () const {
122 return this->get();
123 }
124};
125
126/// \class RuntimeDefinition
127/// Defines the runtime definition of the called function.
128///
129/// Encapsulates the information we have about which Decl will be used
130/// when the call is executed on the given path. When dealing with dynamic
131/// dispatch, the information is based on DynamicTypeInfo and might not be
132/// precise.
133class RuntimeDefinition {
134 /// The Declaration of the function which could be called at runtime.
135 /// NULL if not available.
136 const Decl *D = nullptr;
137
138 /// The region representing an object (ObjC/C++) on which the method is
139 /// called. With dynamic dispatch, the method definition depends on the
140 /// runtime type of this object. NULL when the DynamicTypeInfo is
141 /// precise.
142 const MemRegion *R = nullptr;
143
144public:
145 RuntimeDefinition() = default;
146 RuntimeDefinition(const Decl *InD): D(InD) {}
147 RuntimeDefinition(const Decl *InD, const MemRegion *InR): D(InD), R(InR) {}
148
149 const Decl *getDecl() { return D; }
150
151 /// Check if the definition we have is precise.
152 /// If not, it is possible that the call dispatches to another definition at
153 /// execution time.
154 bool mayHaveOtherDefinitions() { return R != nullptr; }
155
156 /// When other definitions are possible, returns the region whose runtime type
157 /// determines the method definition.
158 const MemRegion *getDispatchRegion() { return R; }
159};
160
161/// Represents an abstract call to a function or method along a
162/// particular path.
163///
164/// CallEvents are created through the factory methods of CallEventManager.
165///
166/// CallEvents should always be cheap to create and destroy. In order for
167/// CallEventManager to be able to re-use CallEvent-sized memory blocks,
168/// subclasses of CallEvent may not add any data members to the base class.
169/// Use the "Data" and "Location" fields instead.
170class CallEvent {
171public:
172 using Kind = CallEventKind;
173
174private:
175 ProgramStateRef State;
176 const LocationContext *LCtx;
177 llvm::PointerUnion<const Expr *, const Decl *> Origin;
178
179protected:
180 // This is user data for subclasses.
181 const void *Data;
182
183 // This is user data for subclasses.
184 // This should come right before RefCount, so that the two fields can be
185 // packed together on LP64 platforms.
186 SourceLocation Location;
187
188private:
189 template <typename T> friend struct llvm::IntrusiveRefCntPtrInfo;
190
191 mutable unsigned RefCount = 0;
192
193 void Retain() const { ++RefCount; }
194 void Release() const;
195
196protected:
197 friend class CallEventManager;
198
199 CallEvent(const Expr *E, ProgramStateRef state, const LocationContext *lctx)
200 : State(std::move(state)), LCtx(lctx), Origin(E) {}
201
202 CallEvent(const Decl *D, ProgramStateRef state, const LocationContext *lctx)
203 : State(std::move(state)), LCtx(lctx), Origin(D) {}
204
205 // DO NOT MAKE PUBLIC
206 CallEvent(const CallEvent &Original)
207 : State(Original.State), LCtx(Original.LCtx), Origin(Original.Origin),
208 Data(Original.Data), Location(Original.Location) {}
209
210 /// Copies this CallEvent, with vtable intact, into a new block of memory.
211 virtual void cloneTo(void *Dest) const = 0;
212
213 /// Get the value of arbitrary expressions at this point in the path.
214 SVal getSVal(const Stmt *S) const {
215 return getState()->getSVal(S, getLocationContext());
216 }
217
218 using ValueList = SmallVectorImpl<SVal>;
219
220 /// Used to specify non-argument regions that will be invalidated as a
221 /// result of this call.
222 virtual void getExtraInvalidatedValues(ValueList &Values,
223 RegionAndSymbolInvalidationTraits *ETraits) const {}
224
225public:
226 CallEvent &operator=(const CallEvent &) = delete;
227 virtual ~CallEvent() = default;
228
229 /// Returns the kind of call this is.
230 virtual Kind getKind() const = 0;
231
232 /// Returns the declaration of the function or method that will be
233 /// called. May be null.
234 virtual const Decl *getDecl() const {
235 return Origin.dyn_cast<const Decl *>();
236 }
237
238 /// The state in which the call is being evaluated.
239 const ProgramStateRef &getState() const {
240 return State;
241 }
242
243 /// The context in which the call is being evaluated.
244 const LocationContext *getLocationContext() const {
245 return LCtx;
246 }
247
248 /// Returns the definition of the function or method that will be
249 /// called.
250 virtual RuntimeDefinition getRuntimeDefinition() const = 0;
251
252 /// Returns the expression whose value will be the result of this call.
253 /// May be null.
254 const Expr *getOriginExpr() const {
255 return Origin.dyn_cast<const Expr *>();
256 }
257
258 /// Returns the number of arguments (explicit and implicit).
259 ///
260 /// Note that this may be greater than the number of parameters in the
261 /// callee's declaration, and that it may include arguments not written in
262 /// the source.
263 virtual unsigned getNumArgs() const = 0;
264
265 /// Returns true if the callee is known to be from a system header.
266 bool isInSystemHeader() const {
267 const Decl *D = getDecl();
268 if (!D)
269 return false;
270
271 SourceLocation Loc = D->getLocation();
272 if (Loc.isValid()) {
273 const SourceManager &SM =
274 getState()->getStateManager().getContext().getSourceManager();
275 return SM.isInSystemHeader(D->getLocation());
276 }
277
278 // Special case for implicitly-declared global operator new/delete.
279 // These should be considered system functions.
280 if (const auto *FD = dyn_cast<FunctionDecl>(D))
281 return FD->isOverloadedOperator() && FD->isImplicit() && FD->isGlobal();
282
283 return false;
284 }
285
286 /// Returns true if the CallEvent is a call to a function that matches
287 /// the CallDescription.
288 ///
289 /// Note that this function is not intended to be used to match Obj-C method
290 /// calls.
291 bool isCalled(const CallDescription &CD) const;
292
293 /// Returns a source range for the entire call, suitable for
294 /// outputting in diagnostics.
295 virtual SourceRange getSourceRange() const {
296 return getOriginExpr()->getSourceRange();
297 }
298
299 /// Returns the value of a given argument at the time of the call.
300 virtual SVal getArgSVal(unsigned Index) const;
301
302 /// Returns the expression associated with a given argument.
303 /// May be null if this expression does not appear in the source.
304 virtual const Expr *getArgExpr(unsigned Index) const { return nullptr; }
305
306 /// Returns the source range for errors associated with this argument.
307 ///
308 /// May be invalid if the argument is not written in the source.
309 virtual SourceRange getArgSourceRange(unsigned Index) const;
310
311 /// Returns the result type, adjusted for references.
312 QualType getResultType() const;
313
314 /// Returns the return value of the call.
315 ///
316 /// This should only be called if the CallEvent was created using a state in
317 /// which the return value has already been bound to the origin expression.
318 SVal getReturnValue() const;
319
320 /// Returns true if the type of any of the non-null arguments satisfies
321 /// the condition.
322 bool hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const;
323
324 /// Returns true if any of the arguments appear to represent callbacks.
325 bool hasNonZeroCallbackArg() const;
326
327 /// Returns true if any of the arguments is void*.
328 bool hasVoidPointerToNonConstArg() const;
329
330 /// Returns true if any of the arguments are known to escape to long-
331 /// term storage, even if this method will not modify them.
332 // NOTE: The exact semantics of this are still being defined!
333 // We don't really want a list of hardcoded exceptions in the long run,
334 // but we don't want duplicated lists of known APIs in the short term either.
335 virtual bool argumentsMayEscape() const {
336 return hasNonZeroCallbackArg();
337 }
338
339 /// Returns true if the callee is an externally-visible function in the
340 /// top-level namespace, such as \c malloc.
341 ///
342 /// You can use this call to determine that a particular function really is
343 /// a library function and not, say, a C++ member function with the same name.
344 ///
345 /// If a name is provided, the function must additionally match the given
346 /// name.
347 ///
348 /// Note that this deliberately excludes C++ library functions in the \c std
349 /// namespace, but will include C library functions accessed through the
350 /// \c std namespace. This also does not check if the function is declared
351 /// as 'extern "C"', or if it uses C++ name mangling.
352 // FIXME: Add a helper for checking namespaces.
353 // FIXME: Move this down to AnyFunctionCall once checkers have more
354 // precise callbacks.
355 bool isGlobalCFunction(StringRef SpecificName = StringRef()) const;
356
357 /// Returns the name of the callee, if its name is a simple identifier.
358 ///
359 /// Note that this will fail for Objective-C methods, blocks, and C++
360 /// overloaded operators. The former is named by a Selector rather than a
361 /// simple identifier, and the latter two do not have names.
362 // FIXME: Move this down to AnyFunctionCall once checkers have more
363 // precise callbacks.
364 const IdentifierInfo *getCalleeIdentifier() const {
365 const auto *ND = dyn_cast_or_null<NamedDecl>(getDecl());
366 if (!ND)
367 return nullptr;
368 return ND->getIdentifier();
369 }
370
371 /// Returns an appropriate ProgramPoint for this call.
372 ProgramPoint getProgramPoint(bool IsPreVisit = false,
373 const ProgramPointTag *Tag = nullptr) const;
374
375 /// Returns a new state with all argument regions invalidated.
376 ///
377 /// This accepts an alternate state in case some processing has already
378 /// occurred.
379 ProgramStateRef invalidateRegions(unsigned BlockCount,
380 ProgramStateRef Orig = nullptr) const;
381
382 using FrameBindingTy = std::pair<Loc, SVal>;
383 using BindingsTy = SmallVectorImpl<FrameBindingTy>;
384
385 /// Populates the given SmallVector with the bindings in the callee's stack
386 /// frame at the start of this call.
387 virtual void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
388 BindingsTy &Bindings) const = 0;
389
390 /// Returns a copy of this CallEvent, but using the given state.
391 template <typename T>
392 CallEventRef<T> cloneWithState(ProgramStateRef NewState) const;
393
394 /// Returns a copy of this CallEvent, but using the given state.
395 CallEventRef<> cloneWithState(ProgramStateRef NewState) const {
396 return cloneWithState<CallEvent>(NewState);
397 }
398
399 /// Returns true if this is a statement is a function or method call
400 /// of some kind.
401 static bool isCallStmt(const Stmt *S);
402
403 /// Returns the result type of a function or method declaration.
404 ///
405 /// This will return a null QualType if the result type cannot be determined.
406 static QualType getDeclaredResultType(const Decl *D);
407
408 /// Returns true if the given decl is known to be variadic.
409 ///
410 /// \p D must not be null.
411 static bool isVariadic(const Decl *D);
412
413 /// Returns AnalysisDeclContext for the callee stack frame.
414 /// Currently may fail; returns null on failure.
415 AnalysisDeclContext *getCalleeAnalysisDeclContext() const;
416
417 /// Returns the callee stack frame. That stack frame will only be entered
418 /// during analysis if the call is inlined, but it may still be useful
419 /// in intermediate calculations even if the call isn't inlined.
420 /// May fail; returns null on failure.
421 const StackFrameContext *getCalleeStackFrame() const;
422
423 /// Returns memory location for a parameter variable within the callee stack
424 /// frame. May fail; returns null on failure.
425 const VarRegion *getParameterLocation(unsigned Index) const;
426
427 /// Returns true if on the current path, the argument was constructed by
428 /// calling a C++ constructor over it. This is an internal detail of the
429 /// analysis which doesn't necessarily represent the program semantics:
430 /// if we are supposed to construct an argument directly, we may still
431 /// not do that because we don't know how (i.e., construction context is
432 /// unavailable in the CFG or not supported by the analyzer).
433 bool isArgumentConstructedDirectly(unsigned Index) const {
434 // This assumes that the object was not yet removed from the state.
435 return ExprEngine::getObjectUnderConstruction(
436 getState(), {getOriginExpr(), Index}, getLocationContext()).hasValue();
437 }
438
439 /// Some calls have parameter numbering mismatched from argument numbering.
440 /// This function converts an argument index to the corresponding
441 /// parameter index. Returns None is the argument doesn't correspond
442 /// to any parameter variable.
443 virtual Optional<unsigned>
444 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const {
445 return ASTArgumentIndex;
446 }
447
448 /// Some call event sub-classes conveniently adjust mismatching AST indices
449 /// to match parameter indices. This function converts an argument index
450 /// as understood by CallEvent to the argument index as understood by the AST.
451 virtual unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const {
452 return CallArgumentIndex;
453 }
454
455 // Iterator access to formal parameters and their types.
456private:
457 struct GetTypeFn {
458 QualType operator()(ParmVarDecl *PD) const { return PD->getType(); }
459 };
460
461public:
462 /// Return call's formal parameters.
463 ///
464 /// Remember that the number of formal parameters may not match the number
465 /// of arguments for all calls. However, the first parameter will always
466 /// correspond with the argument value returned by \c getArgSVal(0).
467 virtual ArrayRef<ParmVarDecl *> parameters() const = 0;
468
469 using param_type_iterator =
470 llvm::mapped_iterator<ArrayRef<ParmVarDecl *>::iterator, GetTypeFn>;
471
472 /// Returns an iterator over the types of the call's formal parameters.
473 ///
474 /// This uses the callee decl found by default name lookup rather than the
475 /// definition because it represents a public interface, and probably has
476 /// more annotations.
477 param_type_iterator param_type_begin() const {
478 return llvm::map_iterator(parameters().begin(), GetTypeFn());
479 }
480 /// \sa param_type_begin()
481 param_type_iterator param_type_end() const {
482 return llvm::map_iterator(parameters().end(), GetTypeFn());
483 }
484
485 // For debugging purposes only
486 void dump(raw_ostream &Out) const;
487 void dump() const;
488};
489
490/// Represents a call to any sort of function that might have a
491/// FunctionDecl.
492class AnyFunctionCall : public CallEvent {
493protected:
494 AnyFunctionCall(const Expr *E, ProgramStateRef St,
495 const LocationContext *LCtx)
496 : CallEvent(E, St, LCtx) {}
497 AnyFunctionCall(const Decl *D, ProgramStateRef St,
498 const LocationContext *LCtx)
499 : CallEvent(D, St, LCtx) {}
500 AnyFunctionCall(const AnyFunctionCall &Other) = default;
501
502public:
503 // This function is overridden by subclasses, but they must return
504 // a FunctionDecl.
505 const FunctionDecl *getDecl() const override {
506 return cast<FunctionDecl>(CallEvent::getDecl());
507 }
508
509 RuntimeDefinition getRuntimeDefinition() const override;
510
511 bool argumentsMayEscape() const override;
512
513 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
514 BindingsTy &Bindings) const override;
515
516 ArrayRef<ParmVarDecl *> parameters() const override;
517
518 static bool classof(const CallEvent *CA) {
519 return CA->getKind() >= CE_BEG_FUNCTION_CALLS &&
520 CA->getKind() <= CE_END_FUNCTION_CALLS;
521 }
522};
523
524/// Represents a C function or static C++ member function call.
525///
526/// Example: \c fun()
527class SimpleFunctionCall : public AnyFunctionCall {
528 friend class CallEventManager;
529
530protected:
531 SimpleFunctionCall(const CallExpr *CE, ProgramStateRef St,
532 const LocationContext *LCtx)
533 : AnyFunctionCall(CE, St, LCtx) {}
534 SimpleFunctionCall(const SimpleFunctionCall &Other) = default;
535
536 void cloneTo(void *Dest) const override {
537 new (Dest) SimpleFunctionCall(*this);
538 }
539
540public:
541 virtual const CallExpr *getOriginExpr() const {
542 return cast<CallExpr>(AnyFunctionCall::getOriginExpr());
543 }
544
545 const FunctionDecl *getDecl() const override;
546
547 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
548
549 const Expr *getArgExpr(unsigned Index) const override {
550 return getOriginExpr()->getArg(Index);
551 }
552
553 Kind getKind() const override { return CE_Function; }
554
555 static bool classof(const CallEvent *CA) {
556 return CA->getKind() == CE_Function;
557 }
558};
559
560/// Represents a call to a block.
561///
562/// Example: <tt>^{ /* ... */ }()</tt>
563class BlockCall : public CallEvent {
564 friend class CallEventManager;
565
566protected:
567 BlockCall(const CallExpr *CE, ProgramStateRef St,
568 const LocationContext *LCtx)
569 : CallEvent(CE, St, LCtx) {}
570 BlockCall(const BlockCall &Other) = default;
571
572 void cloneTo(void *Dest) const override { new (Dest) BlockCall(*this); }
573
574 void getExtraInvalidatedValues(ValueList &Values,
575 RegionAndSymbolInvalidationTraits *ETraits) const override;
576
577public:
578 virtual const CallExpr *getOriginExpr() const {
579 return cast<CallExpr>(CallEvent::getOriginExpr());
580 }
581
582 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
583
584 const Expr *getArgExpr(unsigned Index) const override {
585 return getOriginExpr()->getArg(Index);
586 }
587
588 /// Returns the region associated with this instance of the block.
589 ///
590 /// This may be NULL if the block's origin is unknown.
591 const BlockDataRegion *getBlockRegion() const;
592
593 const BlockDecl *getDecl() const override {
594 const BlockDataRegion *BR = getBlockRegion();
595 if (!BR)
596 return nullptr;
597 return BR->getDecl();
598 }
599
600 bool isConversionFromLambda() const {
601 const BlockDecl *BD = getDecl();
602 if (!BD)
603 return false;
604
605 return BD->isConversionFromLambda();
606 }
607
608 /// For a block converted from a C++ lambda, returns the block
609 /// VarRegion for the variable holding the captured C++ lambda record.
610 const VarRegion *getRegionStoringCapturedLambda() const {
611 assert(isConversionFromLambda());
612 const BlockDataRegion *BR = getBlockRegion();
613 assert(BR && "Block converted from lambda must have a block region");
614
615 auto I = BR->referenced_vars_begin();
616 assert(I != BR->referenced_vars_end());
617
618 return I.getCapturedRegion();
619 }
620
621 RuntimeDefinition getRuntimeDefinition() const override {
622 if (!isConversionFromLambda())
623 return RuntimeDefinition(getDecl());
624
625 // Clang converts lambdas to blocks with an implicit user-defined
626 // conversion operator method on the lambda record that looks (roughly)
627 // like:
628 //
629 // typedef R(^block_type)(P1, P2, ...);
630 // operator block_type() const {
631 // auto Lambda = *this;
632 // return ^(P1 p1, P2 p2, ...){
633 // /* return Lambda(p1, p2, ...); */
634 // };
635 // }
636 //
637 // Here R is the return type of the lambda and P1, P2, ... are
638 // its parameter types. 'Lambda' is a fake VarDecl captured by the block
639 // that is initialized to a copy of the lambda.
640 //
641 // Sema leaves the body of a lambda-converted block empty (it is
642 // produced by CodeGen), so we can't analyze it directly. Instead, we skip
643 // the block body and analyze the operator() method on the captured lambda.
644 const VarDecl *LambdaVD = getRegionStoringCapturedLambda()->getDecl();
645 const CXXRecordDecl *LambdaDecl = LambdaVD->getType()->getAsCXXRecordDecl();
646 CXXMethodDecl* LambdaCallOperator = LambdaDecl->getLambdaCallOperator();
647
648 return RuntimeDefinition(LambdaCallOperator);
649 }
650
651 bool argumentsMayEscape() const override {
652 return true;
653 }
654
655 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
656 BindingsTy &Bindings) const override;
657
658 ArrayRef<ParmVarDecl*> parameters() const override;
659
660 Kind getKind() const override { return CE_Block; }
661
662 static bool classof(const CallEvent *CA) {
663 return CA->getKind() == CE_Block;
664 }
665};
666
667/// Represents a non-static C++ member function call, no matter how
668/// it is written.
669class CXXInstanceCall : public AnyFunctionCall {
670protected:
671 CXXInstanceCall(const CallExpr *CE, ProgramStateRef St,
672 const LocationContext *LCtx)
673 : AnyFunctionCall(CE, St, LCtx) {}
674 CXXInstanceCall(const FunctionDecl *D, ProgramStateRef St,
675 const LocationContext *LCtx)
676 : AnyFunctionCall(D, St, LCtx) {}
677 CXXInstanceCall(const CXXInstanceCall &Other) = default;
678
679 void getExtraInvalidatedValues(ValueList &Values,
680 RegionAndSymbolInvalidationTraits *ETraits) const override;
681
682public:
683 /// Returns the expression representing the implicit 'this' object.
684 virtual const Expr *getCXXThisExpr() const { return nullptr; }
685
686 /// Returns the value of the implicit 'this' object.
687 virtual SVal getCXXThisVal() const;
688
689 const FunctionDecl *getDecl() const override;
690
691 RuntimeDefinition getRuntimeDefinition() const override;
692
693 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
694 BindingsTy &Bindings) const override;
695
696 static bool classof(const CallEvent *CA) {
697 return CA->getKind() >= CE_BEG_CXX_INSTANCE_CALLS &&
698 CA->getKind() <= CE_END_CXX_INSTANCE_CALLS;
699 }
700};
701
702/// Represents a non-static C++ member function call.
703///
704/// Example: \c obj.fun()
705class CXXMemberCall : public CXXInstanceCall {
706 friend class CallEventManager;
707
708protected:
709 CXXMemberCall(const CXXMemberCallExpr *CE, ProgramStateRef St,
710 const LocationContext *LCtx)
711 : CXXInstanceCall(CE, St, LCtx) {}
712 CXXMemberCall(const CXXMemberCall &Other) = default;
713
714 void cloneTo(void *Dest) const override { new (Dest) CXXMemberCall(*this); }
715
716public:
717 virtual const CXXMemberCallExpr *getOriginExpr() const {
718 return cast<CXXMemberCallExpr>(CXXInstanceCall::getOriginExpr());
719 }
720
721 unsigned getNumArgs() const override {
722 if (const CallExpr *CE = getOriginExpr())
723 return CE->getNumArgs();
724 return 0;
725 }
726
727 const Expr *getArgExpr(unsigned Index) const override {
728 return getOriginExpr()->getArg(Index);
729 }
730
731 const Expr *getCXXThisExpr() const override;
732
733 RuntimeDefinition getRuntimeDefinition() const override;
734
735 Kind getKind() const override { return CE_CXXMember; }
736
737 static bool classof(const CallEvent *CA) {
738 return CA->getKind() == CE_CXXMember;
739 }
740};
741
742/// Represents a C++ overloaded operator call where the operator is
743/// implemented as a non-static member function.
744///
745/// Example: <tt>iter + 1</tt>
746class CXXMemberOperatorCall : public CXXInstanceCall {
747 friend class CallEventManager;
748
749protected:
750 CXXMemberOperatorCall(const CXXOperatorCallExpr *CE, ProgramStateRef St,
751 const LocationContext *LCtx)
752 : CXXInstanceCall(CE, St, LCtx) {}
753 CXXMemberOperatorCall(const CXXMemberOperatorCall &Other) = default;
754
755 void cloneTo(void *Dest) const override {
756 new (Dest) CXXMemberOperatorCall(*this);
757 }
758
759public:
760 virtual const CXXOperatorCallExpr *getOriginExpr() const {
761 return cast<CXXOperatorCallExpr>(CXXInstanceCall::getOriginExpr());
762 }
763
764 unsigned getNumArgs() const override {
765 return getOriginExpr()->getNumArgs() - 1;
766 }
767
768 const Expr *getArgExpr(unsigned Index) const override {
769 return getOriginExpr()->getArg(Index + 1);
770 }
771
772 const Expr *getCXXThisExpr() const override;
773
774 Kind getKind() const override { return CE_CXXMemberOperator; }
775
776 static bool classof(const CallEvent *CA) {
777 return CA->getKind() == CE_CXXMemberOperator;
778 }
779
780 Optional<unsigned>
781 getAdjustedParameterIndex(unsigned ASTArgumentIndex) const override {
782 // For member operator calls argument 0 on the expression corresponds
783 // to implicit this-parameter on the declaration.
784 return (ASTArgumentIndex > 0) ? Optional<unsigned>(ASTArgumentIndex - 1)
785 : None;
786 }
787
788 unsigned getASTArgumentIndex(unsigned CallArgumentIndex) const override {
789 // For member operator calls argument 0 on the expression corresponds
790 // to implicit this-parameter on the declaration.
791 return CallArgumentIndex + 1;
792 }
793};
794
795/// Represents an implicit call to a C++ destructor.
796///
797/// This can occur at the end of a scope (for automatic objects), at the end
798/// of a full-expression (for temporaries), or as part of a delete.
799class CXXDestructorCall : public CXXInstanceCall {
800 friend class CallEventManager;
801
802protected:
803 using DtorDataTy = llvm::PointerIntPair<const MemRegion *, 1, bool>;
804
805 /// Creates an implicit destructor.
806 ///
807 /// \param DD The destructor that will be called.
808 /// \param Trigger The statement whose completion causes this destructor call.
809 /// \param Target The object region to be destructed.
810 /// \param St The path-sensitive state at this point in the program.
811 /// \param LCtx The location context at this point in the program.
812 CXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
813 const MemRegion *Target, bool IsBaseDestructor,
814 ProgramStateRef St, const LocationContext *LCtx)
815 : CXXInstanceCall(DD, St, LCtx) {
816 Data = DtorDataTy(Target, IsBaseDestructor).getOpaqueValue();
817 Location = Trigger->getEndLoc();
818 }
819
820 CXXDestructorCall(const CXXDestructorCall &Other) = default;
821
822 void cloneTo(void *Dest) const override {new (Dest) CXXDestructorCall(*this);}
823
824public:
825 SourceRange getSourceRange() const override { return Location; }
826 unsigned getNumArgs() const override { return 0; }
827
828 RuntimeDefinition getRuntimeDefinition() const override;
829
830 /// Returns the value of the implicit 'this' object.
831 SVal getCXXThisVal() const override;
832
833 /// Returns true if this is a call to a base class destructor.
834 bool isBaseDestructor() const {
835 return DtorDataTy::getFromOpaqueValue(Data).getInt();
836 }
837
838 Kind getKind() const override { return CE_CXXDestructor; }
839
840 static bool classof(const CallEvent *CA) {
841 return CA->getKind() == CE_CXXDestructor;
842 }
843};
844
845/// Represents a call to a C++ constructor.
846///
847/// Example: \c T(1)
848class CXXConstructorCall : public AnyFunctionCall {
849 friend class CallEventManager;
850
851protected:
852 /// Creates a constructor call.
853 ///
854 /// \param CE The constructor expression as written in the source.
855 /// \param Target The region where the object should be constructed. If NULL,
856 /// a new symbolic region will be used.
857 /// \param St The path-sensitive state at this point in the program.
858 /// \param LCtx The location context at this point in the program.
859 CXXConstructorCall(const CXXConstructExpr *CE, const MemRegion *Target,
860 ProgramStateRef St, const LocationContext *LCtx)
861 : AnyFunctionCall(CE, St, LCtx) {
862 Data = Target;
863 }
864
865 CXXConstructorCall(const CXXConstructorCall &Other) = default;
866
867 void cloneTo(void *Dest) const override { new (Dest) CXXConstructorCall(*this); }
868
869 void getExtraInvalidatedValues(ValueList &Values,
870 RegionAndSymbolInvalidationTraits *ETraits) const override;
871
872public:
873 virtual const CXXConstructExpr *getOriginExpr() const {
874 return cast<CXXConstructExpr>(AnyFunctionCall::getOriginExpr());
875 }
876
877 const CXXConstructorDecl *getDecl() const override {
878 return getOriginExpr()->getConstructor();
879 }
880
881 unsigned getNumArgs() const override { return getOriginExpr()->getNumArgs(); }
882
883 const Expr *getArgExpr(unsigned Index) const override {
884 return getOriginExpr()->getArg(Index);
885 }
886
887 /// Returns the value of the implicit 'this' object.
888 SVal getCXXThisVal() const;
889
890 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
891 BindingsTy &Bindings) const override;
892
893 Kind getKind() const override { return CE_CXXConstructor; }
894
895 static bool classof(const CallEvent *CA) {
896 return CA->getKind() == CE_CXXConstructor;
897 }
898};
899
900/// Represents the memory allocation call in a C++ new-expression.
901///
902/// This is a call to "operator new".
903class CXXAllocatorCall : public AnyFunctionCall {
904 friend class CallEventManager;
905
906protected:
907 CXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef St,
908 const LocationContext *LCtx)
909 : AnyFunctionCall(E, St, LCtx) {}
910 CXXAllocatorCall(const CXXAllocatorCall &Other) = default;
911
912 void cloneTo(void *Dest) const override { new (Dest) CXXAllocatorCall(*this); }
913
914public:
915 virtual const CXXNewExpr *getOriginExpr() const {
916 return cast<CXXNewExpr>(AnyFunctionCall::getOriginExpr());
917 }
918
919 const FunctionDecl *getDecl() const override {
920 return getOriginExpr()->getOperatorNew();
921 }
922
923 /// Number of non-placement arguments to the call. It is equal to 2 for
924 /// C++17 aligned operator new() calls that have alignment implicitly
925 /// passed as the second argument, and to 1 for other operator new() calls.
926 unsigned getNumImplicitArgs() const {
927 return getOriginExpr()->passAlignment() ? 2 : 1;
928 }
929
930 unsigned getNumArgs() const override {
931 return getOriginExpr()->getNumPlacementArgs() + getNumImplicitArgs();
932 }
933
934 const Expr *getArgExpr(unsigned Index) const override {
935 // The first argument of an allocator call is the size of the allocation.
936 if (Index < getNumImplicitArgs())
937 return nullptr;
938 return getOriginExpr()->getPlacementArg(Index - getNumImplicitArgs());
939 }
940
941 /// Number of placement arguments to the operator new() call. For example,
942 /// standard std::nothrow operator new and standard placement new both have
943 /// 1 implicit argument (size) and 1 placement argument, while regular
944 /// operator new() has 1 implicit argument and 0 placement arguments.
945 const Expr *getPlacementArgExpr(unsigned Index) const {
946 return getOriginExpr()->getPlacementArg(Index);
947 }
948
949 Kind getKind() const override { return CE_CXXAllocator; }
950
951 static bool classof(const CallEvent *CE) {
952 return CE->getKind() == CE_CXXAllocator;
953 }
954};
955
956/// Represents the ways an Objective-C message send can occur.
957//
958// Note to maintainers: OCM_Message should always be last, since it does not
959// need to fit in the Data field's low bits.
960enum ObjCMessageKind {
961 OCM_PropertyAccess,
962 OCM_Subscript,
963 OCM_Message
964};
965
966/// Represents any expression that calls an Objective-C method.
967///
968/// This includes all of the kinds listed in ObjCMessageKind.
969class ObjCMethodCall : public CallEvent {
970 friend class CallEventManager;
971
972 const PseudoObjectExpr *getContainingPseudoObjectExpr() const;
973
974protected:
975 ObjCMethodCall(const ObjCMessageExpr *Msg, ProgramStateRef St,
976 const LocationContext *LCtx)
977 : CallEvent(Msg, St, LCtx) {
978 Data = nullptr;
979 }
980
981 ObjCMethodCall(const ObjCMethodCall &Other) = default;
982
983 void cloneTo(void *Dest) const override { new (Dest) ObjCMethodCall(*this); }
984
985 void getExtraInvalidatedValues(ValueList &Values,
986 RegionAndSymbolInvalidationTraits *ETraits) const override;
987
988 /// Check if the selector may have multiple definitions (may have overrides).
989 virtual bool canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
990 Selector Sel) const;
991
992public:
993 virtual const ObjCMessageExpr *getOriginExpr() const {
994 return cast<ObjCMessageExpr>(CallEvent::getOriginExpr());
995 }
996
997 const ObjCMethodDecl *getDecl() const override {
998 return getOriginExpr()->getMethodDecl();
999 }
1000
1001 unsigned getNumArgs() const override {
1002 return getOriginExpr()->getNumArgs();
1003 }
1004
1005 const Expr *getArgExpr(unsigned Index) const override {
1006 return getOriginExpr()->getArg(Index);
1007 }
1008
1009 bool isInstanceMessage() const {
1010 return getOriginExpr()->isInstanceMessage();
1011 }
1012
1013 ObjCMethodFamily getMethodFamily() const {
1014 return getOriginExpr()->getMethodFamily();
1015 }
1016
1017 Selector getSelector() const {
1018 return getOriginExpr()->getSelector();
1019 }
1020
1021 SourceRange getSourceRange() const override;
1022
1023 /// Returns the value of the receiver at the time of this call.
1024 SVal getReceiverSVal() const;
1025
1026 /// Return the value of 'self' if available.
1027 SVal getSelfSVal() const;
1028
1029 /// Get the interface for the receiver.
1030 ///
1031 /// This works whether this is an instance message or a class message.
1032 /// However, it currently just uses the static type of the receiver.
1033 const ObjCInterfaceDecl *getReceiverInterface() const {
1034 return getOriginExpr()->getReceiverInterface();
1035 }
1036
1037 /// Checks if the receiver refers to 'self' or 'super'.
1038 bool isReceiverSelfOrSuper() const;
1039
1040 /// Returns how the message was written in the source (property access,
1041 /// subscript, or explicit message send).
1042 ObjCMessageKind getMessageKind() const;
1043
1044 /// Returns true if this property access or subscript is a setter (has the
1045 /// form of an assignment).
1046 bool isSetter() const {
1047 switch (getMessageKind()) {
1048 case OCM_Message:
1049 llvm_unreachable("This is not a pseudo-object access!");
1050 case OCM_PropertyAccess:
1051 return getNumArgs() > 0;
1052 case OCM_Subscript:
1053 return getNumArgs() > 1;
1054 }
1055 llvm_unreachable("Unknown message kind");
1056 }
1057
1058 // Returns the property accessed by this method, either explicitly via
1059 // property syntax or implicitly via a getter or setter method. Returns
1060 // nullptr if the call is not a prooperty access.
1061 const ObjCPropertyDecl *getAccessedProperty() const;
1062
1063 RuntimeDefinition getRuntimeDefinition() const override;
1064
1065 bool argumentsMayEscape() const override;
1066
1067 void getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
1068 BindingsTy &Bindings) const override;
1069
1070 ArrayRef<ParmVarDecl*> parameters() const override;
1071
1072 Kind getKind() const override { return CE_ObjCMessage; }
1073
1074 static bool classof(const CallEvent *CA) {
1075 return CA->getKind() == CE_ObjCMessage;
1076 }
1077};
1078
1079/// Manages the lifetime of CallEvent objects.
1080///
1081/// CallEventManager provides a way to create arbitrary CallEvents "on the
1082/// stack" as if they were value objects by keeping a cache of CallEvent-sized
1083/// memory blocks. The CallEvents created by CallEventManager are only valid
1084/// for the lifetime of the OwnedCallEvent that holds them; right now these
1085/// objects cannot be copied and ownership cannot be transferred.
1086class CallEventManager {
1087 friend class CallEvent;
1088
1089 llvm::BumpPtrAllocator &Alloc;
1090 SmallVector<void *, 8> Cache;
1091
1092 using CallEventTemplateTy = SimpleFunctionCall;
1093
1094 void reclaim(const void *Memory) {
1095 Cache.push_back(const_cast<void *>(Memory));
1096 }
1097
1098 /// Returns memory that can be initialized as a CallEvent.
1099 void *allocate() {
1100 if (Cache.empty())
1101 return Alloc.Allocate<CallEventTemplateTy>();
1102 else
1103 return Cache.pop_back_val();
1104 }
1105
1106 template <typename T, typename Arg>
1107 T *create(Arg A, ProgramStateRef St, const LocationContext *LCtx) {
1108 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1109 "CallEvent subclasses are not all the same size");
1110 return new (allocate()) T(A, St, LCtx);
1111 }
1112
1113 template <typename T, typename Arg1, typename Arg2>
1114 T *create(Arg1 A1, Arg2 A2, ProgramStateRef St, const LocationContext *LCtx) {
1115 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1116 "CallEvent subclasses are not all the same size");
1117 return new (allocate()) T(A1, A2, St, LCtx);
1118 }
1119
1120 template <typename T, typename Arg1, typename Arg2, typename Arg3>
1121 T *create(Arg1 A1, Arg2 A2, Arg3 A3, ProgramStateRef St,
1122 const LocationContext *LCtx) {
1123 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1124 "CallEvent subclasses are not all the same size");
1125 return new (allocate()) T(A1, A2, A3, St, LCtx);
1126 }
1127
1128 template <typename T, typename Arg1, typename Arg2, typename Arg3,
1129 typename Arg4>
1130 T *create(Arg1 A1, Arg2 A2, Arg3 A3, Arg4 A4, ProgramStateRef St,
1131 const LocationContext *LCtx) {
1132 static_assert(sizeof(T) == sizeof(CallEventTemplateTy),
1133 "CallEvent subclasses are not all the same size");
1134 return new (allocate()) T(A1, A2, A3, A4, St, LCtx);
1135 }
1136
1137public:
1138 CallEventManager(llvm::BumpPtrAllocator &alloc) : Alloc(alloc) {}
1139
1140 /// Gets an outside caller given a callee context.
1141 CallEventRef<>
1142 getCaller(const StackFrameContext *CalleeCtx, ProgramStateRef State);
1143
1144 /// Gets a call event for a function call, Objective-C method call,
1145 /// or a 'new' call.
1146 CallEventRef<>
1147 getCall(const Stmt *S, ProgramStateRef State,
1148 const LocationContext *LC);
1149
1150 CallEventRef<>
1151 getSimpleCall(const CallExpr *E, ProgramStateRef State,
1152 const LocationContext *LCtx);
1153
1154 CallEventRef<ObjCMethodCall>
1155 getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State,
1156 const LocationContext *LCtx) {
1157 return create<ObjCMethodCall>(E, State, LCtx);
1158 }
1159
1160 CallEventRef<CXXConstructorCall>
1161 getCXXConstructorCall(const CXXConstructExpr *E, const MemRegion *Target,
1162 ProgramStateRef State, const LocationContext *LCtx) {
1163 return create<CXXConstructorCall>(E, Target, State, LCtx);
1164 }
1165
1166 CallEventRef<CXXDestructorCall>
1167 getCXXDestructorCall(const CXXDestructorDecl *DD, const Stmt *Trigger,
1168 const MemRegion *Target, bool IsBase,
1169 ProgramStateRef State, const LocationContext *LCtx) {
1170 return create<CXXDestructorCall>(DD, Trigger, Target, IsBase, State, LCtx);
1171 }
1172
1173 CallEventRef<CXXAllocatorCall>
1174 getCXXAllocatorCall(const CXXNewExpr *E, ProgramStateRef State,
1175 const LocationContext *LCtx) {
1176 return create<CXXAllocatorCall>(E, State, LCtx);
1177 }
1178};
1179
1180template <typename T>
1181CallEventRef<T> CallEvent::cloneWithState(ProgramStateRef NewState) const {
1182 assert(isa<T>(*this) && "Cloning to unrelated type");
1183 static_assert(sizeof(T) == sizeof(CallEvent),
1184 "Subclasses may not add fields");
1185
1186 if (NewState == State)
1187 return cast<T>(this);
1188
1189 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1190 T *Copy = static_cast<T *>(Mgr.allocate());
1191 cloneTo(Copy);
1192 assert(Copy->getKind() == this->getKind() && "Bad copy");
1193
1194 Copy->State = NewState;
1195 return Copy;
1196}
1197
1198inline void CallEvent::Release() const {
1199 assert(RefCount > 0 && "Reference count is already zero.");
1200 --RefCount;
1201
1202 if (RefCount > 0)
1203 return;
1204
1205 CallEventManager &Mgr = State->getStateManager().getCallEventManager();
1206 Mgr.reclaim(this);
1207
1208 this->~CallEvent();
1209}
1210
1211} // namespace ento
1212
1213} // namespace clang
1214
1215namespace llvm {
1216
1217// Support isa<>, cast<>, and dyn_cast<> for CallEventRef.
1218template<class T> struct simplify_type< clang::ento::CallEventRef<T>> {
1219 using SimpleType = const T *;
1220
1221 static SimpleType
1222 getSimplifiedValue(clang::ento::CallEventRef<T> Val) {
1223 return Val.get();
1224 }
1225};
1226
1227} // namespace llvm
1228
1229#endif // LLVM_CLANG_STATICANALYZER_CORE_PATHSENSITIVE_CALLEVENT_H
1230