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