CallEvent.cpp revision 6ebea89be233eaba5e29de8cf3524ad150c860bb
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 assert(Result && "At the very least the static decl should show up."); 439 440 // Does the decl that we found have an implementation? 441 const FunctionDecl *Definition; 442 if (!Result->hasBody(Definition)) 443 return RuntimeDefinition(); 444 445 // We found a definition. If we're not sure that this devirtualization is 446 // actually what will happen at runtime, make sure to provide the region so 447 // that ExprEngine can decide what to do with it. 448 if (DynType.canBeASubClass()) 449 return RuntimeDefinition(Definition, R->StripCasts()); 450 return RuntimeDefinition(Definition, /*DispatchRegion=*/0); 451} 452 453void CXXInstanceCall::getInitialStackFrameContents( 454 const StackFrameContext *CalleeCtx, 455 BindingsTy &Bindings) const { 456 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 457 458 // Handle the binding of 'this' in the new stack frame. 459 SVal ThisVal = getCXXThisVal(); 460 if (!ThisVal.isUnknown()) { 461 ProgramStateManager &StateMgr = getState()->getStateManager(); 462 SValBuilder &SVB = StateMgr.getSValBuilder(); 463 464 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 465 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 466 467 // If we devirtualized to a different member function, we need to make sure 468 // we have the proper layering of CXXBaseObjectRegions. 469 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 470 ASTContext &Ctx = SVB.getContext(); 471 const CXXRecordDecl *Class = MD->getParent(); 472 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 473 474 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 475 bool Failed; 476 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed); 477 assert(!Failed && "Calling an incorrectly devirtualized method"); 478 } 479 480 if (!ThisVal.isUnknown()) 481 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 482 } 483} 484 485 486 487const Expr *CXXMemberCall::getCXXThisExpr() const { 488 return getOriginExpr()->getImplicitObjectArgument(); 489} 490 491 492const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 493 return getOriginExpr()->getArg(0); 494} 495 496 497const BlockDataRegion *BlockCall::getBlockRegion() const { 498 const Expr *Callee = getOriginExpr()->getCallee(); 499 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 500 501 return dyn_cast_or_null<BlockDataRegion>(DataReg); 502} 503 504CallEvent::param_iterator BlockCall::param_begin() const { 505 const BlockDecl *D = getBlockDecl(); 506 if (!D) 507 return 0; 508 return D->param_begin(); 509} 510 511CallEvent::param_iterator BlockCall::param_end() const { 512 const BlockDecl *D = getBlockDecl(); 513 if (!D) 514 return 0; 515 return D->param_end(); 516} 517 518void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const { 519 // FIXME: This also needs to invalidate captured globals. 520 if (const MemRegion *R = getBlockRegion()) 521 Regions.push_back(R); 522} 523 524void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 525 BindingsTy &Bindings) const { 526 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl()); 527 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 528 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 529 D->param_begin(), D->param_end()); 530} 531 532 533SVal CXXConstructorCall::getCXXThisVal() const { 534 if (Data) 535 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 536 return UnknownVal(); 537} 538 539void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const { 540 if (Data) 541 Regions.push_back(static_cast<const MemRegion *>(Data)); 542} 543 544void CXXConstructorCall::getInitialStackFrameContents( 545 const StackFrameContext *CalleeCtx, 546 BindingsTy &Bindings) const { 547 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 548 549 SVal ThisVal = getCXXThisVal(); 550 if (!ThisVal.isUnknown()) { 551 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 552 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 553 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 554 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 555 } 556} 557 558 559 560SVal CXXDestructorCall::getCXXThisVal() const { 561 if (Data) 562 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 563 return UnknownVal(); 564} 565 566 567CallEvent::param_iterator ObjCMethodCall::param_begin() const { 568 const ObjCMethodDecl *D = getDecl(); 569 if (!D) 570 return 0; 571 572 return D->param_begin(); 573} 574 575CallEvent::param_iterator ObjCMethodCall::param_end() const { 576 const ObjCMethodDecl *D = getDecl(); 577 if (!D) 578 return 0; 579 580 return D->param_end(); 581} 582 583void 584ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const { 585 if (const MemRegion *R = getReceiverSVal().getAsRegion()) 586 Regions.push_back(R); 587} 588 589SVal ObjCMethodCall::getSelfSVal() const { 590 const LocationContext *LCtx = getLocationContext(); 591 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 592 if (!SelfDecl) 593 return SVal(); 594 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 595} 596 597SVal ObjCMethodCall::getReceiverSVal() const { 598 // FIXME: Is this the best way to handle class receivers? 599 if (!isInstanceMessage()) 600 return UnknownVal(); 601 602 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 603 return getSVal(RecE); 604 605 // An instance message with no expression means we are sending to super. 606 // In this case the object reference is the same as 'self'. 607 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 608 SVal SelfVal = getSelfSVal(); 609 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 610 return SelfVal; 611} 612 613bool ObjCMethodCall::isReceiverSelfOrSuper() const { 614 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 615 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 616 return true; 617 618 if (!isInstanceMessage()) 619 return false; 620 621 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 622 623 return (RecVal == getSelfSVal()); 624} 625 626SourceRange ObjCMethodCall::getSourceRange() const { 627 switch (getMessageKind()) { 628 case OCM_Message: 629 return getOriginExpr()->getSourceRange(); 630 case OCM_PropertyAccess: 631 case OCM_Subscript: 632 return getContainingPseudoObjectExpr()->getSourceRange(); 633 } 634 llvm_unreachable("unknown message kind"); 635} 636 637typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy; 638 639const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 640 assert(Data != 0 && "Lazy lookup not yet performed."); 641 assert(getMessageKind() != OCM_Message && "Explicit message send."); 642 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 643} 644 645ObjCMessageKind ObjCMethodCall::getMessageKind() const { 646 if (Data == 0) { 647 ParentMap &PM = getLocationContext()->getParentMap(); 648 const Stmt *S = PM.getParent(getOriginExpr()); 649 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 650 const Expr *Syntactic = POE->getSyntacticForm(); 651 652 // This handles the funny case of assigning to the result of a getter. 653 // This can happen if the getter returns a non-const reference. 654 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic)) 655 Syntactic = BO->getLHS(); 656 657 ObjCMessageKind K; 658 switch (Syntactic->getStmtClass()) { 659 case Stmt::ObjCPropertyRefExprClass: 660 K = OCM_PropertyAccess; 661 break; 662 case Stmt::ObjCSubscriptRefExprClass: 663 K = OCM_Subscript; 664 break; 665 default: 666 // FIXME: Can this ever happen? 667 K = OCM_Message; 668 break; 669 } 670 671 if (K != OCM_Message) { 672 const_cast<ObjCMethodCall *>(this)->Data 673 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 674 assert(getMessageKind() == K); 675 return K; 676 } 677 } 678 679 const_cast<ObjCMethodCall *>(this)->Data 680 = ObjCMessageDataTy(0, 1).getOpaqueValue(); 681 assert(getMessageKind() == OCM_Message); 682 return OCM_Message; 683 } 684 685 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 686 if (!Info.getPointer()) 687 return OCM_Message; 688 return static_cast<ObjCMessageKind>(Info.getInt()); 689} 690 691 692bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 693 Selector Sel) const { 694 assert(IDecl); 695 const SourceManager &SM = 696 getState()->getStateManager().getContext().getSourceManager(); 697 698 // If the class interface is declared inside the main file, assume it is not 699 // subcassed. 700 // TODO: It could actually be subclassed if the subclass is private as well. 701 // This is probably very rare. 702 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 703 if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc)) 704 return false; 705 706 // Assume that property accessors are not overridden. 707 if (getMessageKind() == OCM_PropertyAccess) 708 return false; 709 710 // We assume that if the method is public (declared outside of main file) or 711 // has a parent which publicly declares the method, the method could be 712 // overridden in a subclass. 713 714 // Find the first declaration in the class hierarchy that declares 715 // the selector. 716 ObjCMethodDecl *D = 0; 717 while (true) { 718 D = IDecl->lookupMethod(Sel, true); 719 720 // Cannot find a public definition. 721 if (!D) 722 return false; 723 724 // If outside the main file, 725 if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation())) 726 return true; 727 728 if (D->isOverriding()) { 729 // Search in the superclass on the next iteration. 730 IDecl = D->getClassInterface(); 731 if (!IDecl) 732 return false; 733 734 IDecl = IDecl->getSuperClass(); 735 if (!IDecl) 736 return false; 737 738 continue; 739 } 740 741 return false; 742 }; 743 744 llvm_unreachable("The while loop should always terminate."); 745} 746 747RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 748 const ObjCMessageExpr *E = getOriginExpr(); 749 assert(E); 750 Selector Sel = E->getSelector(); 751 752 if (E->isInstanceMessage()) { 753 754 // Find the the receiver type. 755 const ObjCObjectPointerType *ReceiverT = 0; 756 bool CanBeSubClassed = false; 757 QualType SupersType = E->getSuperType(); 758 const MemRegion *Receiver = 0; 759 760 if (!SupersType.isNull()) { 761 // Super always means the type of immediate predecessor to the method 762 // where the call occurs. 763 ReceiverT = cast<ObjCObjectPointerType>(SupersType); 764 } else { 765 Receiver = getReceiverSVal().getAsRegion(); 766 if (!Receiver) 767 return RuntimeDefinition(); 768 769 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver); 770 QualType DynType = DTI.getType(); 771 CanBeSubClassed = DTI.canBeASubClass(); 772 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType); 773 774 if (ReceiverT && CanBeSubClassed) 775 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 776 if (!canBeOverridenInSubclass(IDecl, Sel)) 777 CanBeSubClassed = false; 778 } 779 780 // Lookup the method implementation. 781 if (ReceiverT) 782 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 783 const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel); 784 if (CanBeSubClassed) 785 return RuntimeDefinition(MD, Receiver); 786 else 787 return RuntimeDefinition(MD, 0); 788 } 789 790 } else { 791 // This is a class method. 792 // If we have type info for the receiver class, we are calling via 793 // class name. 794 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 795 // Find/Return the method implementation. 796 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 797 } 798 } 799 800 return RuntimeDefinition(); 801} 802 803void ObjCMethodCall::getInitialStackFrameContents( 804 const StackFrameContext *CalleeCtx, 805 BindingsTy &Bindings) const { 806 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 807 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 808 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 809 D->param_begin(), D->param_end()); 810 811 SVal SelfVal = getReceiverSVal(); 812 if (!SelfVal.isUnknown()) { 813 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 814 MemRegionManager &MRMgr = SVB.getRegionManager(); 815 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 816 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 817 } 818} 819 820CallEventRef<> 821CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 822 const LocationContext *LCtx) { 823 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 824 return create<CXXMemberCall>(MCE, State, LCtx); 825 826 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 827 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 828 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 829 if (MD->isInstance()) 830 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 831 832 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 833 return create<BlockCall>(CE, State, LCtx); 834 } 835 836 // Otherwise, it's a normal function call, static member function call, or 837 // something we can't reason about. 838 return create<FunctionCall>(CE, State, LCtx); 839} 840 841 842CallEventRef<> 843CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 844 ProgramStateRef State) { 845 const LocationContext *ParentCtx = CalleeCtx->getParent(); 846 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 847 assert(CallerCtx && "This should not be used for top-level stack frames"); 848 849 const Stmt *CallSite = CalleeCtx->getCallSite(); 850 851 if (CallSite) { 852 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 853 return getSimpleCall(CE, State, CallerCtx); 854 855 switch (CallSite->getStmtClass()) { 856 case Stmt::CXXConstructExprClass: 857 case Stmt::CXXTemporaryObjectExprClass: { 858 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 859 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 860 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 861 SVal ThisVal = State->getSVal(ThisPtr); 862 863 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 864 ThisVal.getAsRegion(), State, CallerCtx); 865 } 866 case Stmt::CXXNewExprClass: 867 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 868 case Stmt::ObjCMessageExprClass: 869 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 870 State, CallerCtx); 871 default: 872 llvm_unreachable("This is not an inlineable statement."); 873 } 874 } 875 876 // Fall back to the CFG. The only thing we haven't handled yet is 877 // destructors, though this could change in the future. 878 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 879 CFGElement E = (*B)[CalleeCtx->getIndex()]; 880 assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs"); 881 assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet"); 882 883 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 884 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 885 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 886 SVal ThisVal = State->getSVal(ThisPtr); 887 888 const Stmt *Trigger; 889 if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E)) 890 Trigger = AutoDtor->getTriggerStmt(); 891 else 892 Trigger = Dtor->getBody(); 893 894 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 895 State, CallerCtx); 896} 897