CallEvent.cpp revision f8ddc098981d4d85cad4e72fc6dfcfe83b842b66
1//===- Calls.cpp - Wrapper for all function and method calls ------*- C++ -*--// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10/// \file This file defines CallEvent and its subclasses, which represent path- 11/// sensitive instances of different kinds of function and method calls 12/// (C, C++, and Objective-C). 13// 14//===----------------------------------------------------------------------===// 15 16#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 17#include "clang/AST/ParentMap.h" 18#include "clang/Analysis/ProgramPoint.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 20#include "llvm/ADT/SmallSet.h" 21#include "llvm/ADT/StringExtras.h" 22#include "llvm/Support/raw_ostream.h" 23 24using namespace clang; 25using namespace ento; 26 27QualType CallEvent::getResultType() const { 28 const Expr *E = getOriginExpr(); 29 assert(E && "Calls without origin expressions do not have results"); 30 QualType ResultTy = E->getType(); 31 32 ASTContext &Ctx = getState()->getStateManager().getContext(); 33 34 // A function that returns a reference to 'int' will have a result type 35 // of simply 'int'. Check the origin expr's value kind to recover the 36 // proper type. 37 switch (E->getValueKind()) { 38 case VK_LValue: 39 ResultTy = Ctx.getLValueReferenceType(ResultTy); 40 break; 41 case VK_XValue: 42 ResultTy = Ctx.getRValueReferenceType(ResultTy); 43 break; 44 case VK_RValue: 45 // No adjustment is necessary. 46 break; 47 } 48 49 return ResultTy; 50} 51 52static bool isCallbackArg(SVal V, QualType T) { 53 // If the parameter is 0, it's harmless. 54 if (V.isZeroConstant()) 55 return false; 56 57 // If a parameter is a block or a callback, assume it can modify pointer. 58 if (T->isBlockPointerType() || 59 T->isFunctionPointerType() || 60 T->isObjCSelType()) 61 return true; 62 63 // Check if a callback is passed inside a struct (for both, struct passed by 64 // reference and by value). Dig just one level into the struct for now. 65 66 if (T->isAnyPointerType() || T->isReferenceType()) 67 T = T->getPointeeType(); 68 69 if (const RecordType *RT = T->getAsStructureType()) { 70 const RecordDecl *RD = RT->getDecl(); 71 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 72 I != E; ++I) { 73 QualType FieldT = I->getType(); 74 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType()) 75 return true; 76 } 77 } 78 79 return false; 80} 81 82bool CallEvent::hasNonZeroCallbackArg() const { 83 unsigned NumOfArgs = getNumArgs(); 84 85 // If calling using a function pointer, assume the function does not 86 // have a callback. TODO: We could check the types of the arguments here. 87 if (!getDecl()) 88 return false; 89 90 unsigned Idx = 0; 91 for (CallEvent::param_type_iterator I = param_type_begin(), 92 E = param_type_end(); 93 I != E && Idx < NumOfArgs; ++I, ++Idx) { 94 if (NumOfArgs <= Idx) 95 break; 96 97 if (isCallbackArg(getArgSVal(Idx), *I)) 98 return true; 99 } 100 101 return false; 102} 103 104bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { 105 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 106 if (!FD) 107 return false; 108 109 return CheckerContext::isCLibraryFunction(FD, FunctionName); 110} 111 112/// \brief Returns true if a type is a pointer-to-const or reference-to-const 113/// with no further indirection. 114static bool isPointerToConst(QualType Ty) { 115 QualType PointeeTy = Ty->getPointeeType(); 116 if (PointeeTy == QualType()) 117 return false; 118 if (!PointeeTy.isConstQualified()) 119 return false; 120 if (PointeeTy->isAnyPointerType()) 121 return false; 122 return true; 123} 124 125// Try to retrieve the function declaration and find the function parameter 126// types which are pointers/references to a non-pointer const. 127// We will not invalidate the corresponding argument regions. 128static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs, 129 const CallEvent &Call) { 130 unsigned Idx = 0; 131 for (CallEvent::param_type_iterator I = Call.param_type_begin(), 132 E = Call.param_type_end(); 133 I != E; ++I, ++Idx) { 134 if (isPointerToConst(*I)) 135 PreserveArgs.insert(Idx); 136 } 137} 138 139ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount, 140 ProgramStateRef Orig) const { 141 ProgramStateRef Result = (Orig ? Orig : getState()); 142 143 SmallVector<const MemRegion *, 8> ConstRegions; 144 SmallVector<const MemRegion *, 8> RegionsToInvalidate; 145 getExtraInvalidatedRegions(RegionsToInvalidate); 146 147 // Indexes of arguments whose values will be preserved by the call. 148 llvm::SmallSet<unsigned, 4> PreserveArgs; 149 if (!argumentsMayEscape()) 150 findPtrToConstParams(PreserveArgs, *this); 151 152 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) { 153 const MemRegion *R = getArgSVal(Idx).getAsRegion(); 154 if (!R) 155 continue; 156 157 // Mark this region for invalidation. We batch invalidate regions 158 // below for efficiency. 159 if (PreserveArgs.count(Idx)) 160 ConstRegions.push_back(R); 161 else 162 RegionsToInvalidate.push_back(R); 163 } 164 165 // Invalidate designated regions using the batch invalidation API. 166 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 167 // global variables. 168 return Result->invalidateRegions(RegionsToInvalidate, getOriginExpr(), 169 BlockCount, getLocationContext(), 170 /*CausedByPointerEscape*/ true, 171 /*Symbols=*/0, this, ConstRegions); 172} 173 174ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit, 175 const ProgramPointTag *Tag) const { 176 if (const Expr *E = getOriginExpr()) { 177 if (IsPreVisit) 178 return PreStmt(E, getLocationContext(), Tag); 179 return PostStmt(E, getLocationContext(), Tag); 180 } 181 182 const Decl *D = getDecl(); 183 assert(D && "Cannot get a program point without a statement or decl"); 184 185 SourceLocation Loc = getSourceRange().getBegin(); 186 if (IsPreVisit) 187 return PreImplicitCall(D, Loc, getLocationContext(), Tag); 188 return PostImplicitCall(D, Loc, getLocationContext(), Tag); 189} 190 191SVal CallEvent::getArgSVal(unsigned Index) const { 192 const Expr *ArgE = getArgExpr(Index); 193 if (!ArgE) 194 return UnknownVal(); 195 return getSVal(ArgE); 196} 197 198SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 199 const Expr *ArgE = getArgExpr(Index); 200 if (!ArgE) 201 return SourceRange(); 202 return ArgE->getSourceRange(); 203} 204 205SVal CallEvent::getReturnValue() const { 206 const Expr *E = getOriginExpr(); 207 if (!E) 208 return UndefinedVal(); 209 return getSVal(E); 210} 211 212void CallEvent::dump() const { 213 dump(llvm::errs()); 214} 215 216void CallEvent::dump(raw_ostream &Out) const { 217 ASTContext &Ctx = getState()->getStateManager().getContext(); 218 if (const Expr *E = getOriginExpr()) { 219 E->printPretty(Out, 0, Ctx.getPrintingPolicy()); 220 Out << "\n"; 221 return; 222 } 223 224 if (const Decl *D = getDecl()) { 225 Out << "Call to "; 226 D->print(Out, Ctx.getPrintingPolicy()); 227 return; 228 } 229 230 // FIXME: a string representation of the kind would be nice. 231 Out << "Unknown call (type " << getKind() << ")"; 232} 233 234 235bool CallEvent::isCallStmt(const Stmt *S) { 236 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S) 237 || isa<CXXConstructExpr>(S) 238 || isa<CXXNewExpr>(S); 239} 240 241QualType CallEvent::getDeclaredResultType(const Decl *D) { 242 assert(D); 243 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) 244 return FD->getResultType(); 245 else if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D)) 246 return MD->getResultType(); 247 return QualType(); 248} 249 250static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 251 CallEvent::BindingsTy &Bindings, 252 SValBuilder &SVB, 253 const CallEvent &Call, 254 CallEvent::param_iterator I, 255 CallEvent::param_iterator E) { 256 MemRegionManager &MRMgr = SVB.getRegionManager(); 257 258 unsigned Idx = 0; 259 for (; I != E; ++I, ++Idx) { 260 const ParmVarDecl *ParamDecl = *I; 261 assert(ParamDecl && "Formal parameter has no decl?"); 262 263 SVal ArgVal = Call.getArgSVal(Idx); 264 if (!ArgVal.isUnknown()) { 265 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx)); 266 Bindings.push_back(std::make_pair(ParamLoc, ArgVal)); 267 } 268 } 269 270 // FIXME: Variadic arguments are not handled at all right now. 271} 272 273 274CallEvent::param_iterator AnyFunctionCall::param_begin() const { 275 const FunctionDecl *D = getDecl(); 276 if (!D) 277 return 0; 278 279 return D->param_begin(); 280} 281 282CallEvent::param_iterator AnyFunctionCall::param_end() const { 283 const FunctionDecl *D = getDecl(); 284 if (!D) 285 return 0; 286 287 return D->param_end(); 288} 289 290void AnyFunctionCall::getInitialStackFrameContents( 291 const StackFrameContext *CalleeCtx, 292 BindingsTy &Bindings) const { 293 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 294 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 295 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 296 D->param_begin(), D->param_end()); 297} 298 299bool AnyFunctionCall::argumentsMayEscape() const { 300 if (hasNonZeroCallbackArg()) 301 return true; 302 303 const FunctionDecl *D = getDecl(); 304 if (!D) 305 return true; 306 307 const IdentifierInfo *II = D->getIdentifier(); 308 if (!II) 309 return false; 310 311 // This set of "escaping" APIs is 312 313 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 314 // value into thread local storage. The value can later be retrieved with 315 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 316 // parameter is 'const void *', the region escapes through the call. 317 if (II->isStr("pthread_setspecific")) 318 return true; 319 320 // - xpc_connection_set_context stores a value which can be retrieved later 321 // with xpc_connection_get_context. 322 if (II->isStr("xpc_connection_set_context")) 323 return true; 324 325 // - funopen - sets a buffer for future IO calls. 326 if (II->isStr("funopen")) 327 return true; 328 329 StringRef FName = II->getName(); 330 331 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 332 // buffer even if it is const. 333 if (FName.endswith("NoCopy")) 334 return true; 335 336 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 337 // be deallocated by NSMapRemove. 338 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 339 return true; 340 341 // - Many CF containers allow objects to escape through custom 342 // allocators/deallocators upon container construction. (PR12101) 343 if (FName.startswith("CF") || FName.startswith("CG")) { 344 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 345 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 346 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 347 StrInStrNoCase(FName, "WithData") != StringRef::npos || 348 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 349 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 350 } 351 352 return false; 353} 354 355 356const FunctionDecl *SimpleCall::getDecl() const { 357 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 358 if (D) 359 return D; 360 361 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 362} 363 364 365const FunctionDecl *CXXInstanceCall::getDecl() const { 366 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr()); 367 if (!CE) 368 return AnyFunctionCall::getDecl(); 369 370 const FunctionDecl *D = CE->getDirectCallee(); 371 if (D) 372 return D; 373 374 return getSVal(CE->getCallee()).getAsFunctionDecl(); 375} 376 377void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const { 378 if (const MemRegion *R = getCXXThisVal().getAsRegion()) 379 Regions.push_back(R); 380} 381 382SVal CXXInstanceCall::getCXXThisVal() const { 383 const Expr *Base = getCXXThisExpr(); 384 // FIXME: This doesn't handle an overloaded ->* operator. 385 if (!Base) 386 return UnknownVal(); 387 388 SVal ThisVal = getSVal(Base); 389 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 390 return ThisVal; 391} 392 393 394RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 395 // Do we have a decl at all? 396 const Decl *D = getDecl(); 397 if (!D) 398 return RuntimeDefinition(); 399 400 // If the method is non-virtual, we know we can inline it. 401 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 402 if (!MD->isVirtual()) 403 return AnyFunctionCall::getRuntimeDefinition(); 404 405 // Do we know the implicit 'this' object being called? 406 const MemRegion *R = getCXXThisVal().getAsRegion(); 407 if (!R) 408 return RuntimeDefinition(); 409 410 // Do we know anything about the type of 'this'? 411 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R); 412 if (!DynType.isValid()) 413 return RuntimeDefinition(); 414 415 // Is the type a C++ class? (This is mostly a defensive check.) 416 QualType RegionType = DynType.getType()->getPointeeType(); 417 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 418 419 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 420 if (!RD || !RD->hasDefinition()) 421 return RuntimeDefinition(); 422 423 // Find the decl for this method in that class. 424 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 425 if (!Result) { 426 // We might not even get the original statically-resolved method due to 427 // some particularly nasty casting (e.g. casts to sister classes). 428 // However, we should at least be able to search up and down our own class 429 // hierarchy, and some real bugs have been caught by checking this. 430 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 431 432 // FIXME: This is checking that our DynamicTypeInfo is at least as good as 433 // the static type. However, because we currently don't update 434 // DynamicTypeInfo when an object is cast, we can't actually be sure the 435 // DynamicTypeInfo is up to date. This assert should be re-enabled once 436 // this is fixed. <rdar://problem/12287087> 437 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 438 439 return RuntimeDefinition(); 440 } 441 442 // Does the decl that we found have an implementation? 443 const FunctionDecl *Definition; 444 if (!Result->hasBody(Definition)) 445 return RuntimeDefinition(); 446 447 // We found a definition. If we're not sure that this devirtualization is 448 // actually what will happen at runtime, make sure to provide the region so 449 // that ExprEngine can decide what to do with it. 450 if (DynType.canBeASubClass()) 451 return RuntimeDefinition(Definition, R->StripCasts()); 452 return RuntimeDefinition(Definition, /*DispatchRegion=*/0); 453} 454 455void CXXInstanceCall::getInitialStackFrameContents( 456 const StackFrameContext *CalleeCtx, 457 BindingsTy &Bindings) const { 458 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 459 460 // Handle the binding of 'this' in the new stack frame. 461 SVal ThisVal = getCXXThisVal(); 462 if (!ThisVal.isUnknown()) { 463 ProgramStateManager &StateMgr = getState()->getStateManager(); 464 SValBuilder &SVB = StateMgr.getSValBuilder(); 465 466 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 467 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 468 469 // If we devirtualized to a different member function, we need to make sure 470 // we have the proper layering of CXXBaseObjectRegions. 471 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 472 ASTContext &Ctx = SVB.getContext(); 473 const CXXRecordDecl *Class = MD->getParent(); 474 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 475 476 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 477 bool Failed; 478 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed); 479 assert(!Failed && "Calling an incorrectly devirtualized method"); 480 } 481 482 if (!ThisVal.isUnknown()) 483 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 484 } 485} 486 487 488 489const Expr *CXXMemberCall::getCXXThisExpr() const { 490 return getOriginExpr()->getImplicitObjectArgument(); 491} 492 493RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 494 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 495 // id-expression in the class member access expression is a qualified-id, 496 // that function is called. Otherwise, its final overrider in the dynamic type 497 // of the object expression is called. 498 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 499 if (ME->hasQualifier()) 500 return AnyFunctionCall::getRuntimeDefinition(); 501 502 return CXXInstanceCall::getRuntimeDefinition(); 503} 504 505 506const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 507 return getOriginExpr()->getArg(0); 508} 509 510 511const BlockDataRegion *BlockCall::getBlockRegion() const { 512 const Expr *Callee = getOriginExpr()->getCallee(); 513 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 514 515 return dyn_cast_or_null<BlockDataRegion>(DataReg); 516} 517 518CallEvent::param_iterator BlockCall::param_begin() const { 519 const BlockDecl *D = getBlockDecl(); 520 if (!D) 521 return 0; 522 return D->param_begin(); 523} 524 525CallEvent::param_iterator BlockCall::param_end() const { 526 const BlockDecl *D = getBlockDecl(); 527 if (!D) 528 return 0; 529 return D->param_end(); 530} 531 532void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const { 533 // FIXME: This also needs to invalidate captured globals. 534 if (const MemRegion *R = getBlockRegion()) 535 Regions.push_back(R); 536} 537 538void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 539 BindingsTy &Bindings) const { 540 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl()); 541 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 542 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 543 D->param_begin(), D->param_end()); 544} 545 546 547SVal CXXConstructorCall::getCXXThisVal() const { 548 if (Data) 549 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 550 return UnknownVal(); 551} 552 553void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const { 554 if (Data) 555 Regions.push_back(static_cast<const MemRegion *>(Data)); 556} 557 558void CXXConstructorCall::getInitialStackFrameContents( 559 const StackFrameContext *CalleeCtx, 560 BindingsTy &Bindings) const { 561 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 562 563 SVal ThisVal = getCXXThisVal(); 564 if (!ThisVal.isUnknown()) { 565 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 566 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 567 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 568 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 569 } 570} 571 572 573 574SVal CXXDestructorCall::getCXXThisVal() const { 575 if (Data) 576 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 577 return UnknownVal(); 578} 579 580RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 581 // Base destructors are always called non-virtually. 582 // Skip CXXInstanceCall's devirtualization logic in this case. 583 if (isBaseDestructor()) 584 return AnyFunctionCall::getRuntimeDefinition(); 585 586 return CXXInstanceCall::getRuntimeDefinition(); 587} 588 589 590CallEvent::param_iterator ObjCMethodCall::param_begin() const { 591 const ObjCMethodDecl *D = getDecl(); 592 if (!D) 593 return 0; 594 595 return D->param_begin(); 596} 597 598CallEvent::param_iterator ObjCMethodCall::param_end() const { 599 const ObjCMethodDecl *D = getDecl(); 600 if (!D) 601 return 0; 602 603 return D->param_end(); 604} 605 606void 607ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const { 608 if (const MemRegion *R = getReceiverSVal().getAsRegion()) 609 Regions.push_back(R); 610} 611 612SVal ObjCMethodCall::getSelfSVal() const { 613 const LocationContext *LCtx = getLocationContext(); 614 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 615 if (!SelfDecl) 616 return SVal(); 617 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 618} 619 620SVal ObjCMethodCall::getReceiverSVal() const { 621 // FIXME: Is this the best way to handle class receivers? 622 if (!isInstanceMessage()) 623 return UnknownVal(); 624 625 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 626 return getSVal(RecE); 627 628 // An instance message with no expression means we are sending to super. 629 // In this case the object reference is the same as 'self'. 630 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 631 SVal SelfVal = getSelfSVal(); 632 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 633 return SelfVal; 634} 635 636bool ObjCMethodCall::isReceiverSelfOrSuper() const { 637 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 638 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 639 return true; 640 641 if (!isInstanceMessage()) 642 return false; 643 644 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 645 646 return (RecVal == getSelfSVal()); 647} 648 649SourceRange ObjCMethodCall::getSourceRange() const { 650 switch (getMessageKind()) { 651 case OCM_Message: 652 return getOriginExpr()->getSourceRange(); 653 case OCM_PropertyAccess: 654 case OCM_Subscript: 655 return getContainingPseudoObjectExpr()->getSourceRange(); 656 } 657 llvm_unreachable("unknown message kind"); 658} 659 660typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy; 661 662const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 663 assert(Data != 0 && "Lazy lookup not yet performed."); 664 assert(getMessageKind() != OCM_Message && "Explicit message send."); 665 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 666} 667 668ObjCMessageKind ObjCMethodCall::getMessageKind() const { 669 if (Data == 0) { 670 ParentMap &PM = getLocationContext()->getParentMap(); 671 const Stmt *S = PM.getParent(getOriginExpr()); 672 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 673 const Expr *Syntactic = POE->getSyntacticForm(); 674 675 // This handles the funny case of assigning to the result of a getter. 676 // This can happen if the getter returns a non-const reference. 677 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic)) 678 Syntactic = BO->getLHS(); 679 680 ObjCMessageKind K; 681 switch (Syntactic->getStmtClass()) { 682 case Stmt::ObjCPropertyRefExprClass: 683 K = OCM_PropertyAccess; 684 break; 685 case Stmt::ObjCSubscriptRefExprClass: 686 K = OCM_Subscript; 687 break; 688 default: 689 // FIXME: Can this ever happen? 690 K = OCM_Message; 691 break; 692 } 693 694 if (K != OCM_Message) { 695 const_cast<ObjCMethodCall *>(this)->Data 696 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 697 assert(getMessageKind() == K); 698 return K; 699 } 700 } 701 702 const_cast<ObjCMethodCall *>(this)->Data 703 = ObjCMessageDataTy(0, 1).getOpaqueValue(); 704 assert(getMessageKind() == OCM_Message); 705 return OCM_Message; 706 } 707 708 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 709 if (!Info.getPointer()) 710 return OCM_Message; 711 return static_cast<ObjCMessageKind>(Info.getInt()); 712} 713 714 715bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 716 Selector Sel) const { 717 assert(IDecl); 718 const SourceManager &SM = 719 getState()->getStateManager().getContext().getSourceManager(); 720 721 // If the class interface is declared inside the main file, assume it is not 722 // subcassed. 723 // TODO: It could actually be subclassed if the subclass is private as well. 724 // This is probably very rare. 725 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 726 if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc)) 727 return false; 728 729 // Assume that property accessors are not overridden. 730 if (getMessageKind() == OCM_PropertyAccess) 731 return false; 732 733 // We assume that if the method is public (declared outside of main file) or 734 // has a parent which publicly declares the method, the method could be 735 // overridden in a subclass. 736 737 // Find the first declaration in the class hierarchy that declares 738 // the selector. 739 ObjCMethodDecl *D = 0; 740 while (true) { 741 D = IDecl->lookupMethod(Sel, true); 742 743 // Cannot find a public definition. 744 if (!D) 745 return false; 746 747 // If outside the main file, 748 if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation())) 749 return true; 750 751 if (D->isOverriding()) { 752 // Search in the superclass on the next iteration. 753 IDecl = D->getClassInterface(); 754 if (!IDecl) 755 return false; 756 757 IDecl = IDecl->getSuperClass(); 758 if (!IDecl) 759 return false; 760 761 continue; 762 } 763 764 return false; 765 }; 766 767 llvm_unreachable("The while loop should always terminate."); 768} 769 770RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 771 const ObjCMessageExpr *E = getOriginExpr(); 772 assert(E); 773 Selector Sel = E->getSelector(); 774 775 if (E->isInstanceMessage()) { 776 777 // Find the the receiver type. 778 const ObjCObjectPointerType *ReceiverT = 0; 779 bool CanBeSubClassed = false; 780 QualType SupersType = E->getSuperType(); 781 const MemRegion *Receiver = 0; 782 783 if (!SupersType.isNull()) { 784 // Super always means the type of immediate predecessor to the method 785 // where the call occurs. 786 ReceiverT = cast<ObjCObjectPointerType>(SupersType); 787 } else { 788 Receiver = getReceiverSVal().getAsRegion(); 789 if (!Receiver) 790 return RuntimeDefinition(); 791 792 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver); 793 QualType DynType = DTI.getType(); 794 CanBeSubClassed = DTI.canBeASubClass(); 795 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType); 796 797 if (ReceiverT && CanBeSubClassed) 798 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 799 if (!canBeOverridenInSubclass(IDecl, Sel)) 800 CanBeSubClassed = false; 801 } 802 803 // Lookup the method implementation. 804 if (ReceiverT) 805 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 806 // Repeatedly calling lookupPrivateMethod() is expensive, especially 807 // when in many cases it returns null. We cache the results so 808 // that repeated queries on the same ObjCIntefaceDecl and Selector 809 // don't incur the same cost. On some test cases, we can see the 810 // same query being issued thousands of times. 811 // 812 // NOTE: This cache is essentially a "global" variable, but it 813 // only gets lazily created when we get here. The value of the 814 // cache probably comes from it being global across ExprEngines, 815 // where the same queries may get issued. If we are worried about 816 // concurrency, or possibly loading/unloading ASTs, etc., we may 817 // need to revisit this someday. In terms of memory, this table 818 // stays around until clang quits, which also may be bad if we 819 // need to release memory. 820 typedef std::pair<const ObjCInterfaceDecl*, Selector> 821 PrivateMethodKey; 822 typedef llvm::DenseMap<PrivateMethodKey, 823 Optional<const ObjCMethodDecl *> > 824 PrivateMethodCache; 825 826 static PrivateMethodCache PMC; 827 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)]; 828 829 // Query lookupPrivateMethod() if the cache does not hit. 830 if (!Val.hasValue()) 831 Val = IDecl->lookupPrivateMethod(Sel); 832 833 const ObjCMethodDecl *MD = Val.getValue(); 834 if (CanBeSubClassed) 835 return RuntimeDefinition(MD, Receiver); 836 else 837 return RuntimeDefinition(MD, 0); 838 } 839 840 } else { 841 // This is a class method. 842 // If we have type info for the receiver class, we are calling via 843 // class name. 844 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 845 // Find/Return the method implementation. 846 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 847 } 848 } 849 850 return RuntimeDefinition(); 851} 852 853void ObjCMethodCall::getInitialStackFrameContents( 854 const StackFrameContext *CalleeCtx, 855 BindingsTy &Bindings) const { 856 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 857 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 858 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 859 D->param_begin(), D->param_end()); 860 861 SVal SelfVal = getReceiverSVal(); 862 if (!SelfVal.isUnknown()) { 863 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 864 MemRegionManager &MRMgr = SVB.getRegionManager(); 865 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 866 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 867 } 868} 869 870CallEventRef<> 871CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 872 const LocationContext *LCtx) { 873 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 874 return create<CXXMemberCall>(MCE, State, LCtx); 875 876 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 877 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 878 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 879 if (MD->isInstance()) 880 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 881 882 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 883 return create<BlockCall>(CE, State, LCtx); 884 } 885 886 // Otherwise, it's a normal function call, static member function call, or 887 // something we can't reason about. 888 return create<FunctionCall>(CE, State, LCtx); 889} 890 891 892CallEventRef<> 893CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 894 ProgramStateRef State) { 895 const LocationContext *ParentCtx = CalleeCtx->getParent(); 896 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 897 assert(CallerCtx && "This should not be used for top-level stack frames"); 898 899 const Stmt *CallSite = CalleeCtx->getCallSite(); 900 901 if (CallSite) { 902 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 903 return getSimpleCall(CE, State, CallerCtx); 904 905 switch (CallSite->getStmtClass()) { 906 case Stmt::CXXConstructExprClass: 907 case Stmt::CXXTemporaryObjectExprClass: { 908 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 909 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 910 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 911 SVal ThisVal = State->getSVal(ThisPtr); 912 913 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 914 ThisVal.getAsRegion(), State, CallerCtx); 915 } 916 case Stmt::CXXNewExprClass: 917 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 918 case Stmt::ObjCMessageExprClass: 919 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 920 State, CallerCtx); 921 default: 922 llvm_unreachable("This is not an inlineable statement."); 923 } 924 } 925 926 // Fall back to the CFG. The only thing we haven't handled yet is 927 // destructors, though this could change in the future. 928 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 929 CFGElement E = (*B)[CalleeCtx->getIndex()]; 930 assert(E.getAs<CFGImplicitDtor>() && 931 "All other CFG elements should have exprs"); 932 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet"); 933 934 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 935 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 936 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 937 SVal ThisVal = State->getSVal(ThisPtr); 938 939 const Stmt *Trigger; 940 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 941 Trigger = AutoDtor->getTriggerStmt(); 942 else 943 Trigger = Dtor->getBody(); 944 945 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 946 E.getAs<CFGBaseDtor>().hasValue(), State, 947 CallerCtx); 948} 949