clang API Documentation
00001 //===- Calls.cpp - Wrapper for all function and method calls ------*- C++ -*--// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 /// \file This file defines CallEvent and its subclasses, which represent path- 00011 /// sensitive instances of different kinds of function and method calls 00012 /// (C, C++, and Objective-C). 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 00017 #include "clang/AST/ParentMap.h" 00018 #include "clang/Analysis/ProgramPoint.h" 00019 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 00020 #include "llvm/ADT/SmallSet.h" 00021 #include "llvm/ADT/StringExtras.h" 00022 #include "llvm/Support/raw_ostream.h" 00023 00024 using namespace clang; 00025 using namespace ento; 00026 00027 QualType CallEvent::getResultType() const { 00028 const Expr *E = getOriginExpr(); 00029 assert(E && "Calls without origin expressions do not have results"); 00030 QualType ResultTy = E->getType(); 00031 00032 ASTContext &Ctx = getState()->getStateManager().getContext(); 00033 00034 // A function that returns a reference to 'int' will have a result type 00035 // of simply 'int'. Check the origin expr's value kind to recover the 00036 // proper type. 00037 switch (E->getValueKind()) { 00038 case VK_LValue: 00039 ResultTy = Ctx.getLValueReferenceType(ResultTy); 00040 break; 00041 case VK_XValue: 00042 ResultTy = Ctx.getRValueReferenceType(ResultTy); 00043 break; 00044 case VK_RValue: 00045 // No adjustment is necessary. 00046 break; 00047 } 00048 00049 return ResultTy; 00050 } 00051 00052 static bool isCallbackArg(SVal V, QualType T) { 00053 // If the parameter is 0, it's harmless. 00054 if (V.isZeroConstant()) 00055 return false; 00056 00057 // If a parameter is a block or a callback, assume it can modify pointer. 00058 if (T->isBlockPointerType() || 00059 T->isFunctionPointerType() || 00060 T->isObjCSelType()) 00061 return true; 00062 00063 // Check if a callback is passed inside a struct (for both, struct passed by 00064 // reference and by value). Dig just one level into the struct for now. 00065 00066 if (T->isAnyPointerType() || T->isReferenceType()) 00067 T = T->getPointeeType(); 00068 00069 if (const RecordType *RT = T->getAsStructureType()) { 00070 const RecordDecl *RD = RT->getDecl(); 00071 for (const auto *I : RD->fields()) { 00072 QualType FieldT = I->getType(); 00073 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType()) 00074 return true; 00075 } 00076 } 00077 00078 return false; 00079 } 00080 00081 bool CallEvent::hasNonZeroCallbackArg() const { 00082 unsigned NumOfArgs = getNumArgs(); 00083 00084 // If calling using a function pointer, assume the function does not 00085 // have a callback. TODO: We could check the types of the arguments here. 00086 if (!getDecl()) 00087 return false; 00088 00089 unsigned Idx = 0; 00090 for (CallEvent::param_type_iterator I = param_type_begin(), 00091 E = param_type_end(); 00092 I != E && Idx < NumOfArgs; ++I, ++Idx) { 00093 if (NumOfArgs <= Idx) 00094 break; 00095 00096 if (isCallbackArg(getArgSVal(Idx), *I)) 00097 return true; 00098 } 00099 00100 return false; 00101 } 00102 00103 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { 00104 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 00105 if (!FD) 00106 return false; 00107 00108 return CheckerContext::isCLibraryFunction(FD, FunctionName); 00109 } 00110 00111 /// \brief Returns true if a type is a pointer-to-const or reference-to-const 00112 /// with no further indirection. 00113 static bool isPointerToConst(QualType Ty) { 00114 QualType PointeeTy = Ty->getPointeeType(); 00115 if (PointeeTy == QualType()) 00116 return false; 00117 if (!PointeeTy.isConstQualified()) 00118 return false; 00119 if (PointeeTy->isAnyPointerType()) 00120 return false; 00121 return true; 00122 } 00123 00124 // Try to retrieve the function declaration and find the function parameter 00125 // types which are pointers/references to a non-pointer const. 00126 // We will not invalidate the corresponding argument regions. 00127 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs, 00128 const CallEvent &Call) { 00129 unsigned Idx = 0; 00130 for (CallEvent::param_type_iterator I = Call.param_type_begin(), 00131 E = Call.param_type_end(); 00132 I != E; ++I, ++Idx) { 00133 if (isPointerToConst(*I)) 00134 PreserveArgs.insert(Idx); 00135 } 00136 } 00137 00138 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount, 00139 ProgramStateRef Orig) const { 00140 ProgramStateRef Result = (Orig ? Orig : getState()); 00141 00142 // Don't invalidate anything if the callee is marked pure/const. 00143 if (const Decl *callee = getDecl()) 00144 if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>()) 00145 return Result; 00146 00147 SmallVector<SVal, 8> ValuesToInvalidate; 00148 RegionAndSymbolInvalidationTraits ETraits; 00149 00150 getExtraInvalidatedValues(ValuesToInvalidate); 00151 00152 // Indexes of arguments whose values will be preserved by the call. 00153 llvm::SmallSet<unsigned, 4> PreserveArgs; 00154 if (!argumentsMayEscape()) 00155 findPtrToConstParams(PreserveArgs, *this); 00156 00157 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) { 00158 // Mark this region for invalidation. We batch invalidate regions 00159 // below for efficiency. 00160 if (PreserveArgs.count(Idx)) 00161 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion()) 00162 ETraits.setTrait(MR->StripCasts(), 00163 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 00164 // TODO: Factor this out + handle the lower level const pointers. 00165 00166 ValuesToInvalidate.push_back(getArgSVal(Idx)); 00167 } 00168 00169 // Invalidate designated regions using the batch invalidation API. 00170 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 00171 // global variables. 00172 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(), 00173 BlockCount, getLocationContext(), 00174 /*CausedByPointerEscape*/ true, 00175 /*Symbols=*/nullptr, this, &ETraits); 00176 } 00177 00178 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit, 00179 const ProgramPointTag *Tag) const { 00180 if (const Expr *E = getOriginExpr()) { 00181 if (IsPreVisit) 00182 return PreStmt(E, getLocationContext(), Tag); 00183 return PostStmt(E, getLocationContext(), Tag); 00184 } 00185 00186 const Decl *D = getDecl(); 00187 assert(D && "Cannot get a program point without a statement or decl"); 00188 00189 SourceLocation Loc = getSourceRange().getBegin(); 00190 if (IsPreVisit) 00191 return PreImplicitCall(D, Loc, getLocationContext(), Tag); 00192 return PostImplicitCall(D, Loc, getLocationContext(), Tag); 00193 } 00194 00195 SVal CallEvent::getArgSVal(unsigned Index) const { 00196 const Expr *ArgE = getArgExpr(Index); 00197 if (!ArgE) 00198 return UnknownVal(); 00199 return getSVal(ArgE); 00200 } 00201 00202 SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 00203 const Expr *ArgE = getArgExpr(Index); 00204 if (!ArgE) 00205 return SourceRange(); 00206 return ArgE->getSourceRange(); 00207 } 00208 00209 SVal CallEvent::getReturnValue() const { 00210 const Expr *E = getOriginExpr(); 00211 if (!E) 00212 return UndefinedVal(); 00213 return getSVal(E); 00214 } 00215 00216 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); } 00217 00218 void CallEvent::dump(raw_ostream &Out) const { 00219 ASTContext &Ctx = getState()->getStateManager().getContext(); 00220 if (const Expr *E = getOriginExpr()) { 00221 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy()); 00222 Out << "\n"; 00223 return; 00224 } 00225 00226 if (const Decl *D = getDecl()) { 00227 Out << "Call to "; 00228 D->print(Out, Ctx.getPrintingPolicy()); 00229 return; 00230 } 00231 00232 // FIXME: a string representation of the kind would be nice. 00233 Out << "Unknown call (type " << getKind() << ")"; 00234 } 00235 00236 00237 bool CallEvent::isCallStmt(const Stmt *S) { 00238 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S) 00239 || isa<CXXConstructExpr>(S) 00240 || isa<CXXNewExpr>(S); 00241 } 00242 00243 QualType CallEvent::getDeclaredResultType(const Decl *D) { 00244 assert(D); 00245 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) 00246 return FD->getReturnType(); 00247 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D)) 00248 return MD->getReturnType(); 00249 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 00250 // Blocks are difficult because the return type may not be stored in the 00251 // BlockDecl itself. The AST should probably be enhanced, but for now we 00252 // just do what we can. 00253 // If the block is declared without an explicit argument list, the 00254 // signature-as-written just includes the return type, not the entire 00255 // function type. 00256 // FIXME: All blocks should have signatures-as-written, even if the return 00257 // type is inferred. (That's signified with a dependent result type.) 00258 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) { 00259 QualType Ty = TSI->getType(); 00260 if (const FunctionType *FT = Ty->getAs<FunctionType>()) 00261 Ty = FT->getReturnType(); 00262 if (!Ty->isDependentType()) 00263 return Ty; 00264 } 00265 00266 return QualType(); 00267 } 00268 00269 llvm_unreachable("unknown callable kind"); 00270 } 00271 00272 bool CallEvent::isVariadic(const Decl *D) { 00273 assert(D); 00274 00275 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 00276 return FD->isVariadic(); 00277 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 00278 return MD->isVariadic(); 00279 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 00280 return BD->isVariadic(); 00281 00282 llvm_unreachable("unknown callable kind"); 00283 } 00284 00285 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 00286 CallEvent::BindingsTy &Bindings, 00287 SValBuilder &SVB, 00288 const CallEvent &Call, 00289 ArrayRef<ParmVarDecl*> parameters) { 00290 MemRegionManager &MRMgr = SVB.getRegionManager(); 00291 00292 // If the function has fewer parameters than the call has arguments, we simply 00293 // do not bind any values to them. 00294 unsigned NumArgs = Call.getNumArgs(); 00295 unsigned Idx = 0; 00296 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end(); 00297 for (; I != E && Idx < NumArgs; ++I, ++Idx) { 00298 const ParmVarDecl *ParamDecl = *I; 00299 assert(ParamDecl && "Formal parameter has no decl?"); 00300 00301 SVal ArgVal = Call.getArgSVal(Idx); 00302 if (!ArgVal.isUnknown()) { 00303 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx)); 00304 Bindings.push_back(std::make_pair(ParamLoc, ArgVal)); 00305 } 00306 } 00307 00308 // FIXME: Variadic arguments are not handled at all right now. 00309 } 00310 00311 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const { 00312 const FunctionDecl *D = getDecl(); 00313 if (!D) 00314 return None; 00315 return D->parameters(); 00316 } 00317 00318 void AnyFunctionCall::getInitialStackFrameContents( 00319 const StackFrameContext *CalleeCtx, 00320 BindingsTy &Bindings) const { 00321 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 00322 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 00323 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 00324 D->parameters()); 00325 } 00326 00327 bool AnyFunctionCall::argumentsMayEscape() const { 00328 if (hasNonZeroCallbackArg()) 00329 return true; 00330 00331 const FunctionDecl *D = getDecl(); 00332 if (!D) 00333 return true; 00334 00335 const IdentifierInfo *II = D->getIdentifier(); 00336 if (!II) 00337 return false; 00338 00339 // This set of "escaping" APIs is 00340 00341 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 00342 // value into thread local storage. The value can later be retrieved with 00343 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 00344 // parameter is 'const void *', the region escapes through the call. 00345 if (II->isStr("pthread_setspecific")) 00346 return true; 00347 00348 // - xpc_connection_set_context stores a value which can be retrieved later 00349 // with xpc_connection_get_context. 00350 if (II->isStr("xpc_connection_set_context")) 00351 return true; 00352 00353 // - funopen - sets a buffer for future IO calls. 00354 if (II->isStr("funopen")) 00355 return true; 00356 00357 StringRef FName = II->getName(); 00358 00359 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 00360 // buffer even if it is const. 00361 if (FName.endswith("NoCopy")) 00362 return true; 00363 00364 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 00365 // be deallocated by NSMapRemove. 00366 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 00367 return true; 00368 00369 // - Many CF containers allow objects to escape through custom 00370 // allocators/deallocators upon container construction. (PR12101) 00371 if (FName.startswith("CF") || FName.startswith("CG")) { 00372 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 00373 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 00374 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 00375 StrInStrNoCase(FName, "WithData") != StringRef::npos || 00376 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 00377 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 00378 } 00379 00380 return false; 00381 } 00382 00383 00384 const FunctionDecl *SimpleFunctionCall::getDecl() const { 00385 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 00386 if (D) 00387 return D; 00388 00389 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 00390 } 00391 00392 00393 const FunctionDecl *CXXInstanceCall::getDecl() const { 00394 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr()); 00395 if (!CE) 00396 return AnyFunctionCall::getDecl(); 00397 00398 const FunctionDecl *D = CE->getDirectCallee(); 00399 if (D) 00400 return D; 00401 00402 return getSVal(CE->getCallee()).getAsFunctionDecl(); 00403 } 00404 00405 void CXXInstanceCall::getExtraInvalidatedValues(ValueList &Values) const { 00406 Values.push_back(getCXXThisVal()); 00407 } 00408 00409 SVal CXXInstanceCall::getCXXThisVal() const { 00410 const Expr *Base = getCXXThisExpr(); 00411 // FIXME: This doesn't handle an overloaded ->* operator. 00412 if (!Base) 00413 return UnknownVal(); 00414 00415 SVal ThisVal = getSVal(Base); 00416 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 00417 return ThisVal; 00418 } 00419 00420 00421 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 00422 // Do we have a decl at all? 00423 const Decl *D = getDecl(); 00424 if (!D) 00425 return RuntimeDefinition(); 00426 00427 // If the method is non-virtual, we know we can inline it. 00428 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 00429 if (!MD->isVirtual()) 00430 return AnyFunctionCall::getRuntimeDefinition(); 00431 00432 // Do we know the implicit 'this' object being called? 00433 const MemRegion *R = getCXXThisVal().getAsRegion(); 00434 if (!R) 00435 return RuntimeDefinition(); 00436 00437 // Do we know anything about the type of 'this'? 00438 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R); 00439 if (!DynType.isValid()) 00440 return RuntimeDefinition(); 00441 00442 // Is the type a C++ class? (This is mostly a defensive check.) 00443 QualType RegionType = DynType.getType()->getPointeeType(); 00444 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 00445 00446 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 00447 if (!RD || !RD->hasDefinition()) 00448 return RuntimeDefinition(); 00449 00450 // Find the decl for this method in that class. 00451 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 00452 if (!Result) { 00453 // We might not even get the original statically-resolved method due to 00454 // some particularly nasty casting (e.g. casts to sister classes). 00455 // However, we should at least be able to search up and down our own class 00456 // hierarchy, and some real bugs have been caught by checking this. 00457 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 00458 00459 // FIXME: This is checking that our DynamicTypeInfo is at least as good as 00460 // the static type. However, because we currently don't update 00461 // DynamicTypeInfo when an object is cast, we can't actually be sure the 00462 // DynamicTypeInfo is up to date. This assert should be re-enabled once 00463 // this is fixed. <rdar://problem/12287087> 00464 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 00465 00466 return RuntimeDefinition(); 00467 } 00468 00469 // Does the decl that we found have an implementation? 00470 const FunctionDecl *Definition; 00471 if (!Result->hasBody(Definition)) 00472 return RuntimeDefinition(); 00473 00474 // We found a definition. If we're not sure that this devirtualization is 00475 // actually what will happen at runtime, make sure to provide the region so 00476 // that ExprEngine can decide what to do with it. 00477 if (DynType.canBeASubClass()) 00478 return RuntimeDefinition(Definition, R->StripCasts()); 00479 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr); 00480 } 00481 00482 void CXXInstanceCall::getInitialStackFrameContents( 00483 const StackFrameContext *CalleeCtx, 00484 BindingsTy &Bindings) const { 00485 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 00486 00487 // Handle the binding of 'this' in the new stack frame. 00488 SVal ThisVal = getCXXThisVal(); 00489 if (!ThisVal.isUnknown()) { 00490 ProgramStateManager &StateMgr = getState()->getStateManager(); 00491 SValBuilder &SVB = StateMgr.getSValBuilder(); 00492 00493 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 00494 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 00495 00496 // If we devirtualized to a different member function, we need to make sure 00497 // we have the proper layering of CXXBaseObjectRegions. 00498 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 00499 ASTContext &Ctx = SVB.getContext(); 00500 const CXXRecordDecl *Class = MD->getParent(); 00501 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 00502 00503 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 00504 bool Failed; 00505 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed); 00506 assert(!Failed && "Calling an incorrectly devirtualized method"); 00507 } 00508 00509 if (!ThisVal.isUnknown()) 00510 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 00511 } 00512 } 00513 00514 00515 00516 const Expr *CXXMemberCall::getCXXThisExpr() const { 00517 return getOriginExpr()->getImplicitObjectArgument(); 00518 } 00519 00520 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 00521 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 00522 // id-expression in the class member access expression is a qualified-id, 00523 // that function is called. Otherwise, its final overrider in the dynamic type 00524 // of the object expression is called. 00525 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 00526 if (ME->hasQualifier()) 00527 return AnyFunctionCall::getRuntimeDefinition(); 00528 00529 return CXXInstanceCall::getRuntimeDefinition(); 00530 } 00531 00532 00533 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 00534 return getOriginExpr()->getArg(0); 00535 } 00536 00537 00538 const BlockDataRegion *BlockCall::getBlockRegion() const { 00539 const Expr *Callee = getOriginExpr()->getCallee(); 00540 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 00541 00542 return dyn_cast_or_null<BlockDataRegion>(DataReg); 00543 } 00544 00545 ArrayRef<ParmVarDecl*> BlockCall::parameters() const { 00546 const BlockDecl *D = getDecl(); 00547 if (!D) 00548 return nullptr; 00549 return D->parameters(); 00550 } 00551 00552 void BlockCall::getExtraInvalidatedValues(ValueList &Values) const { 00553 // FIXME: This also needs to invalidate captured globals. 00554 if (const MemRegion *R = getBlockRegion()) 00555 Values.push_back(loc::MemRegionVal(R)); 00556 } 00557 00558 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 00559 BindingsTy &Bindings) const { 00560 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl()); 00561 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 00562 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 00563 D->parameters()); 00564 } 00565 00566 00567 SVal CXXConstructorCall::getCXXThisVal() const { 00568 if (Data) 00569 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 00570 return UnknownVal(); 00571 } 00572 00573 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values) const { 00574 if (Data) 00575 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data))); 00576 } 00577 00578 void CXXConstructorCall::getInitialStackFrameContents( 00579 const StackFrameContext *CalleeCtx, 00580 BindingsTy &Bindings) const { 00581 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 00582 00583 SVal ThisVal = getCXXThisVal(); 00584 if (!ThisVal.isUnknown()) { 00585 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 00586 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 00587 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 00588 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 00589 } 00590 } 00591 00592 SVal CXXDestructorCall::getCXXThisVal() const { 00593 if (Data) 00594 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 00595 return UnknownVal(); 00596 } 00597 00598 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 00599 // Base destructors are always called non-virtually. 00600 // Skip CXXInstanceCall's devirtualization logic in this case. 00601 if (isBaseDestructor()) 00602 return AnyFunctionCall::getRuntimeDefinition(); 00603 00604 return CXXInstanceCall::getRuntimeDefinition(); 00605 } 00606 00607 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const { 00608 const ObjCMethodDecl *D = getDecl(); 00609 if (!D) 00610 return None; 00611 return D->parameters(); 00612 } 00613 00614 void 00615 ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values) const { 00616 Values.push_back(getReceiverSVal()); 00617 } 00618 00619 SVal ObjCMethodCall::getSelfSVal() const { 00620 const LocationContext *LCtx = getLocationContext(); 00621 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 00622 if (!SelfDecl) 00623 return SVal(); 00624 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 00625 } 00626 00627 SVal ObjCMethodCall::getReceiverSVal() const { 00628 // FIXME: Is this the best way to handle class receivers? 00629 if (!isInstanceMessage()) 00630 return UnknownVal(); 00631 00632 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 00633 return getSVal(RecE); 00634 00635 // An instance message with no expression means we are sending to super. 00636 // In this case the object reference is the same as 'self'. 00637 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 00638 SVal SelfVal = getSelfSVal(); 00639 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 00640 return SelfVal; 00641 } 00642 00643 bool ObjCMethodCall::isReceiverSelfOrSuper() const { 00644 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 00645 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 00646 return true; 00647 00648 if (!isInstanceMessage()) 00649 return false; 00650 00651 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 00652 00653 return (RecVal == getSelfSVal()); 00654 } 00655 00656 SourceRange ObjCMethodCall::getSourceRange() const { 00657 switch (getMessageKind()) { 00658 case OCM_Message: 00659 return getOriginExpr()->getSourceRange(); 00660 case OCM_PropertyAccess: 00661 case OCM_Subscript: 00662 return getContainingPseudoObjectExpr()->getSourceRange(); 00663 } 00664 llvm_unreachable("unknown message kind"); 00665 } 00666 00667 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy; 00668 00669 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 00670 assert(Data && "Lazy lookup not yet performed."); 00671 assert(getMessageKind() != OCM_Message && "Explicit message send."); 00672 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 00673 } 00674 00675 ObjCMessageKind ObjCMethodCall::getMessageKind() const { 00676 if (!Data) { 00677 00678 // Find the parent, ignoring implicit casts. 00679 ParentMap &PM = getLocationContext()->getParentMap(); 00680 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr()); 00681 00682 // Check if parent is a PseudoObjectExpr. 00683 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 00684 const Expr *Syntactic = POE->getSyntacticForm(); 00685 00686 // This handles the funny case of assigning to the result of a getter. 00687 // This can happen if the getter returns a non-const reference. 00688 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic)) 00689 Syntactic = BO->getLHS(); 00690 00691 ObjCMessageKind K; 00692 switch (Syntactic->getStmtClass()) { 00693 case Stmt::ObjCPropertyRefExprClass: 00694 K = OCM_PropertyAccess; 00695 break; 00696 case Stmt::ObjCSubscriptRefExprClass: 00697 K = OCM_Subscript; 00698 break; 00699 default: 00700 // FIXME: Can this ever happen? 00701 K = OCM_Message; 00702 break; 00703 } 00704 00705 if (K != OCM_Message) { 00706 const_cast<ObjCMethodCall *>(this)->Data 00707 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 00708 assert(getMessageKind() == K); 00709 return K; 00710 } 00711 } 00712 00713 const_cast<ObjCMethodCall *>(this)->Data 00714 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue(); 00715 assert(getMessageKind() == OCM_Message); 00716 return OCM_Message; 00717 } 00718 00719 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 00720 if (!Info.getPointer()) 00721 return OCM_Message; 00722 return static_cast<ObjCMessageKind>(Info.getInt()); 00723 } 00724 00725 00726 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 00727 Selector Sel) const { 00728 assert(IDecl); 00729 const SourceManager &SM = 00730 getState()->getStateManager().getContext().getSourceManager(); 00731 00732 // If the class interface is declared inside the main file, assume it is not 00733 // subcassed. 00734 // TODO: It could actually be subclassed if the subclass is private as well. 00735 // This is probably very rare. 00736 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 00737 if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc)) 00738 return false; 00739 00740 // Assume that property accessors are not overridden. 00741 if (getMessageKind() == OCM_PropertyAccess) 00742 return false; 00743 00744 // We assume that if the method is public (declared outside of main file) or 00745 // has a parent which publicly declares the method, the method could be 00746 // overridden in a subclass. 00747 00748 // Find the first declaration in the class hierarchy that declares 00749 // the selector. 00750 ObjCMethodDecl *D = nullptr; 00751 while (true) { 00752 D = IDecl->lookupMethod(Sel, true); 00753 00754 // Cannot find a public definition. 00755 if (!D) 00756 return false; 00757 00758 // If outside the main file, 00759 if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation())) 00760 return true; 00761 00762 if (D->isOverriding()) { 00763 // Search in the superclass on the next iteration. 00764 IDecl = D->getClassInterface(); 00765 if (!IDecl) 00766 return false; 00767 00768 IDecl = IDecl->getSuperClass(); 00769 if (!IDecl) 00770 return false; 00771 00772 continue; 00773 } 00774 00775 return false; 00776 }; 00777 00778 llvm_unreachable("The while loop should always terminate."); 00779 } 00780 00781 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 00782 const ObjCMessageExpr *E = getOriginExpr(); 00783 assert(E); 00784 Selector Sel = E->getSelector(); 00785 00786 if (E->isInstanceMessage()) { 00787 00788 // Find the the receiver type. 00789 const ObjCObjectPointerType *ReceiverT = nullptr; 00790 bool CanBeSubClassed = false; 00791 QualType SupersType = E->getSuperType(); 00792 const MemRegion *Receiver = nullptr; 00793 00794 if (!SupersType.isNull()) { 00795 // Super always means the type of immediate predecessor to the method 00796 // where the call occurs. 00797 ReceiverT = cast<ObjCObjectPointerType>(SupersType); 00798 } else { 00799 Receiver = getReceiverSVal().getAsRegion(); 00800 if (!Receiver) 00801 return RuntimeDefinition(); 00802 00803 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver); 00804 QualType DynType = DTI.getType(); 00805 CanBeSubClassed = DTI.canBeASubClass(); 00806 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType); 00807 00808 if (ReceiverT && CanBeSubClassed) 00809 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 00810 if (!canBeOverridenInSubclass(IDecl, Sel)) 00811 CanBeSubClassed = false; 00812 } 00813 00814 // Lookup the method implementation. 00815 if (ReceiverT) 00816 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 00817 // Repeatedly calling lookupPrivateMethod() is expensive, especially 00818 // when in many cases it returns null. We cache the results so 00819 // that repeated queries on the same ObjCIntefaceDecl and Selector 00820 // don't incur the same cost. On some test cases, we can see the 00821 // same query being issued thousands of times. 00822 // 00823 // NOTE: This cache is essentially a "global" variable, but it 00824 // only gets lazily created when we get here. The value of the 00825 // cache probably comes from it being global across ExprEngines, 00826 // where the same queries may get issued. If we are worried about 00827 // concurrency, or possibly loading/unloading ASTs, etc., we may 00828 // need to revisit this someday. In terms of memory, this table 00829 // stays around until clang quits, which also may be bad if we 00830 // need to release memory. 00831 typedef std::pair<const ObjCInterfaceDecl*, Selector> 00832 PrivateMethodKey; 00833 typedef llvm::DenseMap<PrivateMethodKey, 00834 Optional<const ObjCMethodDecl *> > 00835 PrivateMethodCache; 00836 00837 static PrivateMethodCache PMC; 00838 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)]; 00839 00840 // Query lookupPrivateMethod() if the cache does not hit. 00841 if (!Val.hasValue()) { 00842 Val = IDecl->lookupPrivateMethod(Sel); 00843 00844 // If the method is a property accessor, we should try to "inline" it 00845 // even if we don't actually have an implementation. 00846 if (!*Val) 00847 if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl()) 00848 if (CompileTimeMD->isPropertyAccessor()) 00849 Val = IDecl->lookupInstanceMethod(Sel); 00850 } 00851 00852 const ObjCMethodDecl *MD = Val.getValue(); 00853 if (CanBeSubClassed) 00854 return RuntimeDefinition(MD, Receiver); 00855 else 00856 return RuntimeDefinition(MD, nullptr); 00857 } 00858 00859 } else { 00860 // This is a class method. 00861 // If we have type info for the receiver class, we are calling via 00862 // class name. 00863 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 00864 // Find/Return the method implementation. 00865 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 00866 } 00867 } 00868 00869 return RuntimeDefinition(); 00870 } 00871 00872 bool ObjCMethodCall::argumentsMayEscape() const { 00873 if (isInSystemHeader() && !isInstanceMessage()) { 00874 Selector Sel = getSelector(); 00875 if (Sel.getNumArgs() == 1 && 00876 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer")) 00877 return true; 00878 } 00879 00880 return CallEvent::argumentsMayEscape(); 00881 } 00882 00883 void ObjCMethodCall::getInitialStackFrameContents( 00884 const StackFrameContext *CalleeCtx, 00885 BindingsTy &Bindings) const { 00886 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 00887 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 00888 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 00889 D->parameters()); 00890 00891 SVal SelfVal = getReceiverSVal(); 00892 if (!SelfVal.isUnknown()) { 00893 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 00894 MemRegionManager &MRMgr = SVB.getRegionManager(); 00895 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 00896 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 00897 } 00898 } 00899 00900 CallEventRef<> 00901 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 00902 const LocationContext *LCtx) { 00903 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 00904 return create<CXXMemberCall>(MCE, State, LCtx); 00905 00906 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 00907 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 00908 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 00909 if (MD->isInstance()) 00910 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 00911 00912 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 00913 return create<BlockCall>(CE, State, LCtx); 00914 } 00915 00916 // Otherwise, it's a normal function call, static member function call, or 00917 // something we can't reason about. 00918 return create<SimpleFunctionCall>(CE, State, LCtx); 00919 } 00920 00921 00922 CallEventRef<> 00923 CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 00924 ProgramStateRef State) { 00925 const LocationContext *ParentCtx = CalleeCtx->getParent(); 00926 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 00927 assert(CallerCtx && "This should not be used for top-level stack frames"); 00928 00929 const Stmt *CallSite = CalleeCtx->getCallSite(); 00930 00931 if (CallSite) { 00932 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 00933 return getSimpleCall(CE, State, CallerCtx); 00934 00935 switch (CallSite->getStmtClass()) { 00936 case Stmt::CXXConstructExprClass: 00937 case Stmt::CXXTemporaryObjectExprClass: { 00938 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 00939 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 00940 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 00941 SVal ThisVal = State->getSVal(ThisPtr); 00942 00943 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 00944 ThisVal.getAsRegion(), State, CallerCtx); 00945 } 00946 case Stmt::CXXNewExprClass: 00947 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 00948 case Stmt::ObjCMessageExprClass: 00949 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 00950 State, CallerCtx); 00951 default: 00952 llvm_unreachable("This is not an inlineable statement."); 00953 } 00954 } 00955 00956 // Fall back to the CFG. The only thing we haven't handled yet is 00957 // destructors, though this could change in the future. 00958 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 00959 CFGElement E = (*B)[CalleeCtx->getIndex()]; 00960 assert(E.getAs<CFGImplicitDtor>() && 00961 "All other CFG elements should have exprs"); 00962 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet"); 00963 00964 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 00965 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 00966 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 00967 SVal ThisVal = State->getSVal(ThisPtr); 00968 00969 const Stmt *Trigger; 00970 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 00971 Trigger = AutoDtor->getTriggerStmt(); 00972 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) 00973 Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr()); 00974 else 00975 Trigger = Dtor->getBody(); 00976 00977 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 00978 E.getAs<CFGBaseDtor>().hasValue(), State, 00979 CallerCtx); 00980 }