CallEvent.cpp revision 00b4f64ecb26b031c1f4888f39be6c706156356a
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 255static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 256 CallEvent::BindingsTy &Bindings, 257 SValBuilder &SVB, 258 const CallEvent &Call, 259 CallEvent::param_iterator I, 260 CallEvent::param_iterator E) { 261 MemRegionManager &MRMgr = SVB.getRegionManager(); 262 263 unsigned Idx = 0; 264 for (; I != E; ++I, ++Idx) { 265 const ParmVarDecl *ParamDecl = *I; 266 assert(ParamDecl && "Formal parameter has no decl?"); 267 268 SVal ArgVal = Call.getArgSVal(Idx); 269 if (!ArgVal.isUnknown()) { 270 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx)); 271 Bindings.push_back(std::make_pair(ParamLoc, ArgVal)); 272 } 273 } 274 275 // FIXME: Variadic arguments are not handled at all right now. 276} 277 278 279CallEvent::param_iterator AnyFunctionCall::param_begin() const { 280 const FunctionDecl *D = getDecl(); 281 if (!D) 282 return 0; 283 284 return D->param_begin(); 285} 286 287CallEvent::param_iterator AnyFunctionCall::param_end() const { 288 const FunctionDecl *D = getDecl(); 289 if (!D) 290 return 0; 291 292 return D->param_end(); 293} 294 295void AnyFunctionCall::getInitialStackFrameContents( 296 const StackFrameContext *CalleeCtx, 297 BindingsTy &Bindings) const { 298 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 299 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 300 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 301 D->param_begin(), D->param_end()); 302} 303 304bool AnyFunctionCall::argumentsMayEscape() const { 305 if (hasNonZeroCallbackArg()) 306 return true; 307 308 const FunctionDecl *D = getDecl(); 309 if (!D) 310 return true; 311 312 const IdentifierInfo *II = D->getIdentifier(); 313 if (!II) 314 return true; 315 316 // This set of "escaping" APIs is 317 318 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 319 // value into thread local storage. The value can later be retrieved with 320 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 321 // parameter is 'const void *', the region escapes through the call. 322 if (II->isStr("pthread_setspecific")) 323 return true; 324 325 // - xpc_connection_set_context stores a value which can be retrieved later 326 // with xpc_connection_get_context. 327 if (II->isStr("xpc_connection_set_context")) 328 return true; 329 330 // - funopen - sets a buffer for future IO calls. 331 if (II->isStr("funopen")) 332 return true; 333 334 StringRef FName = II->getName(); 335 336 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 337 // buffer even if it is const. 338 if (FName.endswith("NoCopy")) 339 return true; 340 341 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 342 // be deallocated by NSMapRemove. 343 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 344 return true; 345 346 // - Many CF containers allow objects to escape through custom 347 // allocators/deallocators upon container construction. (PR12101) 348 if (FName.startswith("CF") || FName.startswith("CG")) { 349 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 350 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 351 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 352 StrInStrNoCase(FName, "WithData") != StringRef::npos || 353 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 354 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 355 } 356 357 return false; 358} 359 360 361const FunctionDecl *SimpleCall::getDecl() const { 362 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 363 if (D) 364 return D; 365 366 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 367} 368 369 370const FunctionDecl *CXXInstanceCall::getDecl() const { 371 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr()); 372 if (!CE) 373 return AnyFunctionCall::getDecl(); 374 375 const FunctionDecl *D = CE->getDirectCallee(); 376 if (D) 377 return D; 378 379 return getSVal(CE->getCallee()).getAsFunctionDecl(); 380} 381 382void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const { 383 if (const MemRegion *R = getCXXThisVal().getAsRegion()) 384 Regions.push_back(R); 385} 386 387SVal CXXInstanceCall::getCXXThisVal() const { 388 const Expr *Base = getCXXThisExpr(); 389 // FIXME: This doesn't handle an overloaded ->* operator. 390 if (!Base) 391 return UnknownVal(); 392 393 SVal ThisVal = getSVal(Base); 394 395 // FIXME: This is only necessary because we can call member functions on 396 // struct rvalues, which do not have regions we can use for a 'this' pointer. 397 // Ideally this should eventually be changed to an assert, i.e. all 398 // non-Unknown, non-null 'this' values should be loc::MemRegionVals. 399 if (isa<DefinedSVal>(ThisVal)) 400 if (!ThisVal.getAsRegion() && !ThisVal.isConstant()) 401 return UnknownVal(); 402 403 return ThisVal; 404} 405 406 407RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 408 // Do we have a decl at all? 409 const Decl *D = getDecl(); 410 if (!D) 411 return RuntimeDefinition(); 412 413 // If the method is non-virtual, we know we can inline it. 414 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 415 if (!MD->isVirtual()) 416 return AnyFunctionCall::getRuntimeDefinition(); 417 418 // Do we know the implicit 'this' object being called? 419 const MemRegion *R = getCXXThisVal().getAsRegion(); 420 if (!R) 421 return RuntimeDefinition(); 422 423 // Do we know anything about the type of 'this'? 424 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R); 425 if (!DynType.isValid()) 426 return RuntimeDefinition(); 427 428 // Is the type a C++ class? (This is mostly a defensive check.) 429 QualType RegionType = DynType.getType()->getPointeeType(); 430 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 431 432 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 433 if (!RD || !RD->hasDefinition()) 434 return RuntimeDefinition(); 435 436 // Find the decl for this method in that class. 437 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 438 if (!Result) { 439 // We might not even get the original statically-resolved method due to 440 // some particularly nasty casting (e.g. casts to sister classes). 441 // However, we should at least be able to search up and down our own class 442 // hierarchy, and some real bugs have been caught by checking this. 443 assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 444 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 445 return RuntimeDefinition(); 446 } 447 448 // Does the decl that we found have an implementation? 449 const FunctionDecl *Definition; 450 if (!Result->hasBody(Definition)) 451 return RuntimeDefinition(); 452 453 // We found a definition. If we're not sure that this devirtualization is 454 // actually what will happen at runtime, make sure to provide the region so 455 // that ExprEngine can decide what to do with it. 456 if (DynType.canBeASubClass()) 457 return RuntimeDefinition(Definition, R->StripCasts()); 458 return RuntimeDefinition(Definition, /*DispatchRegion=*/0); 459} 460 461void CXXInstanceCall::getInitialStackFrameContents( 462 const StackFrameContext *CalleeCtx, 463 BindingsTy &Bindings) const { 464 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 465 466 // Handle the binding of 'this' in the new stack frame. 467 SVal ThisVal = getCXXThisVal(); 468 if (!ThisVal.isUnknown()) { 469 ProgramStateManager &StateMgr = getState()->getStateManager(); 470 SValBuilder &SVB = StateMgr.getSValBuilder(); 471 472 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 473 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 474 475 // If we devirtualized to a different member function, we need to make sure 476 // we have the proper layering of CXXBaseObjectRegions. 477 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 478 ASTContext &Ctx = SVB.getContext(); 479 const CXXRecordDecl *Class = MD->getParent(); 480 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 481 482 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 483 bool Failed; 484 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed); 485 assert(!Failed && "Calling an incorrectly devirtualized method"); 486 } 487 488 if (!ThisVal.isUnknown()) 489 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 490 } 491} 492 493 494 495const Expr *CXXMemberCall::getCXXThisExpr() const { 496 return getOriginExpr()->getImplicitObjectArgument(); 497} 498 499RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 500 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 501 // id-expression in the class member access expression is a qualified-id, 502 // that function is called. Otherwise, its final overrider in the dynamic type 503 // of the object expression is called. 504 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 505 if (ME->hasQualifier()) 506 return AnyFunctionCall::getRuntimeDefinition(); 507 508 return CXXInstanceCall::getRuntimeDefinition(); 509} 510 511 512const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 513 return getOriginExpr()->getArg(0); 514} 515 516 517const BlockDataRegion *BlockCall::getBlockRegion() const { 518 const Expr *Callee = getOriginExpr()->getCallee(); 519 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 520 521 return dyn_cast_or_null<BlockDataRegion>(DataReg); 522} 523 524CallEvent::param_iterator BlockCall::param_begin() const { 525 const BlockDecl *D = getBlockDecl(); 526 if (!D) 527 return 0; 528 return D->param_begin(); 529} 530 531CallEvent::param_iterator BlockCall::param_end() const { 532 const BlockDecl *D = getBlockDecl(); 533 if (!D) 534 return 0; 535 return D->param_end(); 536} 537 538void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const { 539 // FIXME: This also needs to invalidate captured globals. 540 if (const MemRegion *R = getBlockRegion()) 541 Regions.push_back(R); 542} 543 544void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 545 BindingsTy &Bindings) const { 546 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl()); 547 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 548 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 549 D->param_begin(), D->param_end()); 550} 551 552 553SVal CXXConstructorCall::getCXXThisVal() const { 554 if (Data) 555 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 556 return UnknownVal(); 557} 558 559void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const { 560 if (Data) 561 Regions.push_back(static_cast<const MemRegion *>(Data)); 562} 563 564void CXXConstructorCall::getInitialStackFrameContents( 565 const StackFrameContext *CalleeCtx, 566 BindingsTy &Bindings) const { 567 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 568 569 SVal ThisVal = getCXXThisVal(); 570 if (!ThisVal.isUnknown()) { 571 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 572 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 573 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 574 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 575 } 576} 577 578 579 580SVal CXXDestructorCall::getCXXThisVal() const { 581 if (Data) 582 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 583 return UnknownVal(); 584} 585 586RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 587 // Base destructors are always called non-virtually. 588 // Skip CXXInstanceCall's devirtualization logic in this case. 589 if (isBaseDestructor()) 590 return AnyFunctionCall::getRuntimeDefinition(); 591 592 return CXXInstanceCall::getRuntimeDefinition(); 593} 594 595 596CallEvent::param_iterator ObjCMethodCall::param_begin() const { 597 const ObjCMethodDecl *D = getDecl(); 598 if (!D) 599 return 0; 600 601 return D->param_begin(); 602} 603 604CallEvent::param_iterator ObjCMethodCall::param_end() const { 605 const ObjCMethodDecl *D = getDecl(); 606 if (!D) 607 return 0; 608 609 return D->param_end(); 610} 611 612void 613ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const { 614 if (const MemRegion *R = getReceiverSVal().getAsRegion()) 615 Regions.push_back(R); 616} 617 618SVal ObjCMethodCall::getSelfSVal() const { 619 const LocationContext *LCtx = getLocationContext(); 620 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 621 if (!SelfDecl) 622 return SVal(); 623 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 624} 625 626SVal ObjCMethodCall::getReceiverSVal() const { 627 // FIXME: Is this the best way to handle class receivers? 628 if (!isInstanceMessage()) 629 return UnknownVal(); 630 631 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 632 return getSVal(RecE); 633 634 // An instance message with no expression means we are sending to super. 635 // In this case the object reference is the same as 'self'. 636 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 637 SVal SelfVal = getSelfSVal(); 638 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 639 return SelfVal; 640} 641 642bool ObjCMethodCall::isReceiverSelfOrSuper() const { 643 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 644 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 645 return true; 646 647 if (!isInstanceMessage()) 648 return false; 649 650 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 651 652 return (RecVal == getSelfSVal()); 653} 654 655SourceRange ObjCMethodCall::getSourceRange() const { 656 switch (getMessageKind()) { 657 case OCM_Message: 658 return getOriginExpr()->getSourceRange(); 659 case OCM_PropertyAccess: 660 case OCM_Subscript: 661 return getContainingPseudoObjectExpr()->getSourceRange(); 662 } 663 llvm_unreachable("unknown message kind"); 664} 665 666typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy; 667 668const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 669 assert(Data != 0 && "Lazy lookup not yet performed."); 670 assert(getMessageKind() != OCM_Message && "Explicit message send."); 671 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 672} 673 674ObjCMessageKind ObjCMethodCall::getMessageKind() const { 675 if (Data == 0) { 676 ParentMap &PM = getLocationContext()->getParentMap(); 677 const Stmt *S = PM.getParent(getOriginExpr()); 678 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 679 const Expr *Syntactic = POE->getSyntacticForm(); 680 681 // This handles the funny case of assigning to the result of a getter. 682 // This can happen if the getter returns a non-const reference. 683 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic)) 684 Syntactic = BO->getLHS(); 685 686 ObjCMessageKind K; 687 switch (Syntactic->getStmtClass()) { 688 case Stmt::ObjCPropertyRefExprClass: 689 K = OCM_PropertyAccess; 690 break; 691 case Stmt::ObjCSubscriptRefExprClass: 692 K = OCM_Subscript; 693 break; 694 default: 695 // FIXME: Can this ever happen? 696 K = OCM_Message; 697 break; 698 } 699 700 if (K != OCM_Message) { 701 const_cast<ObjCMethodCall *>(this)->Data 702 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 703 assert(getMessageKind() == K); 704 return K; 705 } 706 } 707 708 const_cast<ObjCMethodCall *>(this)->Data 709 = ObjCMessageDataTy(0, 1).getOpaqueValue(); 710 assert(getMessageKind() == OCM_Message); 711 return OCM_Message; 712 } 713 714 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 715 if (!Info.getPointer()) 716 return OCM_Message; 717 return static_cast<ObjCMessageKind>(Info.getInt()); 718} 719 720 721bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 722 Selector Sel) const { 723 assert(IDecl); 724 const SourceManager &SM = 725 getState()->getStateManager().getContext().getSourceManager(); 726 727 // If the class interface is declared inside the main file, assume it is not 728 // subcassed. 729 // TODO: It could actually be subclassed if the subclass is private as well. 730 // This is probably very rare. 731 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 732 if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc)) 733 return false; 734 735 // Assume that property accessors are not overridden. 736 if (getMessageKind() == OCM_PropertyAccess) 737 return false; 738 739 // We assume that if the method is public (declared outside of main file) or 740 // has a parent which publicly declares the method, the method could be 741 // overridden in a subclass. 742 743 // Find the first declaration in the class hierarchy that declares 744 // the selector. 745 ObjCMethodDecl *D = 0; 746 while (true) { 747 D = IDecl->lookupMethod(Sel, true); 748 749 // Cannot find a public definition. 750 if (!D) 751 return false; 752 753 // If outside the main file, 754 if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation())) 755 return true; 756 757 if (D->isOverriding()) { 758 // Search in the superclass on the next iteration. 759 IDecl = D->getClassInterface(); 760 if (!IDecl) 761 return false; 762 763 IDecl = IDecl->getSuperClass(); 764 if (!IDecl) 765 return false; 766 767 continue; 768 } 769 770 return false; 771 }; 772 773 llvm_unreachable("The while loop should always terminate."); 774} 775 776RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 777 const ObjCMessageExpr *E = getOriginExpr(); 778 assert(E); 779 Selector Sel = E->getSelector(); 780 781 if (E->isInstanceMessage()) { 782 783 // Find the the receiver type. 784 const ObjCObjectPointerType *ReceiverT = 0; 785 bool CanBeSubClassed = false; 786 QualType SupersType = E->getSuperType(); 787 const MemRegion *Receiver = 0; 788 789 if (!SupersType.isNull()) { 790 // Super always means the type of immediate predecessor to the method 791 // where the call occurs. 792 ReceiverT = cast<ObjCObjectPointerType>(SupersType); 793 } else { 794 Receiver = getReceiverSVal().getAsRegion(); 795 if (!Receiver) 796 return RuntimeDefinition(); 797 798 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver); 799 QualType DynType = DTI.getType(); 800 CanBeSubClassed = DTI.canBeASubClass(); 801 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType); 802 803 if (ReceiverT && CanBeSubClassed) 804 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 805 if (!canBeOverridenInSubclass(IDecl, Sel)) 806 CanBeSubClassed = false; 807 } 808 809 // Lookup the method implementation. 810 if (ReceiverT) 811 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 812 const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel); 813 if (CanBeSubClassed) 814 return RuntimeDefinition(MD, Receiver); 815 else 816 return RuntimeDefinition(MD, 0); 817 } 818 819 } else { 820 // This is a class method. 821 // If we have type info for the receiver class, we are calling via 822 // class name. 823 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 824 // Find/Return the method implementation. 825 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 826 } 827 } 828 829 return RuntimeDefinition(); 830} 831 832void ObjCMethodCall::getInitialStackFrameContents( 833 const StackFrameContext *CalleeCtx, 834 BindingsTy &Bindings) const { 835 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 836 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 837 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 838 D->param_begin(), D->param_end()); 839 840 SVal SelfVal = getReceiverSVal(); 841 if (!SelfVal.isUnknown()) { 842 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 843 MemRegionManager &MRMgr = SVB.getRegionManager(); 844 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 845 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 846 } 847} 848 849CallEventRef<> 850CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 851 const LocationContext *LCtx) { 852 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 853 return create<CXXMemberCall>(MCE, State, LCtx); 854 855 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 856 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 857 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 858 if (MD->isInstance()) 859 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 860 861 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 862 return create<BlockCall>(CE, State, LCtx); 863 } 864 865 // Otherwise, it's a normal function call, static member function call, or 866 // something we can't reason about. 867 return create<FunctionCall>(CE, State, LCtx); 868} 869 870 871CallEventRef<> 872CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 873 ProgramStateRef State) { 874 const LocationContext *ParentCtx = CalleeCtx->getParent(); 875 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 876 assert(CallerCtx && "This should not be used for top-level stack frames"); 877 878 const Stmt *CallSite = CalleeCtx->getCallSite(); 879 880 if (CallSite) { 881 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 882 return getSimpleCall(CE, State, CallerCtx); 883 884 switch (CallSite->getStmtClass()) { 885 case Stmt::CXXConstructExprClass: 886 case Stmt::CXXTemporaryObjectExprClass: { 887 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 888 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 889 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 890 SVal ThisVal = State->getSVal(ThisPtr); 891 892 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 893 ThisVal.getAsRegion(), State, CallerCtx); 894 } 895 case Stmt::CXXNewExprClass: 896 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 897 case Stmt::ObjCMessageExprClass: 898 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 899 State, CallerCtx); 900 default: 901 llvm_unreachable("This is not an inlineable statement."); 902 } 903 } 904 905 // Fall back to the CFG. The only thing we haven't handled yet is 906 // destructors, though this could change in the future. 907 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 908 CFGElement E = (*B)[CalleeCtx->getIndex()]; 909 assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs"); 910 assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet"); 911 912 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 913 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 914 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 915 SVal ThisVal = State->getSVal(ThisPtr); 916 917 const Stmt *Trigger; 918 if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E)) 919 Trigger = AutoDtor->getTriggerStmt(); 920 else 921 Trigger = Dtor->getBody(); 922 923 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 924 isa<CFGBaseDtor>(E), State, CallerCtx); 925} 926