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