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