14f7df9beSJordan Rose //===- Calls.cpp - Wrapper for all function and method calls ------*- C++ -*--// 24f7df9beSJordan Rose // 34f7df9beSJordan Rose // The LLVM Compiler Infrastructure 44f7df9beSJordan Rose // 54f7df9beSJordan Rose // This file is distributed under the University of Illinois Open Source 64f7df9beSJordan Rose // License. See LICENSE.TXT for details. 74f7df9beSJordan Rose // 84f7df9beSJordan Rose //===----------------------------------------------------------------------===// 94f7df9beSJordan Rose // 104f7df9beSJordan Rose /// \file This file defines CallEvent and its subclasses, which represent path- 114f7df9beSJordan Rose /// sensitive instances of different kinds of function and method calls 124f7df9beSJordan Rose /// (C, C++, and Objective-C). 134f7df9beSJordan Rose // 144f7df9beSJordan Rose //===----------------------------------------------------------------------===// 154f7df9beSJordan Rose 164f7df9beSJordan Rose #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 174f7df9beSJordan Rose #include "clang/AST/ParentMap.h" 183a02247dSChandler Carruth #include "clang/Analysis/ProgramPoint.h" 193a02247dSChandler Carruth #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 204df9d812SGabor Horvath #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h" 214f7df9beSJordan Rose #include "llvm/ADT/SmallSet.h" 224f7df9beSJordan Rose #include "llvm/ADT/StringExtras.h" 23444a1304SBenjamin Kramer #include "llvm/Support/raw_ostream.h" 244f7df9beSJordan Rose 254f7df9beSJordan Rose using namespace clang; 264f7df9beSJordan Rose using namespace ento; 274f7df9beSJordan Rose 284f7df9beSJordan Rose QualType CallEvent::getResultType() const { 292da56438SJordan Rose const Expr *E = getOriginExpr(); 302da56438SJordan Rose assert(E && "Calls without origin expressions do not have results"); 312da56438SJordan Rose QualType ResultTy = E->getType(); 324f7df9beSJordan Rose 332da56438SJordan Rose ASTContext &Ctx = getState()->getStateManager().getContext(); 342da56438SJordan Rose 352da56438SJordan Rose // A function that returns a reference to 'int' will have a result type 362da56438SJordan Rose // of simply 'int'. Check the origin expr's value kind to recover the 372da56438SJordan Rose // proper type. 382da56438SJordan Rose switch (E->getValueKind()) { 392da56438SJordan Rose case VK_LValue: 402da56438SJordan Rose ResultTy = Ctx.getLValueReferenceType(ResultTy); 412da56438SJordan Rose break; 422da56438SJordan Rose case VK_XValue: 432da56438SJordan Rose ResultTy = Ctx.getRValueReferenceType(ResultTy); 442da56438SJordan Rose break; 452da56438SJordan Rose case VK_RValue: 462da56438SJordan Rose // No adjustment is necessary. 472da56438SJordan Rose break; 482da56438SJordan Rose } 494f7df9beSJordan Rose 504f7df9beSJordan Rose return ResultTy; 514f7df9beSJordan Rose } 524f7df9beSJordan Rose 53fe1eca51SAnna Zaks static bool isCallback(QualType T) { 544f7df9beSJordan Rose // If a parameter is a block or a callback, assume it can modify pointer. 554f7df9beSJordan Rose if (T->isBlockPointerType() || 564f7df9beSJordan Rose T->isFunctionPointerType() || 574f7df9beSJordan Rose T->isObjCSelType()) 584f7df9beSJordan Rose return true; 594f7df9beSJordan Rose 604f7df9beSJordan Rose // Check if a callback is passed inside a struct (for both, struct passed by 614f7df9beSJordan Rose // reference and by value). Dig just one level into the struct for now. 624f7df9beSJordan Rose 63d1a08b6eSJordan Rose if (T->isAnyPointerType() || T->isReferenceType()) 644f7df9beSJordan Rose T = T->getPointeeType(); 654f7df9beSJordan Rose 664f7df9beSJordan Rose if (const RecordType *RT = T->getAsStructureType()) { 674f7df9beSJordan Rose const RecordDecl *RD = RT->getDecl(); 68e8a8baefSAaron Ballman for (const auto *I : RD->fields()) { 694f7df9beSJordan Rose QualType FieldT = I->getType(); 704f7df9beSJordan Rose if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType()) 714f7df9beSJordan Rose return true; 724f7df9beSJordan Rose } 734f7df9beSJordan Rose } 744f7df9beSJordan Rose return false; 754f7df9beSJordan Rose } 764f7df9beSJordan Rose 77fe1eca51SAnna Zaks static bool isVoidPointerToNonConst(QualType T) { 78fe1eca51SAnna Zaks if (const PointerType *PT = T->getAs<PointerType>()) { 79fe1eca51SAnna Zaks QualType PointeeTy = PT->getPointeeType(); 80fe1eca51SAnna Zaks if (PointeeTy.isConstQualified()) 81fe1eca51SAnna Zaks return false; 82fe1eca51SAnna Zaks return PointeeTy->isVoidType(); 83fe1eca51SAnna Zaks } else 84fe1eca51SAnna Zaks return false; 85fe1eca51SAnna Zaks } 86fe1eca51SAnna Zaks 87fe1eca51SAnna Zaks bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const { 884f7df9beSJordan Rose unsigned NumOfArgs = getNumArgs(); 894f7df9beSJordan Rose 904f7df9beSJordan Rose // If calling using a function pointer, assume the function does not 91fe1eca51SAnna Zaks // satisfy the callback. 92fe1eca51SAnna Zaks // TODO: We could check the types of the arguments here. 934f7df9beSJordan Rose if (!getDecl()) 944f7df9beSJordan Rose return false; 954f7df9beSJordan Rose 964f7df9beSJordan Rose unsigned Idx = 0; 974f7df9beSJordan Rose for (CallEvent::param_type_iterator I = param_type_begin(), 984f7df9beSJordan Rose E = param_type_end(); 994f7df9beSJordan Rose I != E && Idx < NumOfArgs; ++I, ++Idx) { 1004f7df9beSJordan Rose if (NumOfArgs <= Idx) 1014f7df9beSJordan Rose break; 1024f7df9beSJordan Rose 103fe1eca51SAnna Zaks // If the parameter is 0, it's harmless. 104fe1eca51SAnna Zaks if (getArgSVal(Idx).isZeroConstant()) 105fe1eca51SAnna Zaks continue; 106fe1eca51SAnna Zaks 107fe1eca51SAnna Zaks if (Condition(*I)) 1084f7df9beSJordan Rose return true; 1094f7df9beSJordan Rose } 1104f7df9beSJordan Rose return false; 1114f7df9beSJordan Rose } 1124f7df9beSJordan Rose 113fe1eca51SAnna Zaks bool CallEvent::hasNonZeroCallbackArg() const { 114fe1eca51SAnna Zaks return hasNonNullArgumentsWithType(isCallback); 115fe1eca51SAnna Zaks } 116fe1eca51SAnna Zaks 117fe1eca51SAnna Zaks bool CallEvent::hasVoidPointerToNonConstArg() const { 118fe1eca51SAnna Zaks return hasNonNullArgumentsWithType(isVoidPointerToNonConst); 119fe1eca51SAnna Zaks } 120fe1eca51SAnna Zaks 121829c3831SJordan Rose bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { 122829c3831SJordan Rose const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 123829c3831SJordan Rose if (!FD) 124829c3831SJordan Rose return false; 125829c3831SJordan Rose 126829c3831SJordan Rose return CheckerContext::isCLibraryFunction(FD, FunctionName); 127829c3831SJordan Rose } 128829c3831SJordan Rose 1294f7df9beSJordan Rose /// \brief Returns true if a type is a pointer-to-const or reference-to-const 1304f7df9beSJordan Rose /// with no further indirection. 1314f7df9beSJordan Rose static bool isPointerToConst(QualType Ty) { 1324f7df9beSJordan Rose QualType PointeeTy = Ty->getPointeeType(); 1334f7df9beSJordan Rose if (PointeeTy == QualType()) 1344f7df9beSJordan Rose return false; 1354f7df9beSJordan Rose if (!PointeeTy.isConstQualified()) 1364f7df9beSJordan Rose return false; 1374f7df9beSJordan Rose if (PointeeTy->isAnyPointerType()) 1384f7df9beSJordan Rose return false; 1394f7df9beSJordan Rose return true; 1404f7df9beSJordan Rose } 1414f7df9beSJordan Rose 1424f7df9beSJordan Rose // Try to retrieve the function declaration and find the function parameter 1434f7df9beSJordan Rose // types which are pointers/references to a non-pointer const. 1444f7df9beSJordan Rose // We will not invalidate the corresponding argument regions. 1455413aaa7SJordan Rose static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs, 1464f7df9beSJordan Rose const CallEvent &Call) { 1474f7df9beSJordan Rose unsigned Idx = 0; 1484f7df9beSJordan Rose for (CallEvent::param_type_iterator I = Call.param_type_begin(), 1494f7df9beSJordan Rose E = Call.param_type_end(); 1504f7df9beSJordan Rose I != E; ++I, ++Idx) { 1514f7df9beSJordan Rose if (isPointerToConst(*I)) 1524f7df9beSJordan Rose PreserveArgs.insert(Idx); 1534f7df9beSJordan Rose } 1544f7df9beSJordan Rose } 1554f7df9beSJordan Rose 1564f7df9beSJordan Rose ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount, 1574f7df9beSJordan Rose ProgramStateRef Orig) const { 1584f7df9beSJordan Rose ProgramStateRef Result = (Orig ? Orig : getState()); 1594f7df9beSJordan Rose 1602741654bSJordan Rose // Don't invalidate anything if the callee is marked pure/const. 1612741654bSJordan Rose if (const Decl *callee = getDecl()) 1622741654bSJordan Rose if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>()) 1632741654bSJordan Rose return Result; 1642741654bSJordan Rose 16560bf5f45SAnna Zaks SmallVector<SVal, 8> ValuesToInvalidate; 166424ad95fSAnton Yartsev RegionAndSymbolInvalidationTraits ETraits; 16760bf5f45SAnna Zaks 1684f770deeSDevin Coughlin getExtraInvalidatedValues(ValuesToInvalidate, &ETraits); 1694f7df9beSJordan Rose 1704f7df9beSJordan Rose // Indexes of arguments whose values will be preserved by the call. 1715413aaa7SJordan Rose llvm::SmallSet<unsigned, 4> PreserveArgs; 1724f7df9beSJordan Rose if (!argumentsMayEscape()) 1734f7df9beSJordan Rose findPtrToConstParams(PreserveArgs, *this); 1744f7df9beSJordan Rose 1754f7df9beSJordan Rose for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) { 1764f7df9beSJordan Rose // Mark this region for invalidation. We batch invalidate regions 1774f7df9beSJordan Rose // below for efficiency. 1785413aaa7SJordan Rose if (PreserveArgs.count(Idx)) 179424ad95fSAnton Yartsev if (const MemRegion *MR = getArgSVal(Idx).getAsRegion()) 180424ad95fSAnton Yartsev ETraits.setTrait(MR->StripCasts(), 181424ad95fSAnton Yartsev RegionAndSymbolInvalidationTraits::TK_PreserveContents); 182424ad95fSAnton Yartsev // TODO: Factor this out + handle the lower level const pointers. 183424ad95fSAnton Yartsev 18460bf5f45SAnna Zaks ValuesToInvalidate.push_back(getArgSVal(Idx)); 1854f7df9beSJordan Rose } 1864f7df9beSJordan Rose 1874f7df9beSJordan Rose // Invalidate designated regions using the batch invalidation API. 1884f7df9beSJordan Rose // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 1894f7df9beSJordan Rose // global variables. 19060bf5f45SAnna Zaks return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(), 1914f7df9beSJordan Rose BlockCount, getLocationContext(), 1929747febbSAnna Zaks /*CausedByPointerEscape*/ true, 1930dbb783cSCraig Topper /*Symbols=*/nullptr, this, &ETraits); 1944f7df9beSJordan Rose } 1954f7df9beSJordan Rose 1964f7df9beSJordan Rose ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit, 1974f7df9beSJordan Rose const ProgramPointTag *Tag) const { 1984f7df9beSJordan Rose if (const Expr *E = getOriginExpr()) { 1994f7df9beSJordan Rose if (IsPreVisit) 2004f7df9beSJordan Rose return PreStmt(E, getLocationContext(), Tag); 2014f7df9beSJordan Rose return PostStmt(E, getLocationContext(), Tag); 2024f7df9beSJordan Rose } 2034f7df9beSJordan Rose 2044f7df9beSJordan Rose const Decl *D = getDecl(); 2054f7df9beSJordan Rose assert(D && "Cannot get a program point without a statement or decl"); 2064f7df9beSJordan Rose 2074f7df9beSJordan Rose SourceLocation Loc = getSourceRange().getBegin(); 2084f7df9beSJordan Rose if (IsPreVisit) 2094f7df9beSJordan Rose return PreImplicitCall(D, Loc, getLocationContext(), Tag); 2104f7df9beSJordan Rose return PostImplicitCall(D, Loc, getLocationContext(), Tag); 2114f7df9beSJordan Rose } 2124f7df9beSJordan Rose 213*343730c5SGabor Horvath bool CallEvent::isCalled(const CallDescription &CD) const { 214*343730c5SGabor Horvath assert(getKind() != CE_ObjCMessage && "Obj-C methods are not supported"); 215*343730c5SGabor Horvath if (!CD.II) 216*343730c5SGabor Horvath CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName); 217*343730c5SGabor Horvath if (getCalleeIdentifier() != CD.II) 218*343730c5SGabor Horvath return false; 219*343730c5SGabor Horvath return (CD.RequiredArgs == CallDescription::NoArgRequirement || 220*343730c5SGabor Horvath CD.RequiredArgs == getNumArgs()); 221*343730c5SGabor Horvath } 222*343730c5SGabor Horvath 22372ce8e2dSJordan Rose SVal CallEvent::getArgSVal(unsigned Index) const { 22472ce8e2dSJordan Rose const Expr *ArgE = getArgExpr(Index); 22572ce8e2dSJordan Rose if (!ArgE) 22672ce8e2dSJordan Rose return UnknownVal(); 22772ce8e2dSJordan Rose return getSVal(ArgE); 22872ce8e2dSJordan Rose } 22972ce8e2dSJordan Rose 23072ce8e2dSJordan Rose SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 23172ce8e2dSJordan Rose const Expr *ArgE = getArgExpr(Index); 23272ce8e2dSJordan Rose if (!ArgE) 23372ce8e2dSJordan Rose return SourceRange(); 23472ce8e2dSJordan Rose return ArgE->getSourceRange(); 23572ce8e2dSJordan Rose } 23672ce8e2dSJordan Rose 237829c3831SJordan Rose SVal CallEvent::getReturnValue() const { 238829c3831SJordan Rose const Expr *E = getOriginExpr(); 239829c3831SJordan Rose if (!E) 240829c3831SJordan Rose return UndefinedVal(); 241829c3831SJordan Rose return getSVal(E); 242829c3831SJordan Rose } 243829c3831SJordan Rose 244ef6b007dSAlp Toker LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); } 2459299d8c2SBenjamin Kramer 24672ce8e2dSJordan Rose void CallEvent::dump(raw_ostream &Out) const { 24772ce8e2dSJordan Rose ASTContext &Ctx = getState()->getStateManager().getContext(); 24872ce8e2dSJordan Rose if (const Expr *E = getOriginExpr()) { 2490dbb783cSCraig Topper E->printPretty(Out, nullptr, Ctx.getPrintingPolicy()); 25072ce8e2dSJordan Rose Out << "\n"; 25172ce8e2dSJordan Rose return; 25272ce8e2dSJordan Rose } 25372ce8e2dSJordan Rose 25472ce8e2dSJordan Rose if (const Decl *D = getDecl()) { 25572ce8e2dSJordan Rose Out << "Call to "; 25672ce8e2dSJordan Rose D->print(Out, Ctx.getPrintingPolicy()); 25772ce8e2dSJordan Rose return; 25872ce8e2dSJordan Rose } 25972ce8e2dSJordan Rose 26072ce8e2dSJordan Rose // FIXME: a string representation of the kind would be nice. 26172ce8e2dSJordan Rose Out << "Unknown call (type " << getKind() << ")"; 26272ce8e2dSJordan Rose } 26372ce8e2dSJordan Rose 2644f7df9beSJordan Rose 265e537cc05SJordan Rose bool CallEvent::isCallStmt(const Stmt *S) { 26672ce8e2dSJordan Rose return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S) 267e537cc05SJordan Rose || isa<CXXConstructExpr>(S) 268e537cc05SJordan Rose || isa<CXXNewExpr>(S); 2694f7df9beSJordan Rose } 2704f7df9beSJordan Rose 2715d2964e7SAnna Zaks QualType CallEvent::getDeclaredResultType(const Decl *D) { 2725d2964e7SAnna Zaks assert(D); 2735d2964e7SAnna Zaks if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) 274314cc81bSAlp Toker return FD->getReturnType(); 275add14263SJordan Rose if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D)) 276314cc81bSAlp Toker return MD->getReturnType(); 277add14263SJordan Rose if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 278add14263SJordan Rose // Blocks are difficult because the return type may not be stored in the 279add14263SJordan Rose // BlockDecl itself. The AST should probably be enhanced, but for now we 280add14263SJordan Rose // just do what we can. 281278d9de3SJordan Rose // If the block is declared without an explicit argument list, the 282278d9de3SJordan Rose // signature-as-written just includes the return type, not the entire 283278d9de3SJordan Rose // function type. 2841bfe9c78SJordan Rose // FIXME: All blocks should have signatures-as-written, even if the return 285278d9de3SJordan Rose // type is inferred. (That's signified with a dependent result type.) 2861bfe9c78SJordan Rose if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) { 287278d9de3SJordan Rose QualType Ty = TSI->getType(); 288278d9de3SJordan Rose if (const FunctionType *FT = Ty->getAs<FunctionType>()) 289314cc81bSAlp Toker Ty = FT->getReturnType(); 290278d9de3SJordan Rose if (!Ty->isDependentType()) 291278d9de3SJordan Rose return Ty; 2921bfe9c78SJordan Rose } 293add14263SJordan Rose 294add14263SJordan Rose return QualType(); 295add14263SJordan Rose } 296add14263SJordan Rose 2973553bb38SJordan Rose llvm_unreachable("unknown callable kind"); 2983553bb38SJordan Rose } 2993553bb38SJordan Rose 3003553bb38SJordan Rose bool CallEvent::isVariadic(const Decl *D) { 3013553bb38SJordan Rose assert(D); 3023553bb38SJordan Rose 3033553bb38SJordan Rose if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 3043553bb38SJordan Rose return FD->isVariadic(); 3053553bb38SJordan Rose if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 3063553bb38SJordan Rose return MD->isVariadic(); 3073553bb38SJordan Rose if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 3083553bb38SJordan Rose return BD->isVariadic(); 3093553bb38SJordan Rose 3103553bb38SJordan Rose llvm_unreachable("unknown callable kind"); 3115d2964e7SAnna Zaks } 3125d2964e7SAnna Zaks 31342e8d649SJordan Rose static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 31442e8d649SJordan Rose CallEvent::BindingsTy &Bindings, 31542e8d649SJordan Rose SValBuilder &SVB, 31642e8d649SJordan Rose const CallEvent &Call, 3172ff16004STed Kremenek ArrayRef<ParmVarDecl*> parameters) { 31842e8d649SJordan Rose MemRegionManager &MRMgr = SVB.getRegionManager(); 3194f7df9beSJordan Rose 320963f91b3SPavel Labath // If the function has fewer parameters than the call has arguments, we simply 321963f91b3SPavel Labath // do not bind any values to them. 322963f91b3SPavel Labath unsigned NumArgs = Call.getNumArgs(); 32342e8d649SJordan Rose unsigned Idx = 0; 3242ff16004STed Kremenek ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end(); 325963f91b3SPavel Labath for (; I != E && Idx < NumArgs; ++I, ++Idx) { 32642e8d649SJordan Rose const ParmVarDecl *ParamDecl = *I; 32742e8d649SJordan Rose assert(ParamDecl && "Formal parameter has no decl?"); 3284f7df9beSJordan Rose 32942e8d649SJordan Rose SVal ArgVal = Call.getArgSVal(Idx); 33042e8d649SJordan Rose if (!ArgVal.isUnknown()) { 33142e8d649SJordan Rose Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx)); 33242e8d649SJordan Rose Bindings.push_back(std::make_pair(ParamLoc, ArgVal)); 33342e8d649SJordan Rose } 3344f7df9beSJordan Rose } 3354f7df9beSJordan Rose 33642e8d649SJordan Rose // FIXME: Variadic arguments are not handled at all right now. 33742e8d649SJordan Rose } 33842e8d649SJordan Rose 3392ff16004STed Kremenek ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const { 34042e8d649SJordan Rose const FunctionDecl *D = getDecl(); 3414f7df9beSJordan Rose if (!D) 34200bbdcf9SCraig Topper return None; 3432ff16004STed Kremenek return D->parameters(); 34442e8d649SJordan Rose } 34542e8d649SJordan Rose 34642e8d649SJordan Rose void AnyFunctionCall::getInitialStackFrameContents( 34742e8d649SJordan Rose const StackFrameContext *CalleeCtx, 34842e8d649SJordan Rose BindingsTy &Bindings) const { 34942e8d649SJordan Rose const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 35042e8d649SJordan Rose SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 35142e8d649SJordan Rose addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 3522ff16004STed Kremenek D->parameters()); 3534f7df9beSJordan Rose } 3544f7df9beSJordan Rose 3554f7df9beSJordan Rose bool AnyFunctionCall::argumentsMayEscape() const { 356fe1eca51SAnna Zaks if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg()) 3574f7df9beSJordan Rose return true; 3584f7df9beSJordan Rose 3594f7df9beSJordan Rose const FunctionDecl *D = getDecl(); 3604f7df9beSJordan Rose if (!D) 3614f7df9beSJordan Rose return true; 3624f7df9beSJordan Rose 3634f7df9beSJordan Rose const IdentifierInfo *II = D->getIdentifier(); 3644f7df9beSJordan Rose if (!II) 3657bd0674dSAnna Zaks return false; 3664f7df9beSJordan Rose 3674f7df9beSJordan Rose // This set of "escaping" APIs is 3684f7df9beSJordan Rose 3694f7df9beSJordan Rose // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 3704f7df9beSJordan Rose // value into thread local storage. The value can later be retrieved with 3714f7df9beSJordan Rose // 'void *ptheread_getspecific(pthread_key)'. So even thought the 3724f7df9beSJordan Rose // parameter is 'const void *', the region escapes through the call. 3734f7df9beSJordan Rose if (II->isStr("pthread_setspecific")) 3744f7df9beSJordan Rose return true; 3754f7df9beSJordan Rose 3764f7df9beSJordan Rose // - xpc_connection_set_context stores a value which can be retrieved later 3774f7df9beSJordan Rose // with xpc_connection_get_context. 3784f7df9beSJordan Rose if (II->isStr("xpc_connection_set_context")) 3794f7df9beSJordan Rose return true; 3804f7df9beSJordan Rose 3814f7df9beSJordan Rose // - funopen - sets a buffer for future IO calls. 3824f7df9beSJordan Rose if (II->isStr("funopen")) 3834f7df9beSJordan Rose return true; 3844f7df9beSJordan Rose 3854f7df9beSJordan Rose StringRef FName = II->getName(); 3864f7df9beSJordan Rose 3874f7df9beSJordan Rose // - CoreFoundation functions that end with "NoCopy" can free a passed-in 3884f7df9beSJordan Rose // buffer even if it is const. 3894f7df9beSJordan Rose if (FName.endswith("NoCopy")) 3904f7df9beSJordan Rose return true; 3914f7df9beSJordan Rose 3924f7df9beSJordan Rose // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 3934f7df9beSJordan Rose // be deallocated by NSMapRemove. 3944f7df9beSJordan Rose if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 3954f7df9beSJordan Rose return true; 3964f7df9beSJordan Rose 3974f7df9beSJordan Rose // - Many CF containers allow objects to escape through custom 3984f7df9beSJordan Rose // allocators/deallocators upon container construction. (PR12101) 3994f7df9beSJordan Rose if (FName.startswith("CF") || FName.startswith("CG")) { 4004f7df9beSJordan Rose return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 4014f7df9beSJordan Rose StrInStrNoCase(FName, "AddValue") != StringRef::npos || 4024f7df9beSJordan Rose StrInStrNoCase(FName, "SetValue") != StringRef::npos || 4034f7df9beSJordan Rose StrInStrNoCase(FName, "WithData") != StringRef::npos || 4044f7df9beSJordan Rose StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 4054f7df9beSJordan Rose StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 4064f7df9beSJordan Rose } 4074f7df9beSJordan Rose 4084f7df9beSJordan Rose return false; 4094f7df9beSJordan Rose } 4104f7df9beSJordan Rose 4114f7df9beSJordan Rose 4122a833ca5SJordan Rose const FunctionDecl *SimpleFunctionCall::getDecl() const { 4134f7df9beSJordan Rose const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 4144f7df9beSJordan Rose if (D) 4154f7df9beSJordan Rose return D; 4164f7df9beSJordan Rose 4174f7df9beSJordan Rose return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 4184f7df9beSJordan Rose } 4194f7df9beSJordan Rose 4204f7df9beSJordan Rose 421ce6c99a5SJordan Rose const FunctionDecl *CXXInstanceCall::getDecl() const { 422ce6c99a5SJordan Rose const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr()); 423ce6c99a5SJordan Rose if (!CE) 424ce6c99a5SJordan Rose return AnyFunctionCall::getDecl(); 425ce6c99a5SJordan Rose 426ce6c99a5SJordan Rose const FunctionDecl *D = CE->getDirectCallee(); 427ce6c99a5SJordan Rose if (D) 428ce6c99a5SJordan Rose return D; 429ce6c99a5SJordan Rose 430ce6c99a5SJordan Rose return getSVal(CE->getCallee()).getAsFunctionDecl(); 431ce6c99a5SJordan Rose } 432ce6c99a5SJordan Rose 43300e780e1SSean Eveson void CXXInstanceCall::getExtraInvalidatedValues( 43400e780e1SSean Eveson ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 4354f770deeSDevin Coughlin SVal ThisVal = getCXXThisVal(); 4364f770deeSDevin Coughlin Values.push_back(ThisVal); 4374f770deeSDevin Coughlin 4383f072ef8SSean Eveson // Don't invalidate if the method is const and there are no mutable fields. 4394f770deeSDevin Coughlin if (const CXXMethodDecl *D = cast_or_null<CXXMethodDecl>(getDecl())) { 4404f770deeSDevin Coughlin if (!D->isConst()) 4414f770deeSDevin Coughlin return; 4424f770deeSDevin Coughlin // Get the record decl for the class of 'This'. D->getParent() may return a 4434f770deeSDevin Coughlin // base class decl, rather than the class of the instance which needs to be 4444f770deeSDevin Coughlin // checked for mutable fields. 4454f770deeSDevin Coughlin const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts(); 4464f770deeSDevin Coughlin const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl(); 4474f770deeSDevin Coughlin if (!ParentRecord || ParentRecord->hasMutableFields()) 4484f770deeSDevin Coughlin return; 4494f770deeSDevin Coughlin // Preserve CXXThis. 4504f770deeSDevin Coughlin const MemRegion *ThisRegion = ThisVal.getAsRegion(); 4519c76869bSDevin Coughlin if (!ThisRegion) 4529c76869bSDevin Coughlin return; 4539c76869bSDevin Coughlin 4544f770deeSDevin Coughlin ETraits->setTrait(ThisRegion->getBaseRegion(), 4554f770deeSDevin Coughlin RegionAndSymbolInvalidationTraits::TK_PreserveContents); 4564f770deeSDevin Coughlin } 4574f7df9beSJordan Rose } 4584f7df9beSJordan Rose 459fcdda361SJordan Rose SVal CXXInstanceCall::getCXXThisVal() const { 460fcdda361SJordan Rose const Expr *Base = getCXXThisExpr(); 461fcdda361SJordan Rose // FIXME: This doesn't handle an overloaded ->* operator. 462fcdda361SJordan Rose if (!Base) 463fcdda361SJordan Rose return UnknownVal(); 464fcdda361SJordan Rose 465fcdda361SJordan Rose SVal ThisVal = getSVal(Base); 4662fdacbc5SDavid Blaikie assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 467fcdda361SJordan Rose return ThisVal; 468fcdda361SJordan Rose } 469fcdda361SJordan Rose 4704f7df9beSJordan Rose 471089c5510STed Kremenek RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 4720f6d63beSJordan Rose // Do we have a decl at all? 47351bcb226SJordan Rose const Decl *D = getDecl(); 4744f7df9beSJordan Rose if (!D) 475123af098SAnna Zaks return RuntimeDefinition(); 4764f7df9beSJordan Rose 4770f6d63beSJordan Rose // If the method is non-virtual, we know we can inline it. 4784f7df9beSJordan Rose const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 4794f7df9beSJordan Rose if (!MD->isVirtual()) 480089c5510STed Kremenek return AnyFunctionCall::getRuntimeDefinition(); 4814f7df9beSJordan Rose 4820f6d63beSJordan Rose // Do we know the implicit 'this' object being called? 4830f6d63beSJordan Rose const MemRegion *R = getCXXThisVal().getAsRegion(); 4840f6d63beSJordan Rose if (!R) 485123af098SAnna Zaks return RuntimeDefinition(); 4860f6d63beSJordan Rose 4870f6d63beSJordan Rose // Do we know anything about the type of 'this'? 4884df9d812SGabor Horvath DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R); 4890f6d63beSJordan Rose if (!DynType.isValid()) 4900f6d63beSJordan Rose return RuntimeDefinition(); 4910f6d63beSJordan Rose 4920f6d63beSJordan Rose // Is the type a C++ class? (This is mostly a defensive check.) 4930f6d63beSJordan Rose QualType RegionType = DynType.getType()->getPointeeType(); 494d1a08b6eSJordan Rose assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 495d1a08b6eSJordan Rose 4960f6d63beSJordan Rose const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 49799107208SJordan Rose if (!RD || !RD->hasDefinition()) 4980f6d63beSJordan Rose return RuntimeDefinition(); 4990f6d63beSJordan Rose 50099c6c2b4SJordan Rose // Find the decl for this method in that class. 50199c6c2b4SJordan Rose const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 50281456d9fSJordan Rose if (!Result) { 50381456d9fSJordan Rose // We might not even get the original statically-resolved method due to 50481456d9fSJordan Rose // some particularly nasty casting (e.g. casts to sister classes). 50581456d9fSJordan Rose // However, we should at least be able to search up and down our own class 50681456d9fSJordan Rose // hierarchy, and some real bugs have been caught by checking this. 50781456d9fSJordan Rose assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 508d44977efSJordan Rose 509d44977efSJordan Rose // FIXME: This is checking that our DynamicTypeInfo is at least as good as 510d44977efSJordan Rose // the static type. However, because we currently don't update 511d44977efSJordan Rose // DynamicTypeInfo when an object is cast, we can't actually be sure the 512d44977efSJordan Rose // DynamicTypeInfo is up to date. This assert should be re-enabled once 513d44977efSJordan Rose // this is fixed. <rdar://problem/12287087> 514d44977efSJordan Rose //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 515d44977efSJordan Rose 51681456d9fSJordan Rose return RuntimeDefinition(); 51781456d9fSJordan Rose } 5180f6d63beSJordan Rose 5190f6d63beSJordan Rose // Does the decl that we found have an implementation? 5200f6d63beSJordan Rose const FunctionDecl *Definition; 5210f6d63beSJordan Rose if (!Result->hasBody(Definition)) 5220f6d63beSJordan Rose return RuntimeDefinition(); 5230f6d63beSJordan Rose 5240f6d63beSJordan Rose // We found a definition. If we're not sure that this devirtualization is 5250f6d63beSJordan Rose // actually what will happen at runtime, make sure to provide the region so 5260f6d63beSJordan Rose // that ExprEngine can decide what to do with it. 5270f6d63beSJordan Rose if (DynType.canBeASubClass()) 5280f6d63beSJordan Rose return RuntimeDefinition(Definition, R->StripCasts()); 5290dbb783cSCraig Topper return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr); 5304f7df9beSJordan Rose } 5314f7df9beSJordan Rose 53242e8d649SJordan Rose void CXXInstanceCall::getInitialStackFrameContents( 53342e8d649SJordan Rose const StackFrameContext *CalleeCtx, 53442e8d649SJordan Rose BindingsTy &Bindings) const { 53542e8d649SJordan Rose AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 53642e8d649SJordan Rose 53702e5309bSJordan Rose // Handle the binding of 'this' in the new stack frame. 53842e8d649SJordan Rose SVal ThisVal = getCXXThisVal(); 53942e8d649SJordan Rose if (!ThisVal.isUnknown()) { 54002e5309bSJordan Rose ProgramStateManager &StateMgr = getState()->getStateManager(); 54102e5309bSJordan Rose SValBuilder &SVB = StateMgr.getSValBuilder(); 54202e5309bSJordan Rose 54342e8d649SJordan Rose const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 54442e8d649SJordan Rose Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 54502e5309bSJordan Rose 54631c3fa9cSJordan Rose // If we devirtualized to a different member function, we need to make sure 54731c3fa9cSJordan Rose // we have the proper layering of CXXBaseObjectRegions. 54831c3fa9cSJordan Rose if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 549710f6b12SJordan Rose ASTContext &Ctx = SVB.getContext(); 55002e5309bSJordan Rose const CXXRecordDecl *Class = MD->getParent(); 551710f6b12SJordan Rose QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 55202e5309bSJordan Rose 553710f6b12SJordan Rose // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 554710f6b12SJordan Rose bool Failed; 555710f6b12SJordan Rose ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed); 556710f6b12SJordan Rose assert(!Failed && "Calling an incorrectly devirtualized method"); 55702e5309bSJordan Rose } 55802e5309bSJordan Rose 55931c3fa9cSJordan Rose if (!ThisVal.isUnknown()) 56042e8d649SJordan Rose Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 56142e8d649SJordan Rose } 56242e8d649SJordan Rose } 56342e8d649SJordan Rose 56442e8d649SJordan Rose 5654f7df9beSJordan Rose 56692e1449bSJordan Rose const Expr *CXXMemberCall::getCXXThisExpr() const { 56792e1449bSJordan Rose return getOriginExpr()->getImplicitObjectArgument(); 5684f7df9beSJordan Rose } 5694f7df9beSJordan Rose 570089c5510STed Kremenek RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 57112f669e3SJordan Rose // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 57212f669e3SJordan Rose // id-expression in the class member access expression is a qualified-id, 57312f669e3SJordan Rose // that function is called. Otherwise, its final overrider in the dynamic type 57412f669e3SJordan Rose // of the object expression is called. 57512f669e3SJordan Rose if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 57612f669e3SJordan Rose if (ME->hasQualifier()) 577089c5510STed Kremenek return AnyFunctionCall::getRuntimeDefinition(); 57812f669e3SJordan Rose 579089c5510STed Kremenek return CXXInstanceCall::getRuntimeDefinition(); 58012f669e3SJordan Rose } 58112f669e3SJordan Rose 5824f7df9beSJordan Rose 58392e1449bSJordan Rose const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 58492e1449bSJordan Rose return getOriginExpr()->getArg(0); 5854f7df9beSJordan Rose } 5864f7df9beSJordan Rose 5874f7df9beSJordan Rose 5884f7df9beSJordan Rose const BlockDataRegion *BlockCall::getBlockRegion() const { 5894f7df9beSJordan Rose const Expr *Callee = getOriginExpr()->getCallee(); 5904f7df9beSJordan Rose const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 5914f7df9beSJordan Rose 5924f7df9beSJordan Rose return dyn_cast_or_null<BlockDataRegion>(DataReg); 5934f7df9beSJordan Rose } 5944f7df9beSJordan Rose 5952ff16004STed Kremenek ArrayRef<ParmVarDecl*> BlockCall::parameters() const { 5962a833ca5SJordan Rose const BlockDecl *D = getDecl(); 5974f7df9beSJordan Rose if (!D) 5980dbb783cSCraig Topper return nullptr; 5992ff16004STed Kremenek return D->parameters(); 6004f7df9beSJordan Rose } 6014f7df9beSJordan Rose 6024f770deeSDevin Coughlin void BlockCall::getExtraInvalidatedValues(ValueList &Values, 6034f770deeSDevin Coughlin RegionAndSymbolInvalidationTraits *ETraits) const { 6044f7df9beSJordan Rose // FIXME: This also needs to invalidate captured globals. 6054f7df9beSJordan Rose if (const MemRegion *R = getBlockRegion()) 60660bf5f45SAnna Zaks Values.push_back(loc::MemRegionVal(R)); 6074f7df9beSJordan Rose } 6084f7df9beSJordan Rose 60942e8d649SJordan Rose void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 61042e8d649SJordan Rose BindingsTy &Bindings) const { 61142e8d649SJordan Rose SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 612ebeed880SDevin Coughlin ArrayRef<ParmVarDecl*> Params; 613ebeed880SDevin Coughlin if (isConversionFromLambda()) { 614ebeed880SDevin Coughlin auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 615ebeed880SDevin Coughlin Params = LambdaOperatorDecl->parameters(); 616ebeed880SDevin Coughlin 617ebeed880SDevin Coughlin // For blocks converted from a C++ lambda, the callee declaration is the 6185690454bSSanjay Patel // operator() method on the lambda so we bind "this" to 619ebeed880SDevin Coughlin // the lambda captured by the block. 620ebeed880SDevin Coughlin const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda(); 621ebeed880SDevin Coughlin SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion); 622ebeed880SDevin Coughlin Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx); 623ebeed880SDevin Coughlin Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 624ebeed880SDevin Coughlin } else { 625ebeed880SDevin Coughlin Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters(); 626ebeed880SDevin Coughlin } 627ebeed880SDevin Coughlin 62842e8d649SJordan Rose addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 629ebeed880SDevin Coughlin Params); 63042e8d649SJordan Rose } 63142e8d649SJordan Rose 63242e8d649SJordan Rose 6334f7df9beSJordan Rose SVal CXXConstructorCall::getCXXThisVal() const { 6344f7df9beSJordan Rose if (Data) 6354f7df9beSJordan Rose return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 6364f7df9beSJordan Rose return UnknownVal(); 6374f7df9beSJordan Rose } 6384f7df9beSJordan Rose 6394f770deeSDevin Coughlin void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values, 6404f770deeSDevin Coughlin RegionAndSymbolInvalidationTraits *ETraits) const { 6414f7df9beSJordan Rose if (Data) 64260bf5f45SAnna Zaks Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data))); 6434f7df9beSJordan Rose } 6444f7df9beSJordan Rose 64542e8d649SJordan Rose void CXXConstructorCall::getInitialStackFrameContents( 64642e8d649SJordan Rose const StackFrameContext *CalleeCtx, 64742e8d649SJordan Rose BindingsTy &Bindings) const { 64842e8d649SJordan Rose AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 64942e8d649SJordan Rose 65042e8d649SJordan Rose SVal ThisVal = getCXXThisVal(); 65142e8d649SJordan Rose if (!ThisVal.isUnknown()) { 65242e8d649SJordan Rose SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 65342e8d649SJordan Rose const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 65442e8d649SJordan Rose Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 65542e8d649SJordan Rose Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 65642e8d649SJordan Rose } 65742e8d649SJordan Rose } 65842e8d649SJordan Rose 6594f7df9beSJordan Rose SVal CXXDestructorCall::getCXXThisVal() const { 6604f7df9beSJordan Rose if (Data) 6612bc9674bSJordan Rose return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 6624f7df9beSJordan Rose return UnknownVal(); 6634f7df9beSJordan Rose } 6644f7df9beSJordan Rose 665089c5510STed Kremenek RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 6662bc9674bSJordan Rose // Base destructors are always called non-virtually. 6672bc9674bSJordan Rose // Skip CXXInstanceCall's devirtualization logic in this case. 6682bc9674bSJordan Rose if (isBaseDestructor()) 669089c5510STed Kremenek return AnyFunctionCall::getRuntimeDefinition(); 6702bc9674bSJordan Rose 671089c5510STed Kremenek return CXXInstanceCall::getRuntimeDefinition(); 6722bc9674bSJordan Rose } 6732bc9674bSJordan Rose 6742ff16004STed Kremenek ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const { 67542e8d649SJordan Rose const ObjCMethodDecl *D = getDecl(); 6764f7df9beSJordan Rose if (!D) 6775fc8fc2dSCraig Topper return None; 6782ff16004STed Kremenek return D->parameters(); 6794f7df9beSJordan Rose } 6804f7df9beSJordan Rose 6814f7df9beSJordan Rose void 6824f770deeSDevin Coughlin ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values, 6834f770deeSDevin Coughlin RegionAndSymbolInvalidationTraits *ETraits) const { 68460bf5f45SAnna Zaks Values.push_back(getReceiverSVal()); 6854f7df9beSJordan Rose } 6864f7df9beSJordan Rose 6873d5d3d3eSAnna Zaks SVal ObjCMethodCall::getSelfSVal() const { 6883d5d3d3eSAnna Zaks const LocationContext *LCtx = getLocationContext(); 6893d5d3d3eSAnna Zaks const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 6903d5d3d3eSAnna Zaks if (!SelfDecl) 6913d5d3d3eSAnna Zaks return SVal(); 6923d5d3d3eSAnna Zaks return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 6933d5d3d3eSAnna Zaks } 6943d5d3d3eSAnna Zaks 6954f7df9beSJordan Rose SVal ObjCMethodCall::getReceiverSVal() const { 6964f7df9beSJordan Rose // FIXME: Is this the best way to handle class receivers? 6974f7df9beSJordan Rose if (!isInstanceMessage()) 6984f7df9beSJordan Rose return UnknownVal(); 6994f7df9beSJordan Rose 700472dbcf1SAnna Zaks if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 701472dbcf1SAnna Zaks return getSVal(RecE); 7024f7df9beSJordan Rose 7034f7df9beSJordan Rose // An instance message with no expression means we are sending to super. 7044f7df9beSJordan Rose // In this case the object reference is the same as 'self'. 7053d5d3d3eSAnna Zaks assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 7063d5d3d3eSAnna Zaks SVal SelfVal = getSelfSVal(); 7073d5d3d3eSAnna Zaks assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 7083d5d3d3eSAnna Zaks return SelfVal; 7093d5d3d3eSAnna Zaks } 7103d5d3d3eSAnna Zaks 7113d5d3d3eSAnna Zaks bool ObjCMethodCall::isReceiverSelfOrSuper() const { 7123d5d3d3eSAnna Zaks if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 7133d5d3d3eSAnna Zaks getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 7143d5d3d3eSAnna Zaks return true; 7153d5d3d3eSAnna Zaks 7163d5d3d3eSAnna Zaks if (!isInstanceMessage()) 7173d5d3d3eSAnna Zaks return false; 7183d5d3d3eSAnna Zaks 7193d5d3d3eSAnna Zaks SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 7203d5d3d3eSAnna Zaks 7213d5d3d3eSAnna Zaks return (RecVal == getSelfSVal()); 7224f7df9beSJordan Rose } 7234f7df9beSJordan Rose 7244f7df9beSJordan Rose SourceRange ObjCMethodCall::getSourceRange() const { 7254f7df9beSJordan Rose switch (getMessageKind()) { 7264f7df9beSJordan Rose case OCM_Message: 7274f7df9beSJordan Rose return getOriginExpr()->getSourceRange(); 7284f7df9beSJordan Rose case OCM_PropertyAccess: 7294f7df9beSJordan Rose case OCM_Subscript: 7304f7df9beSJordan Rose return getContainingPseudoObjectExpr()->getSourceRange(); 7314f7df9beSJordan Rose } 7324f7df9beSJordan Rose llvm_unreachable("unknown message kind"); 7334f7df9beSJordan Rose } 7344f7df9beSJordan Rose 7354f7df9beSJordan Rose typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy; 7364f7df9beSJordan Rose 7374f7df9beSJordan Rose const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 7380dbb783cSCraig Topper assert(Data && "Lazy lookup not yet performed."); 7394f7df9beSJordan Rose assert(getMessageKind() != OCM_Message && "Explicit message send."); 7404f7df9beSJordan Rose return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 7414f7df9beSJordan Rose } 7424f7df9beSJordan Rose 7434f7df9beSJordan Rose ObjCMessageKind ObjCMethodCall::getMessageKind() const { 7440dbb783cSCraig Topper if (!Data) { 745226a56faSAnna Zaks 746226a56faSAnna Zaks // Find the parent, ignoring implicit casts. 7474f7df9beSJordan Rose ParentMap &PM = getLocationContext()->getParentMap(); 7485770c038SJordan Rose const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr()); 749226a56faSAnna Zaks 750226a56faSAnna Zaks // Check if parent is a PseudoObjectExpr. 7514f7df9beSJordan Rose if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 7524f7df9beSJordan Rose const Expr *Syntactic = POE->getSyntacticForm(); 7534f7df9beSJordan Rose 7544f7df9beSJordan Rose // This handles the funny case of assigning to the result of a getter. 7554f7df9beSJordan Rose // This can happen if the getter returns a non-const reference. 7564f7df9beSJordan Rose if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic)) 7574f7df9beSJordan Rose Syntactic = BO->getLHS(); 7584f7df9beSJordan Rose 7594f7df9beSJordan Rose ObjCMessageKind K; 7604f7df9beSJordan Rose switch (Syntactic->getStmtClass()) { 7614f7df9beSJordan Rose case Stmt::ObjCPropertyRefExprClass: 7624f7df9beSJordan Rose K = OCM_PropertyAccess; 7634f7df9beSJordan Rose break; 7644f7df9beSJordan Rose case Stmt::ObjCSubscriptRefExprClass: 7654f7df9beSJordan Rose K = OCM_Subscript; 7664f7df9beSJordan Rose break; 7674f7df9beSJordan Rose default: 7684f7df9beSJordan Rose // FIXME: Can this ever happen? 7694f7df9beSJordan Rose K = OCM_Message; 7704f7df9beSJordan Rose break; 7714f7df9beSJordan Rose } 7724f7df9beSJordan Rose 7734f7df9beSJordan Rose if (K != OCM_Message) { 7744f7df9beSJordan Rose const_cast<ObjCMethodCall *>(this)->Data 7754f7df9beSJordan Rose = ObjCMessageDataTy(POE, K).getOpaqueValue(); 7764f7df9beSJordan Rose assert(getMessageKind() == K); 7774f7df9beSJordan Rose return K; 7784f7df9beSJordan Rose } 7794f7df9beSJordan Rose } 7804f7df9beSJordan Rose 7814f7df9beSJordan Rose const_cast<ObjCMethodCall *>(this)->Data 7820dbb783cSCraig Topper = ObjCMessageDataTy(nullptr, 1).getOpaqueValue(); 7834f7df9beSJordan Rose assert(getMessageKind() == OCM_Message); 7844f7df9beSJordan Rose return OCM_Message; 7854f7df9beSJordan Rose } 7864f7df9beSJordan Rose 7874f7df9beSJordan Rose ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 7884f7df9beSJordan Rose if (!Info.getPointer()) 7894f7df9beSJordan Rose return OCM_Message; 7904f7df9beSJordan Rose return static_cast<ObjCMessageKind>(Info.getInt()); 7914f7df9beSJordan Rose } 7924f7df9beSJordan Rose 793920af014SAnna Zaks 794920af014SAnna Zaks bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 795920af014SAnna Zaks Selector Sel) const { 796920af014SAnna Zaks assert(IDecl); 797920af014SAnna Zaks const SourceManager &SM = 798920af014SAnna Zaks getState()->getStateManager().getContext().getSourceManager(); 799920af014SAnna Zaks 800920af014SAnna Zaks // If the class interface is declared inside the main file, assume it is not 801920af014SAnna Zaks // subcassed. 802920af014SAnna Zaks // TODO: It could actually be subclassed if the subclass is private as well. 803920af014SAnna Zaks // This is probably very rare. 804920af014SAnna Zaks SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 8055ba37d52SEli Friedman if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc)) 806920af014SAnna Zaks return false; 807920af014SAnna Zaks 8086ddb6b1aSAnna Zaks // Assume that property accessors are not overridden. 8096ddb6b1aSAnna Zaks if (getMessageKind() == OCM_PropertyAccess) 8106ddb6b1aSAnna Zaks return false; 811920af014SAnna Zaks 812920af014SAnna Zaks // We assume that if the method is public (declared outside of main file) or 813920af014SAnna Zaks // has a parent which publicly declares the method, the method could be 814920af014SAnna Zaks // overridden in a subclass. 815920af014SAnna Zaks 816920af014SAnna Zaks // Find the first declaration in the class hierarchy that declares 817920af014SAnna Zaks // the selector. 8180dbb783cSCraig Topper ObjCMethodDecl *D = nullptr; 819920af014SAnna Zaks while (true) { 820920af014SAnna Zaks D = IDecl->lookupMethod(Sel, true); 821920af014SAnna Zaks 822920af014SAnna Zaks // Cannot find a public definition. 823920af014SAnna Zaks if (!D) 824920af014SAnna Zaks return false; 825920af014SAnna Zaks 826920af014SAnna Zaks // If outside the main file, 8275ba37d52SEli Friedman if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation())) 828920af014SAnna Zaks return true; 829920af014SAnna Zaks 830920af014SAnna Zaks if (D->isOverriding()) { 831920af014SAnna Zaks // Search in the superclass on the next iteration. 832920af014SAnna Zaks IDecl = D->getClassInterface(); 833920af014SAnna Zaks if (!IDecl) 834920af014SAnna Zaks return false; 835920af014SAnna Zaks 836920af014SAnna Zaks IDecl = IDecl->getSuperClass(); 837920af014SAnna Zaks if (!IDecl) 838920af014SAnna Zaks return false; 839920af014SAnna Zaks 840920af014SAnna Zaks continue; 841920af014SAnna Zaks } 842920af014SAnna Zaks 843920af014SAnna Zaks return false; 844920af014SAnna Zaks }; 845920af014SAnna Zaks 846920af014SAnna Zaks llvm_unreachable("The while loop should always terminate."); 847920af014SAnna Zaks } 848920af014SAnna Zaks 849089c5510STed Kremenek RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 85063282aefSAnna Zaks const ObjCMessageExpr *E = getOriginExpr(); 85163282aefSAnna Zaks assert(E); 8525808eb80SAnna Zaks Selector Sel = E->getSelector(); 8534f7df9beSJordan Rose 85463282aefSAnna Zaks if (E->isInstanceMessage()) { 8555808eb80SAnna Zaks 8562c4555adSEric Christopher // Find the receiver type. 8570dbb783cSCraig Topper const ObjCObjectPointerType *ReceiverT = nullptr; 85875f49a9cSAnna Zaks bool CanBeSubClassed = false; 8595808eb80SAnna Zaks QualType SupersType = E->getSuperType(); 8600dbb783cSCraig Topper const MemRegion *Receiver = nullptr; 861123af098SAnna Zaks 8625808eb80SAnna Zaks if (!SupersType.isNull()) { 863123af098SAnna Zaks // Super always means the type of immediate predecessor to the method 864123af098SAnna Zaks // where the call occurs. 86575930b65SAnna Zaks ReceiverT = cast<ObjCObjectPointerType>(SupersType); 8665808eb80SAnna Zaks } else { 867123af098SAnna Zaks Receiver = getReceiverSVal().getAsRegion(); 8686a97d92eSJordan Rose if (!Receiver) 869123af098SAnna Zaks return RuntimeDefinition(); 8706a97d92eSJordan Rose 8714df9d812SGabor Horvath DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver); 87275f49a9cSAnna Zaks QualType DynType = DTI.getType(); 87375f49a9cSAnna Zaks CanBeSubClassed = DTI.canBeASubClass(); 87475930b65SAnna Zaks ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType); 87575f49a9cSAnna Zaks 87675f49a9cSAnna Zaks if (ReceiverT && CanBeSubClassed) 87775f49a9cSAnna Zaks if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 87875f49a9cSAnna Zaks if (!canBeOverridenInSubclass(IDecl, Sel)) 87975f49a9cSAnna Zaks CanBeSubClassed = false; 8804f7df9beSJordan Rose } 8814f7df9beSJordan Rose 8825808eb80SAnna Zaks // Lookup the method implementation. 8835808eb80SAnna Zaks if (ReceiverT) 884920af014SAnna Zaks if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 885245e45afSTed Kremenek // Repeatedly calling lookupPrivateMethod() is expensive, especially 886245e45afSTed Kremenek // when in many cases it returns null. We cache the results so 887245e45afSTed Kremenek // that repeated queries on the same ObjCIntefaceDecl and Selector 888245e45afSTed Kremenek // don't incur the same cost. On some test cases, we can see the 889245e45afSTed Kremenek // same query being issued thousands of times. 890245e45afSTed Kremenek // 891245e45afSTed Kremenek // NOTE: This cache is essentially a "global" variable, but it 892245e45afSTed Kremenek // only gets lazily created when we get here. The value of the 893245e45afSTed Kremenek // cache probably comes from it being global across ExprEngines, 894245e45afSTed Kremenek // where the same queries may get issued. If we are worried about 895245e45afSTed Kremenek // concurrency, or possibly loading/unloading ASTs, etc., we may 896245e45afSTed Kremenek // need to revisit this someday. In terms of memory, this table 897245e45afSTed Kremenek // stays around until clang quits, which also may be bad if we 898245e45afSTed Kremenek // need to release memory. 899245e45afSTed Kremenek typedef std::pair<const ObjCInterfaceDecl*, Selector> 900245e45afSTed Kremenek PrivateMethodKey; 901245e45afSTed Kremenek typedef llvm::DenseMap<PrivateMethodKey, 90205785d16SDavid Blaikie Optional<const ObjCMethodDecl *> > 903245e45afSTed Kremenek PrivateMethodCache; 904245e45afSTed Kremenek 905245e45afSTed Kremenek static PrivateMethodCache PMC; 90605785d16SDavid Blaikie Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)]; 907245e45afSTed Kremenek 908245e45afSTed Kremenek // Query lookupPrivateMethod() if the cache does not hit. 9091a866cd5SJordan Rose if (!Val.hasValue()) { 910245e45afSTed Kremenek Val = IDecl->lookupPrivateMethod(Sel); 911245e45afSTed Kremenek 9121a866cd5SJordan Rose // If the method is a property accessor, we should try to "inline" it 9131a866cd5SJordan Rose // even if we don't actually have an implementation. 9141a866cd5SJordan Rose if (!*Val) 9151a866cd5SJordan Rose if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl()) 9161a866cd5SJordan Rose if (CompileTimeMD->isPropertyAccessor()) 9171a866cd5SJordan Rose Val = IDecl->lookupInstanceMethod(Sel); 9181a866cd5SJordan Rose } 9191a866cd5SJordan Rose 920245e45afSTed Kremenek const ObjCMethodDecl *MD = Val.getValue(); 92175f49a9cSAnna Zaks if (CanBeSubClassed) 92275f49a9cSAnna Zaks return RuntimeDefinition(MD, Receiver); 923920af014SAnna Zaks else 9240dbb783cSCraig Topper return RuntimeDefinition(MD, nullptr); 925920af014SAnna Zaks } 9265808eb80SAnna Zaks 92763282aefSAnna Zaks } else { 92863282aefSAnna Zaks // This is a class method. 92963282aefSAnna Zaks // If we have type info for the receiver class, we are calling via 93063282aefSAnna Zaks // class name. 93163282aefSAnna Zaks if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 93263282aefSAnna Zaks // Find/Return the method implementation. 93385383182SAnna Zaks return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 9344f7df9beSJordan Rose } 93563282aefSAnna Zaks } 93663282aefSAnna Zaks 937123af098SAnna Zaks return RuntimeDefinition(); 9384f7df9beSJordan Rose } 9394f7df9beSJordan Rose 940514f9354SJordan Rose bool ObjCMethodCall::argumentsMayEscape() const { 941514f9354SJordan Rose if (isInSystemHeader() && !isInstanceMessage()) { 942514f9354SJordan Rose Selector Sel = getSelector(); 943514f9354SJordan Rose if (Sel.getNumArgs() == 1 && 944514f9354SJordan Rose Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer")) 945514f9354SJordan Rose return true; 946514f9354SJordan Rose } 947514f9354SJordan Rose 948514f9354SJordan Rose return CallEvent::argumentsMayEscape(); 949514f9354SJordan Rose } 950514f9354SJordan Rose 95142e8d649SJordan Rose void ObjCMethodCall::getInitialStackFrameContents( 95242e8d649SJordan Rose const StackFrameContext *CalleeCtx, 95342e8d649SJordan Rose BindingsTy &Bindings) const { 95442e8d649SJordan Rose const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 95542e8d649SJordan Rose SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 95642e8d649SJordan Rose addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 9572ff16004STed Kremenek D->parameters()); 95842e8d649SJordan Rose 95942e8d649SJordan Rose SVal SelfVal = getReceiverSVal(); 96042e8d649SJordan Rose if (!SelfVal.isUnknown()) { 96142e8d649SJordan Rose const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 96242e8d649SJordan Rose MemRegionManager &MRMgr = SVB.getRegionManager(); 96342e8d649SJordan Rose Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 96442e8d649SJordan Rose Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 96542e8d649SJordan Rose } 96642e8d649SJordan Rose } 96742e8d649SJordan Rose 968ce6c99a5SJordan Rose CallEventRef<> 969fcd016e5SJordan Rose CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 970fcd016e5SJordan Rose const LocationContext *LCtx) { 971fcd016e5SJordan Rose if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 972fcd016e5SJordan Rose return create<CXXMemberCall>(MCE, State, LCtx); 973fcd016e5SJordan Rose 974fcd016e5SJordan Rose if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 975fcd016e5SJordan Rose const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 976fcd016e5SJordan Rose if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 977fcd016e5SJordan Rose if (MD->isInstance()) 978fcd016e5SJordan Rose return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 979fcd016e5SJordan Rose 980fcd016e5SJordan Rose } else if (CE->getCallee()->getType()->isBlockPointerType()) { 981fcd016e5SJordan Rose return create<BlockCall>(CE, State, LCtx); 982fcd016e5SJordan Rose } 983fcd016e5SJordan Rose 984fcd016e5SJordan Rose // Otherwise, it's a normal function call, static member function call, or 985fcd016e5SJordan Rose // something we can't reason about. 9862a833ca5SJordan Rose return create<SimpleFunctionCall>(CE, State, LCtx); 987fcd016e5SJordan Rose } 988c2d249ceSJordan Rose 989c2d249ceSJordan Rose 990c2d249ceSJordan Rose CallEventRef<> 991c2d249ceSJordan Rose CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 992c2d249ceSJordan Rose ProgramStateRef State) { 993c2d249ceSJordan Rose const LocationContext *ParentCtx = CalleeCtx->getParent(); 994c2d249ceSJordan Rose const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 995c2d249ceSJordan Rose assert(CallerCtx && "This should not be used for top-level stack frames"); 996c2d249ceSJordan Rose 997c2d249ceSJordan Rose const Stmt *CallSite = CalleeCtx->getCallSite(); 998c2d249ceSJordan Rose 999c2d249ceSJordan Rose if (CallSite) { 1000c2d249ceSJordan Rose if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 1001c2d249ceSJordan Rose return getSimpleCall(CE, State, CallerCtx); 1002c2d249ceSJordan Rose 1003c2d249ceSJordan Rose switch (CallSite->getStmtClass()) { 10048d48938bSJordan Rose case Stmt::CXXConstructExprClass: 10058d48938bSJordan Rose case Stmt::CXXTemporaryObjectExprClass: { 1006c2d249ceSJordan Rose SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1007c2d249ceSJordan Rose const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 1008c2d249ceSJordan Rose Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 1009c2d249ceSJordan Rose SVal ThisVal = State->getSVal(ThisPtr); 1010c2d249ceSJordan Rose 1011c2d249ceSJordan Rose return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 1012c2d249ceSJordan Rose ThisVal.getAsRegion(), State, CallerCtx); 1013c2d249ceSJordan Rose } 1014c2d249ceSJordan Rose case Stmt::CXXNewExprClass: 1015c2d249ceSJordan Rose return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 1016c2d249ceSJordan Rose case Stmt::ObjCMessageExprClass: 1017c2d249ceSJordan Rose return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 1018c2d249ceSJordan Rose State, CallerCtx); 1019c2d249ceSJordan Rose default: 1020c2d249ceSJordan Rose llvm_unreachable("This is not an inlineable statement."); 1021c2d249ceSJordan Rose } 1022c2d249ceSJordan Rose } 1023c2d249ceSJordan Rose 1024c2d249ceSJordan Rose // Fall back to the CFG. The only thing we haven't handled yet is 1025c2d249ceSJordan Rose // destructors, though this could change in the future. 1026c2d249ceSJordan Rose const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 1027c2d249ceSJordan Rose CFGElement E = (*B)[CalleeCtx->getIndex()]; 10282a01f5d4SDavid Blaikie assert(E.getAs<CFGImplicitDtor>() && 10292a01f5d4SDavid Blaikie "All other CFG elements should have exprs"); 10302a01f5d4SDavid Blaikie assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet"); 1031c2d249ceSJordan Rose 1032c2d249ceSJordan Rose SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1033c2d249ceSJordan Rose const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 1034c2d249ceSJordan Rose Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 1035c2d249ceSJordan Rose SVal ThisVal = State->getSVal(ThisPtr); 1036c2d249ceSJordan Rose 1037c2d249ceSJordan Rose const Stmt *Trigger; 103800be69abSDavid Blaikie if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 103900be69abSDavid Blaikie Trigger = AutoDtor->getTriggerStmt(); 10401ccc43d5SJordan Rose else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) 10411ccc43d5SJordan Rose Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr()); 1042c2d249ceSJordan Rose else 1043c2d249ceSJordan Rose Trigger = Dtor->getBody(); 1044c2d249ceSJordan Rose 1045c2d249ceSJordan Rose return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 104600be69abSDavid Blaikie E.getAs<CFGBaseDtor>().hasValue(), State, 104700be69abSDavid Blaikie CallerCtx); 1048c2d249ceSJordan Rose } 1049