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