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