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