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/AST/ParentMap.h" 18 #include "clang/Analysis/ProgramPoint.h" 19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 20 #include "llvm/ADT/SmallSet.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/Support/raw_ostream.h" 23 24 using namespace clang; 25 using namespace ento; 26 27 QualType CallEvent::getResultType() const { 28 const Expr *E = getOriginExpr(); 29 assert(E && "Calls without origin expressions do not have results"); 30 QualType ResultTy = E->getType(); 31 32 ASTContext &Ctx = getState()->getStateManager().getContext(); 33 34 // A function that returns a reference to 'int' will have a result type 35 // of simply 'int'. Check the origin expr's value kind to recover the 36 // proper type. 37 switch (E->getValueKind()) { 38 case VK_LValue: 39 ResultTy = Ctx.getLValueReferenceType(ResultTy); 40 break; 41 case VK_XValue: 42 ResultTy = Ctx.getRValueReferenceType(ResultTy); 43 break; 44 case VK_RValue: 45 // No adjustment is necessary. 46 break; 47 } 48 49 return ResultTy; 50 } 51 52 static bool isCallbackArg(SVal V, QualType T) { 53 // If the parameter is 0, it's harmless. 54 if (V.isZeroConstant()) 55 return false; 56 57 // If a parameter is a block or a callback, assume it can modify pointer. 58 if (T->isBlockPointerType() || 59 T->isFunctionPointerType() || 60 T->isObjCSelType()) 61 return true; 62 63 // Check if a callback is passed inside a struct (for both, struct passed by 64 // reference and by value). Dig just one level into the struct for now. 65 66 if (T->isAnyPointerType() || T->isReferenceType()) 67 T = T->getPointeeType(); 68 69 if (const RecordType *RT = T->getAsStructureType()) { 70 const RecordDecl *RD = RT->getDecl(); 71 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 72 I != E; ++I) { 73 QualType FieldT = I->getType(); 74 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType()) 75 return true; 76 } 77 } 78 79 return false; 80 } 81 82 bool CallEvent::hasNonZeroCallbackArg() const { 83 unsigned NumOfArgs = getNumArgs(); 84 85 // If calling using a function pointer, assume the function does not 86 // have a callback. TODO: We could check the types of the arguments here. 87 if (!getDecl()) 88 return false; 89 90 unsigned Idx = 0; 91 for (CallEvent::param_type_iterator I = param_type_begin(), 92 E = param_type_end(); 93 I != E && Idx < NumOfArgs; ++I, ++Idx) { 94 if (NumOfArgs <= Idx) 95 break; 96 97 if (isCallbackArg(getArgSVal(Idx), *I)) 98 return true; 99 } 100 101 return false; 102 } 103 104 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { 105 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 106 if (!FD) 107 return false; 108 109 return CheckerContext::isCLibraryFunction(FD, FunctionName); 110 } 111 112 /// \brief Returns true if a type is a pointer-to-const or reference-to-const 113 /// with no further indirection. 114 static bool isPointerToConst(QualType Ty) { 115 QualType PointeeTy = Ty->getPointeeType(); 116 if (PointeeTy == QualType()) 117 return false; 118 if (!PointeeTy.isConstQualified()) 119 return false; 120 if (PointeeTy->isAnyPointerType()) 121 return false; 122 return true; 123 } 124 125 // Try to retrieve the function declaration and find the function parameter 126 // types which are pointers/references to a non-pointer const. 127 // We will not invalidate the corresponding argument regions. 128 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs, 129 const CallEvent &Call) { 130 unsigned Idx = 0; 131 for (CallEvent::param_type_iterator I = Call.param_type_begin(), 132 E = Call.param_type_end(); 133 I != E; ++I, ++Idx) { 134 if (isPointerToConst(*I)) 135 PreserveArgs.insert(Idx); 136 } 137 } 138 139 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount, 140 ProgramStateRef Orig) const { 141 ProgramStateRef Result = (Orig ? Orig : getState()); 142 143 SmallVector<SVal, 8> ValuesToInvalidate; 144 RegionAndSymbolInvalidationTraits ETraits; 145 146 getExtraInvalidatedValues(ValuesToInvalidate); 147 148 // Indexes of arguments whose values will be preserved by the call. 149 llvm::SmallSet<unsigned, 4> PreserveArgs; 150 if (!argumentsMayEscape()) 151 findPtrToConstParams(PreserveArgs, *this); 152 153 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) { 154 // Mark this region for invalidation. We batch invalidate regions 155 // below for efficiency. 156 if (PreserveArgs.count(Idx)) 157 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion()) 158 ETraits.setTrait(MR->StripCasts(), 159 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 160 // TODO: Factor this out + handle the lower level const pointers. 161 162 ValuesToInvalidate.push_back(getArgSVal(Idx)); 163 } 164 165 // Invalidate designated regions using the batch invalidation API. 166 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 167 // global variables. 168 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(), 169 BlockCount, getLocationContext(), 170 /*CausedByPointerEscape*/ true, 171 /*Symbols=*/0, this, &ETraits); 172 } 173 174 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit, 175 const ProgramPointTag *Tag) const { 176 if (const Expr *E = getOriginExpr()) { 177 if (IsPreVisit) 178 return PreStmt(E, getLocationContext(), Tag); 179 return PostStmt(E, getLocationContext(), Tag); 180 } 181 182 const Decl *D = getDecl(); 183 assert(D && "Cannot get a program point without a statement or decl"); 184 185 SourceLocation Loc = getSourceRange().getBegin(); 186 if (IsPreVisit) 187 return PreImplicitCall(D, Loc, getLocationContext(), Tag); 188 return PostImplicitCall(D, Loc, getLocationContext(), Tag); 189 } 190 191 SVal CallEvent::getArgSVal(unsigned Index) const { 192 const Expr *ArgE = getArgExpr(Index); 193 if (!ArgE) 194 return UnknownVal(); 195 return getSVal(ArgE); 196 } 197 198 SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 199 const Expr *ArgE = getArgExpr(Index); 200 if (!ArgE) 201 return SourceRange(); 202 return ArgE->getSourceRange(); 203 } 204 205 SVal CallEvent::getReturnValue() const { 206 const Expr *E = getOriginExpr(); 207 if (!E) 208 return UndefinedVal(); 209 return getSVal(E); 210 } 211 212 void CallEvent::dump() const { 213 dump(llvm::errs()); 214 } 215 216 void CallEvent::dump(raw_ostream &Out) const { 217 ASTContext &Ctx = getState()->getStateManager().getContext(); 218 if (const Expr *E = getOriginExpr()) { 219 E->printPretty(Out, 0, Ctx.getPrintingPolicy()); 220 Out << "\n"; 221 return; 222 } 223 224 if (const Decl *D = getDecl()) { 225 Out << "Call to "; 226 D->print(Out, Ctx.getPrintingPolicy()); 227 return; 228 } 229 230 // FIXME: a string representation of the kind would be nice. 231 Out << "Unknown call (type " << getKind() << ")"; 232 } 233 234 235 bool CallEvent::isCallStmt(const Stmt *S) { 236 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S) 237 || isa<CXXConstructExpr>(S) 238 || isa<CXXNewExpr>(S); 239 } 240 241 QualType CallEvent::getDeclaredResultType(const Decl *D) { 242 assert(D); 243 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(D)) 244 return FD->getResultType(); 245 if (const ObjCMethodDecl* MD = dyn_cast<ObjCMethodDecl>(D)) 246 return MD->getResultType(); 247 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 248 // Blocks are difficult because the return type may not be stored in the 249 // BlockDecl itself. The AST should probably be enhanced, but for now we 250 // just do what we can. 251 // If the block is declared without an explicit argument list, the 252 // signature-as-written just includes the return type, not the entire 253 // function type. 254 // FIXME: All blocks should have signatures-as-written, even if the return 255 // type is inferred. (That's signified with a dependent result type.) 256 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) { 257 QualType Ty = TSI->getType(); 258 if (const FunctionType *FT = Ty->getAs<FunctionType>()) 259 Ty = FT->getResultType(); 260 if (!Ty->isDependentType()) 261 return Ty; 262 } 263 264 return QualType(); 265 } 266 267 return QualType(); 268 } 269 270 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 271 CallEvent::BindingsTy &Bindings, 272 SValBuilder &SVB, 273 const CallEvent &Call, 274 CallEvent::param_iterator I, 275 CallEvent::param_iterator E) { 276 MemRegionManager &MRMgr = SVB.getRegionManager(); 277 278 // If the function has fewer parameters than the call has arguments, we simply 279 // do not bind any values to them. 280 unsigned NumArgs = Call.getNumArgs(); 281 unsigned Idx = 0; 282 for (; I != E && Idx < NumArgs; ++I, ++Idx) { 283 const ParmVarDecl *ParamDecl = *I; 284 assert(ParamDecl && "Formal parameter has no decl?"); 285 286 SVal ArgVal = Call.getArgSVal(Idx); 287 if (!ArgVal.isUnknown()) { 288 Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx)); 289 Bindings.push_back(std::make_pair(ParamLoc, ArgVal)); 290 } 291 } 292 293 // FIXME: Variadic arguments are not handled at all right now. 294 } 295 296 297 CallEvent::param_iterator AnyFunctionCall::param_begin() const { 298 const FunctionDecl *D = getDecl(); 299 if (!D) 300 return 0; 301 302 return D->param_begin(); 303 } 304 305 CallEvent::param_iterator AnyFunctionCall::param_end() const { 306 const FunctionDecl *D = getDecl(); 307 if (!D) 308 return 0; 309 310 return D->param_end(); 311 } 312 313 void AnyFunctionCall::getInitialStackFrameContents( 314 const StackFrameContext *CalleeCtx, 315 BindingsTy &Bindings) const { 316 const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 317 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 318 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 319 D->param_begin(), D->param_end()); 320 } 321 322 bool AnyFunctionCall::argumentsMayEscape() const { 323 if (hasNonZeroCallbackArg()) 324 return true; 325 326 const FunctionDecl *D = getDecl(); 327 if (!D) 328 return true; 329 330 const IdentifierInfo *II = D->getIdentifier(); 331 if (!II) 332 return false; 333 334 // This set of "escaping" APIs is 335 336 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 337 // value into thread local storage. The value can later be retrieved with 338 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 339 // parameter is 'const void *', the region escapes through the call. 340 if (II->isStr("pthread_setspecific")) 341 return true; 342 343 // - xpc_connection_set_context stores a value which can be retrieved later 344 // with xpc_connection_get_context. 345 if (II->isStr("xpc_connection_set_context")) 346 return true; 347 348 // - funopen - sets a buffer for future IO calls. 349 if (II->isStr("funopen")) 350 return true; 351 352 StringRef FName = II->getName(); 353 354 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 355 // buffer even if it is const. 356 if (FName.endswith("NoCopy")) 357 return true; 358 359 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 360 // be deallocated by NSMapRemove. 361 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 362 return true; 363 364 // - Many CF containers allow objects to escape through custom 365 // allocators/deallocators upon container construction. (PR12101) 366 if (FName.startswith("CF") || FName.startswith("CG")) { 367 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 368 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 369 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 370 StrInStrNoCase(FName, "WithData") != StringRef::npos || 371 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 372 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 373 } 374 375 return false; 376 } 377 378 379 const FunctionDecl *SimpleCall::getDecl() const { 380 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 381 if (D) 382 return D; 383 384 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 385 } 386 387 388 const FunctionDecl *CXXInstanceCall::getDecl() const { 389 const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr()); 390 if (!CE) 391 return AnyFunctionCall::getDecl(); 392 393 const FunctionDecl *D = CE->getDirectCallee(); 394 if (D) 395 return D; 396 397 return getSVal(CE->getCallee()).getAsFunctionDecl(); 398 } 399 400 void CXXInstanceCall::getExtraInvalidatedValues(ValueList &Values) const { 401 Values.push_back(getCXXThisVal()); 402 } 403 404 SVal CXXInstanceCall::getCXXThisVal() const { 405 const Expr *Base = getCXXThisExpr(); 406 // FIXME: This doesn't handle an overloaded ->* operator. 407 if (!Base) 408 return UnknownVal(); 409 410 SVal ThisVal = getSVal(Base); 411 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 412 return ThisVal; 413 } 414 415 416 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 417 // Do we have a decl at all? 418 const Decl *D = getDecl(); 419 if (!D) 420 return RuntimeDefinition(); 421 422 // If the method is non-virtual, we know we can inline it. 423 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 424 if (!MD->isVirtual()) 425 return AnyFunctionCall::getRuntimeDefinition(); 426 427 // Do we know the implicit 'this' object being called? 428 const MemRegion *R = getCXXThisVal().getAsRegion(); 429 if (!R) 430 return RuntimeDefinition(); 431 432 // Do we know anything about the type of 'this'? 433 DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R); 434 if (!DynType.isValid()) 435 return RuntimeDefinition(); 436 437 // Is the type a C++ class? (This is mostly a defensive check.) 438 QualType RegionType = DynType.getType()->getPointeeType(); 439 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 440 441 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 442 if (!RD || !RD->hasDefinition()) 443 return RuntimeDefinition(); 444 445 // Find the decl for this method in that class. 446 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 447 if (!Result) { 448 // We might not even get the original statically-resolved method due to 449 // some particularly nasty casting (e.g. casts to sister classes). 450 // However, we should at least be able to search up and down our own class 451 // hierarchy, and some real bugs have been caught by checking this. 452 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 453 454 // FIXME: This is checking that our DynamicTypeInfo is at least as good as 455 // the static type. However, because we currently don't update 456 // DynamicTypeInfo when an object is cast, we can't actually be sure the 457 // DynamicTypeInfo is up to date. This assert should be re-enabled once 458 // this is fixed. <rdar://problem/12287087> 459 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 460 461 return RuntimeDefinition(); 462 } 463 464 // Does the decl that we found have an implementation? 465 const FunctionDecl *Definition; 466 if (!Result->hasBody(Definition)) 467 return RuntimeDefinition(); 468 469 // We found a definition. If we're not sure that this devirtualization is 470 // actually what will happen at runtime, make sure to provide the region so 471 // that ExprEngine can decide what to do with it. 472 if (DynType.canBeASubClass()) 473 return RuntimeDefinition(Definition, R->StripCasts()); 474 return RuntimeDefinition(Definition, /*DispatchRegion=*/0); 475 } 476 477 void CXXInstanceCall::getInitialStackFrameContents( 478 const StackFrameContext *CalleeCtx, 479 BindingsTy &Bindings) const { 480 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 481 482 // Handle the binding of 'this' in the new stack frame. 483 SVal ThisVal = getCXXThisVal(); 484 if (!ThisVal.isUnknown()) { 485 ProgramStateManager &StateMgr = getState()->getStateManager(); 486 SValBuilder &SVB = StateMgr.getSValBuilder(); 487 488 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 489 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 490 491 // If we devirtualized to a different member function, we need to make sure 492 // we have the proper layering of CXXBaseObjectRegions. 493 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 494 ASTContext &Ctx = SVB.getContext(); 495 const CXXRecordDecl *Class = MD->getParent(); 496 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 497 498 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 499 bool Failed; 500 ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed); 501 assert(!Failed && "Calling an incorrectly devirtualized method"); 502 } 503 504 if (!ThisVal.isUnknown()) 505 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 506 } 507 } 508 509 510 511 const Expr *CXXMemberCall::getCXXThisExpr() const { 512 return getOriginExpr()->getImplicitObjectArgument(); 513 } 514 515 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 516 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 517 // id-expression in the class member access expression is a qualified-id, 518 // that function is called. Otherwise, its final overrider in the dynamic type 519 // of the object expression is called. 520 if (const MemberExpr *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 521 if (ME->hasQualifier()) 522 return AnyFunctionCall::getRuntimeDefinition(); 523 524 return CXXInstanceCall::getRuntimeDefinition(); 525 } 526 527 528 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 529 return getOriginExpr()->getArg(0); 530 } 531 532 533 const BlockDataRegion *BlockCall::getBlockRegion() const { 534 const Expr *Callee = getOriginExpr()->getCallee(); 535 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 536 537 return dyn_cast_or_null<BlockDataRegion>(DataReg); 538 } 539 540 CallEvent::param_iterator BlockCall::param_begin() const { 541 const BlockDecl *D = getBlockDecl(); 542 if (!D) 543 return 0; 544 return D->param_begin(); 545 } 546 547 CallEvent::param_iterator BlockCall::param_end() const { 548 const BlockDecl *D = getBlockDecl(); 549 if (!D) 550 return 0; 551 return D->param_end(); 552 } 553 554 void BlockCall::getExtraInvalidatedValues(ValueList &Values) const { 555 // FIXME: This also needs to invalidate captured globals. 556 if (const MemRegion *R = getBlockRegion()) 557 Values.push_back(loc::MemRegionVal(R)); 558 } 559 560 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 561 BindingsTy &Bindings) const { 562 const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl()); 563 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 564 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 565 D->param_begin(), D->param_end()); 566 } 567 568 569 SVal CXXConstructorCall::getCXXThisVal() const { 570 if (Data) 571 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 572 return UnknownVal(); 573 } 574 575 void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values) const { 576 if (Data) 577 Values.push_back(loc::MemRegionVal(static_cast<const MemRegion *>(Data))); 578 } 579 580 void CXXConstructorCall::getInitialStackFrameContents( 581 const StackFrameContext *CalleeCtx, 582 BindingsTy &Bindings) const { 583 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 584 585 SVal ThisVal = getCXXThisVal(); 586 if (!ThisVal.isUnknown()) { 587 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 588 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 589 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 590 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 591 } 592 } 593 594 595 596 SVal CXXDestructorCall::getCXXThisVal() const { 597 if (Data) 598 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 599 return UnknownVal(); 600 } 601 602 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 603 // Base destructors are always called non-virtually. 604 // Skip CXXInstanceCall's devirtualization logic in this case. 605 if (isBaseDestructor()) 606 return AnyFunctionCall::getRuntimeDefinition(); 607 608 return CXXInstanceCall::getRuntimeDefinition(); 609 } 610 611 612 CallEvent::param_iterator ObjCMethodCall::param_begin() const { 613 const ObjCMethodDecl *D = getDecl(); 614 if (!D) 615 return 0; 616 617 return D->param_begin(); 618 } 619 620 CallEvent::param_iterator ObjCMethodCall::param_end() const { 621 const ObjCMethodDecl *D = getDecl(); 622 if (!D) 623 return 0; 624 625 return D->param_end(); 626 } 627 628 void 629 ObjCMethodCall::getExtraInvalidatedValues(ValueList &Values) const { 630 Values.push_back(getReceiverSVal()); 631 } 632 633 SVal ObjCMethodCall::getSelfSVal() const { 634 const LocationContext *LCtx = getLocationContext(); 635 const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl(); 636 if (!SelfDecl) 637 return SVal(); 638 return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx)); 639 } 640 641 SVal ObjCMethodCall::getReceiverSVal() const { 642 // FIXME: Is this the best way to handle class receivers? 643 if (!isInstanceMessage()) 644 return UnknownVal(); 645 646 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 647 return getSVal(RecE); 648 649 // An instance message with no expression means we are sending to super. 650 // In this case the object reference is the same as 'self'. 651 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 652 SVal SelfVal = getSelfSVal(); 653 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 654 return SelfVal; 655 } 656 657 bool ObjCMethodCall::isReceiverSelfOrSuper() const { 658 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 659 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 660 return true; 661 662 if (!isInstanceMessage()) 663 return false; 664 665 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 666 667 return (RecVal == getSelfSVal()); 668 } 669 670 SourceRange ObjCMethodCall::getSourceRange() const { 671 switch (getMessageKind()) { 672 case OCM_Message: 673 return getOriginExpr()->getSourceRange(); 674 case OCM_PropertyAccess: 675 case OCM_Subscript: 676 return getContainingPseudoObjectExpr()->getSourceRange(); 677 } 678 llvm_unreachable("unknown message kind"); 679 } 680 681 typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy; 682 683 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 684 assert(Data != 0 && "Lazy lookup not yet performed."); 685 assert(getMessageKind() != OCM_Message && "Explicit message send."); 686 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 687 } 688 689 ObjCMessageKind ObjCMethodCall::getMessageKind() const { 690 if (Data == 0) { 691 692 // Find the parent, ignoring implicit casts. 693 ParentMap &PM = getLocationContext()->getParentMap(); 694 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr()); 695 696 // Check if parent is a PseudoObjectExpr. 697 if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 698 const Expr *Syntactic = POE->getSyntacticForm(); 699 700 // This handles the funny case of assigning to the result of a getter. 701 // This can happen if the getter returns a non-const reference. 702 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic)) 703 Syntactic = BO->getLHS(); 704 705 ObjCMessageKind K; 706 switch (Syntactic->getStmtClass()) { 707 case Stmt::ObjCPropertyRefExprClass: 708 K = OCM_PropertyAccess; 709 break; 710 case Stmt::ObjCSubscriptRefExprClass: 711 K = OCM_Subscript; 712 break; 713 default: 714 // FIXME: Can this ever happen? 715 K = OCM_Message; 716 break; 717 } 718 719 if (K != OCM_Message) { 720 const_cast<ObjCMethodCall *>(this)->Data 721 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 722 assert(getMessageKind() == K); 723 return K; 724 } 725 } 726 727 const_cast<ObjCMethodCall *>(this)->Data 728 = ObjCMessageDataTy(0, 1).getOpaqueValue(); 729 assert(getMessageKind() == OCM_Message); 730 return OCM_Message; 731 } 732 733 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 734 if (!Info.getPointer()) 735 return OCM_Message; 736 return static_cast<ObjCMessageKind>(Info.getInt()); 737 } 738 739 740 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 741 Selector Sel) const { 742 assert(IDecl); 743 const SourceManager &SM = 744 getState()->getStateManager().getContext().getSourceManager(); 745 746 // If the class interface is declared inside the main file, assume it is not 747 // subcassed. 748 // TODO: It could actually be subclassed if the subclass is private as well. 749 // This is probably very rare. 750 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 751 if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc)) 752 return false; 753 754 // Assume that property accessors are not overridden. 755 if (getMessageKind() == OCM_PropertyAccess) 756 return false; 757 758 // We assume that if the method is public (declared outside of main file) or 759 // has a parent which publicly declares the method, the method could be 760 // overridden in a subclass. 761 762 // Find the first declaration in the class hierarchy that declares 763 // the selector. 764 ObjCMethodDecl *D = 0; 765 while (true) { 766 D = IDecl->lookupMethod(Sel, true); 767 768 // Cannot find a public definition. 769 if (!D) 770 return false; 771 772 // If outside the main file, 773 if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation())) 774 return true; 775 776 if (D->isOverriding()) { 777 // Search in the superclass on the next iteration. 778 IDecl = D->getClassInterface(); 779 if (!IDecl) 780 return false; 781 782 IDecl = IDecl->getSuperClass(); 783 if (!IDecl) 784 return false; 785 786 continue; 787 } 788 789 return false; 790 }; 791 792 llvm_unreachable("The while loop should always terminate."); 793 } 794 795 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 796 const ObjCMessageExpr *E = getOriginExpr(); 797 assert(E); 798 Selector Sel = E->getSelector(); 799 800 if (E->isInstanceMessage()) { 801 802 // Find the the receiver type. 803 const ObjCObjectPointerType *ReceiverT = 0; 804 bool CanBeSubClassed = false; 805 QualType SupersType = E->getSuperType(); 806 const MemRegion *Receiver = 0; 807 808 if (!SupersType.isNull()) { 809 // Super always means the type of immediate predecessor to the method 810 // where the call occurs. 811 ReceiverT = cast<ObjCObjectPointerType>(SupersType); 812 } else { 813 Receiver = getReceiverSVal().getAsRegion(); 814 if (!Receiver) 815 return RuntimeDefinition(); 816 817 DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver); 818 QualType DynType = DTI.getType(); 819 CanBeSubClassed = DTI.canBeASubClass(); 820 ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType); 821 822 if (ReceiverT && CanBeSubClassed) 823 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) 824 if (!canBeOverridenInSubclass(IDecl, Sel)) 825 CanBeSubClassed = false; 826 } 827 828 // Lookup the method implementation. 829 if (ReceiverT) 830 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) { 831 // Repeatedly calling lookupPrivateMethod() is expensive, especially 832 // when in many cases it returns null. We cache the results so 833 // that repeated queries on the same ObjCIntefaceDecl and Selector 834 // don't incur the same cost. On some test cases, we can see the 835 // same query being issued thousands of times. 836 // 837 // NOTE: This cache is essentially a "global" variable, but it 838 // only gets lazily created when we get here. The value of the 839 // cache probably comes from it being global across ExprEngines, 840 // where the same queries may get issued. If we are worried about 841 // concurrency, or possibly loading/unloading ASTs, etc., we may 842 // need to revisit this someday. In terms of memory, this table 843 // stays around until clang quits, which also may be bad if we 844 // need to release memory. 845 typedef std::pair<const ObjCInterfaceDecl*, Selector> 846 PrivateMethodKey; 847 typedef llvm::DenseMap<PrivateMethodKey, 848 Optional<const ObjCMethodDecl *> > 849 PrivateMethodCache; 850 851 static PrivateMethodCache PMC; 852 Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)]; 853 854 // Query lookupPrivateMethod() if the cache does not hit. 855 if (!Val.hasValue()) 856 Val = IDecl->lookupPrivateMethod(Sel); 857 858 const ObjCMethodDecl *MD = Val.getValue(); 859 if (CanBeSubClassed) 860 return RuntimeDefinition(MD, Receiver); 861 else 862 return RuntimeDefinition(MD, 0); 863 } 864 865 } else { 866 // This is a class method. 867 // If we have type info for the receiver class, we are calling via 868 // class name. 869 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 870 // Find/Return the method implementation. 871 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 872 } 873 } 874 875 return RuntimeDefinition(); 876 } 877 878 void ObjCMethodCall::getInitialStackFrameContents( 879 const StackFrameContext *CalleeCtx, 880 BindingsTy &Bindings) const { 881 const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 882 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 883 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 884 D->param_begin(), D->param_end()); 885 886 SVal SelfVal = getReceiverSVal(); 887 if (!SelfVal.isUnknown()) { 888 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 889 MemRegionManager &MRMgr = SVB.getRegionManager(); 890 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 891 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 892 } 893 } 894 895 CallEventRef<> 896 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 897 const LocationContext *LCtx) { 898 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 899 return create<CXXMemberCall>(MCE, State, LCtx); 900 901 if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 902 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 903 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 904 if (MD->isInstance()) 905 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 906 907 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 908 return create<BlockCall>(CE, State, LCtx); 909 } 910 911 // Otherwise, it's a normal function call, static member function call, or 912 // something we can't reason about. 913 return create<FunctionCall>(CE, State, LCtx); 914 } 915 916 917 CallEventRef<> 918 CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 919 ProgramStateRef State) { 920 const LocationContext *ParentCtx = CalleeCtx->getParent(); 921 const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame(); 922 assert(CallerCtx && "This should not be used for top-level stack frames"); 923 924 const Stmt *CallSite = CalleeCtx->getCallSite(); 925 926 if (CallSite) { 927 if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite)) 928 return getSimpleCall(CE, State, CallerCtx); 929 930 switch (CallSite->getStmtClass()) { 931 case Stmt::CXXConstructExprClass: 932 case Stmt::CXXTemporaryObjectExprClass: { 933 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 934 const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 935 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 936 SVal ThisVal = State->getSVal(ThisPtr); 937 938 return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite), 939 ThisVal.getAsRegion(), State, CallerCtx); 940 } 941 case Stmt::CXXNewExprClass: 942 return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx); 943 case Stmt::ObjCMessageExprClass: 944 return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite), 945 State, CallerCtx); 946 default: 947 llvm_unreachable("This is not an inlineable statement."); 948 } 949 } 950 951 // Fall back to the CFG. The only thing we haven't handled yet is 952 // destructors, though this could change in the future. 953 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 954 CFGElement E = (*B)[CalleeCtx->getIndex()]; 955 assert(E.getAs<CFGImplicitDtor>() && 956 "All other CFG elements should have exprs"); 957 assert(!E.getAs<CFGTemporaryDtor>() && "We don't handle temporaries yet"); 958 959 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 960 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 961 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 962 SVal ThisVal = State->getSVal(ThisPtr); 963 964 const Stmt *Trigger; 965 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 966 Trigger = AutoDtor->getTriggerStmt(); 967 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) 968 Trigger = cast<Stmt>(DeleteDtor->getDeleteExpr()); 969 else 970 Trigger = Dtor->getBody(); 971 972 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 973 E.getAs<CFGBaseDtor>().hasValue(), State, 974 CallerCtx); 975 } 976