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