1 //===- CallEvent.cpp - Wrapper for all function and method calls ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file This file defines CallEvent and its subclasses, which represent path- 10 /// sensitive instances of different kinds of function and method calls 11 /// (C, C++, and Objective-C). 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/Expr.h" 23 #include "clang/AST/ExprCXX.h" 24 #include "clang/AST/ExprObjC.h" 25 #include "clang/AST/ParentMap.h" 26 #include "clang/AST/Stmt.h" 27 #include "clang/AST/Type.h" 28 #include "clang/Analysis/AnalysisDeclContext.h" 29 #include "clang/Analysis/CFG.h" 30 #include "clang/Analysis/CFGStmtMap.h" 31 #include "clang/Analysis/PathDiagnostic.h" 32 #include "clang/Analysis/ProgramPoint.h" 33 #include "clang/Basic/IdentifierTable.h" 34 #include "clang/Basic/LLVM.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/SourceManager.h" 37 #include "clang/Basic/Specifiers.h" 38 #include "clang/CrossTU/CrossTranslationUnit.h" 39 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" 40 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicType.h" 41 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h" 42 #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h" 43 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h" 44 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h" 45 #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h" 46 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h" 47 #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h" 48 #include "llvm/ADT/ArrayRef.h" 49 #include "llvm/ADT/DenseMap.h" 50 #include "llvm/ADT/ImmutableList.h" 51 #include "llvm/ADT/None.h" 52 #include "llvm/ADT/Optional.h" 53 #include "llvm/ADT/PointerIntPair.h" 54 #include "llvm/ADT/SmallSet.h" 55 #include "llvm/ADT/SmallVector.h" 56 #include "llvm/ADT/StringExtras.h" 57 #include "llvm/ADT/StringRef.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/Compiler.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include <cassert> 64 #include <utility> 65 66 #define DEBUG_TYPE "static-analyzer-call-event" 67 68 using namespace clang; 69 using namespace ento; 70 71 QualType CallEvent::getResultType() const { 72 ASTContext &Ctx = getState()->getStateManager().getContext(); 73 const Expr *E = getOriginExpr(); 74 if (!E) 75 return Ctx.VoidTy; 76 return Ctx.getReferenceQualifiedType(E); 77 } 78 79 static bool isCallback(QualType T) { 80 // If a parameter is a block or a callback, assume it can modify pointer. 81 if (T->isBlockPointerType() || 82 T->isFunctionPointerType() || 83 T->isObjCSelType()) 84 return true; 85 86 // Check if a callback is passed inside a struct (for both, struct passed by 87 // reference and by value). Dig just one level into the struct for now. 88 89 if (T->isAnyPointerType() || T->isReferenceType()) 90 T = T->getPointeeType(); 91 92 if (const RecordType *RT = T->getAsStructureType()) { 93 const RecordDecl *RD = RT->getDecl(); 94 for (const auto *I : RD->fields()) { 95 QualType FieldT = I->getType(); 96 if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType()) 97 return true; 98 } 99 } 100 return false; 101 } 102 103 static bool isVoidPointerToNonConst(QualType T) { 104 if (const auto *PT = T->getAs<PointerType>()) { 105 QualType PointeeTy = PT->getPointeeType(); 106 if (PointeeTy.isConstQualified()) 107 return false; 108 return PointeeTy->isVoidType(); 109 } else 110 return false; 111 } 112 113 bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const { 114 unsigned NumOfArgs = getNumArgs(); 115 116 // If calling using a function pointer, assume the function does not 117 // satisfy the callback. 118 // TODO: We could check the types of the arguments here. 119 if (!getDecl()) 120 return false; 121 122 unsigned Idx = 0; 123 for (CallEvent::param_type_iterator I = param_type_begin(), 124 E = param_type_end(); 125 I != E && Idx < NumOfArgs; ++I, ++Idx) { 126 // If the parameter is 0, it's harmless. 127 if (getArgSVal(Idx).isZeroConstant()) 128 continue; 129 130 if (Condition(*I)) 131 return true; 132 } 133 return false; 134 } 135 136 bool CallEvent::hasNonZeroCallbackArg() const { 137 return hasNonNullArgumentsWithType(isCallback); 138 } 139 140 bool CallEvent::hasVoidPointerToNonConstArg() const { 141 return hasNonNullArgumentsWithType(isVoidPointerToNonConst); 142 } 143 144 bool CallEvent::isGlobalCFunction(StringRef FunctionName) const { 145 const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 146 if (!FD) 147 return false; 148 149 return CheckerContext::isCLibraryFunction(FD, FunctionName); 150 } 151 152 AnalysisDeclContext *CallEvent::getCalleeAnalysisDeclContext() const { 153 const Decl *D = getDecl(); 154 if (!D) 155 return nullptr; 156 157 AnalysisDeclContext *ADC = 158 LCtx->getAnalysisDeclContext()->getManager()->getContext(D); 159 160 return ADC; 161 } 162 163 const StackFrameContext * 164 CallEvent::getCalleeStackFrame(unsigned BlockCount) const { 165 AnalysisDeclContext *ADC = getCalleeAnalysisDeclContext(); 166 if (!ADC) 167 return nullptr; 168 169 const Expr *E = getOriginExpr(); 170 if (!E) 171 return nullptr; 172 173 // Recover CFG block via reverse lookup. 174 // TODO: If we were to keep CFG element information as part of the CallEvent 175 // instead of doing this reverse lookup, we would be able to build the stack 176 // frame for non-expression-based calls, and also we wouldn't need the reverse 177 // lookup. 178 CFGStmtMap *Map = LCtx->getAnalysisDeclContext()->getCFGStmtMap(); 179 const CFGBlock *B = Map->getBlock(E); 180 assert(B); 181 182 // Also recover CFG index by scanning the CFG block. 183 unsigned Idx = 0, Sz = B->size(); 184 for (; Idx < Sz; ++Idx) 185 if (auto StmtElem = (*B)[Idx].getAs<CFGStmt>()) 186 if (StmtElem->getStmt() == E) 187 break; 188 assert(Idx < Sz); 189 190 return ADC->getManager()->getStackFrame(ADC, LCtx, E, B, BlockCount, Idx); 191 } 192 193 const ParamVarRegion 194 *CallEvent::getParameterLocation(unsigned Index, unsigned BlockCount) const { 195 const StackFrameContext *SFC = getCalleeStackFrame(BlockCount); 196 // We cannot construct a VarRegion without a stack frame. 197 if (!SFC) 198 return nullptr; 199 200 const ParamVarRegion *PVR = 201 State->getStateManager().getRegionManager().getParamVarRegion( 202 getOriginExpr(), Index, SFC); 203 return PVR; 204 } 205 206 /// Returns true if a type is a pointer-to-const or reference-to-const 207 /// with no further indirection. 208 static bool isPointerToConst(QualType Ty) { 209 QualType PointeeTy = Ty->getPointeeType(); 210 if (PointeeTy == QualType()) 211 return false; 212 if (!PointeeTy.isConstQualified()) 213 return false; 214 if (PointeeTy->isAnyPointerType()) 215 return false; 216 return true; 217 } 218 219 // Try to retrieve the function declaration and find the function parameter 220 // types which are pointers/references to a non-pointer const. 221 // We will not invalidate the corresponding argument regions. 222 static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs, 223 const CallEvent &Call) { 224 unsigned Idx = 0; 225 for (CallEvent::param_type_iterator I = Call.param_type_begin(), 226 E = Call.param_type_end(); 227 I != E; ++I, ++Idx) { 228 if (isPointerToConst(*I)) 229 PreserveArgs.insert(Idx); 230 } 231 } 232 233 ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount, 234 ProgramStateRef Orig) const { 235 ProgramStateRef Result = (Orig ? Orig : getState()); 236 237 // Don't invalidate anything if the callee is marked pure/const. 238 if (const Decl *callee = getDecl()) 239 if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>()) 240 return Result; 241 242 SmallVector<SVal, 8> ValuesToInvalidate; 243 RegionAndSymbolInvalidationTraits ETraits; 244 245 getExtraInvalidatedValues(ValuesToInvalidate, &ETraits); 246 247 // Indexes of arguments whose values will be preserved by the call. 248 llvm::SmallSet<unsigned, 4> PreserveArgs; 249 if (!argumentsMayEscape()) 250 findPtrToConstParams(PreserveArgs, *this); 251 252 for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) { 253 // Mark this region for invalidation. We batch invalidate regions 254 // below for efficiency. 255 if (PreserveArgs.count(Idx)) 256 if (const MemRegion *MR = getArgSVal(Idx).getAsRegion()) 257 ETraits.setTrait(MR->getBaseRegion(), 258 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 259 // TODO: Factor this out + handle the lower level const pointers. 260 261 ValuesToInvalidate.push_back(getArgSVal(Idx)); 262 263 // If a function accepts an object by argument (which would of course be a 264 // temporary that isn't lifetime-extended), invalidate the object itself, 265 // not only other objects reachable from it. This is necessary because the 266 // destructor has access to the temporary object after the call. 267 // TODO: Support placement arguments once we start 268 // constructing them directly. 269 // TODO: This is unnecessary when there's no destructor, but that's 270 // currently hard to figure out. 271 if (getKind() != CE_CXXAllocator) 272 if (isArgumentConstructedDirectly(Idx)) 273 if (auto AdjIdx = getAdjustedParameterIndex(Idx)) 274 if (const TypedValueRegion *TVR = 275 getParameterLocation(*AdjIdx, BlockCount)) 276 ValuesToInvalidate.push_back(loc::MemRegionVal(TVR)); 277 } 278 279 // Invalidate designated regions using the batch invalidation API. 280 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 281 // global variables. 282 return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(), 283 BlockCount, getLocationContext(), 284 /*CausedByPointerEscape*/ true, 285 /*Symbols=*/nullptr, this, &ETraits); 286 } 287 288 ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit, 289 const ProgramPointTag *Tag) const { 290 if (const Expr *E = getOriginExpr()) { 291 if (IsPreVisit) 292 return PreStmt(E, getLocationContext(), Tag); 293 return PostStmt(E, getLocationContext(), Tag); 294 } 295 296 const Decl *D = getDecl(); 297 assert(D && "Cannot get a program point without a statement or decl"); 298 299 SourceLocation Loc = getSourceRange().getBegin(); 300 if (IsPreVisit) 301 return PreImplicitCall(D, Loc, getLocationContext(), Tag); 302 return PostImplicitCall(D, Loc, getLocationContext(), Tag); 303 } 304 305 bool CallEvent::isCalled(const CallDescription &CD) const { 306 // FIXME: Add ObjC Message support. 307 if (getKind() == CE_ObjCMessage) 308 return false; 309 310 const IdentifierInfo *II = getCalleeIdentifier(); 311 if (!II) 312 return false; 313 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 314 if (!FD) 315 return false; 316 317 if (CD.Flags & CDF_MaybeBuiltin) { 318 return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) && 319 (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) && 320 (!CD.RequiredParams || CD.RequiredParams <= parameters().size()); 321 } 322 323 if (!CD.IsLookupDone) { 324 CD.IsLookupDone = true; 325 CD.II = &getState()->getStateManager().getContext().Idents.get( 326 CD.getFunctionName()); 327 } 328 329 if (II != CD.II) 330 return false; 331 332 // If CallDescription provides prefix names, use them to improve matching 333 // accuracy. 334 if (CD.QualifiedName.size() > 1 && FD) { 335 const DeclContext *Ctx = FD->getDeclContext(); 336 // See if we'll be able to match them all. 337 size_t NumUnmatched = CD.QualifiedName.size() - 1; 338 for (; Ctx && isa<NamedDecl>(Ctx); Ctx = Ctx->getParent()) { 339 if (NumUnmatched == 0) 340 break; 341 342 if (const auto *ND = dyn_cast<NamespaceDecl>(Ctx)) { 343 if (ND->getName() == CD.QualifiedName[NumUnmatched - 1]) 344 --NumUnmatched; 345 continue; 346 } 347 348 if (const auto *RD = dyn_cast<RecordDecl>(Ctx)) { 349 if (RD->getName() == CD.QualifiedName[NumUnmatched - 1]) 350 --NumUnmatched; 351 continue; 352 } 353 } 354 355 if (NumUnmatched > 0) 356 return false; 357 } 358 359 return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs()) && 360 (!CD.RequiredParams || CD.RequiredParams == parameters().size()); 361 } 362 363 SVal CallEvent::getArgSVal(unsigned Index) const { 364 const Expr *ArgE = getArgExpr(Index); 365 if (!ArgE) 366 return UnknownVal(); 367 return getSVal(ArgE); 368 } 369 370 SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 371 const Expr *ArgE = getArgExpr(Index); 372 if (!ArgE) 373 return {}; 374 return ArgE->getSourceRange(); 375 } 376 377 SVal CallEvent::getReturnValue() const { 378 const Expr *E = getOriginExpr(); 379 if (!E) 380 return UndefinedVal(); 381 return getSVal(E); 382 } 383 384 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); } 385 386 void CallEvent::dump(raw_ostream &Out) const { 387 ASTContext &Ctx = getState()->getStateManager().getContext(); 388 if (const Expr *E = getOriginExpr()) { 389 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy()); 390 Out << "\n"; 391 return; 392 } 393 394 if (const Decl *D = getDecl()) { 395 Out << "Call to "; 396 D->print(Out, Ctx.getPrintingPolicy()); 397 return; 398 } 399 400 Out << "Unknown call (type " << getKindAsString() << ")"; 401 } 402 403 bool CallEvent::isCallStmt(const Stmt *S) { 404 return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S) 405 || isa<CXXConstructExpr>(S) 406 || isa<CXXNewExpr>(S); 407 } 408 409 QualType CallEvent::getDeclaredResultType(const Decl *D) { 410 assert(D); 411 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 412 return FD->getReturnType(); 413 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 414 return MD->getReturnType(); 415 if (const auto *BD = dyn_cast<BlockDecl>(D)) { 416 // Blocks are difficult because the return type may not be stored in the 417 // BlockDecl itself. The AST should probably be enhanced, but for now we 418 // just do what we can. 419 // If the block is declared without an explicit argument list, the 420 // signature-as-written just includes the return type, not the entire 421 // function type. 422 // FIXME: All blocks should have signatures-as-written, even if the return 423 // type is inferred. (That's signified with a dependent result type.) 424 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) { 425 QualType Ty = TSI->getType(); 426 if (const FunctionType *FT = Ty->getAs<FunctionType>()) 427 Ty = FT->getReturnType(); 428 if (!Ty->isDependentType()) 429 return Ty; 430 } 431 432 return {}; 433 } 434 435 llvm_unreachable("unknown callable kind"); 436 } 437 438 bool CallEvent::isVariadic(const Decl *D) { 439 assert(D); 440 441 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 442 return FD->isVariadic(); 443 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 444 return MD->isVariadic(); 445 if (const auto *BD = dyn_cast<BlockDecl>(D)) 446 return BD->isVariadic(); 447 448 llvm_unreachable("unknown callable kind"); 449 } 450 451 static bool isTransparentUnion(QualType T) { 452 const RecordType *UT = T->getAsUnionType(); 453 return UT && UT->getDecl()->hasAttr<TransparentUnionAttr>(); 454 } 455 456 // In some cases, symbolic cases should be transformed before we associate 457 // them with parameters. This function incapsulates such cases. 458 static SVal processArgument(SVal Value, const Expr *ArgumentExpr, 459 const ParmVarDecl *Parameter, SValBuilder &SVB) { 460 QualType ParamType = Parameter->getType(); 461 QualType ArgumentType = ArgumentExpr->getType(); 462 463 // Transparent unions allow users to easily convert values of union field 464 // types into union-typed objects. 465 // 466 // Also, more importantly, they allow users to define functions with different 467 // different parameter types, substituting types matching transparent union 468 // field types with the union type itself. 469 // 470 // Here, we check specifically for latter cases and prevent binding 471 // field-typed values to union-typed regions. 472 if (isTransparentUnion(ParamType) && 473 // Let's check that we indeed trying to bind different types. 474 !isTransparentUnion(ArgumentType)) { 475 BasicValueFactory &BVF = SVB.getBasicValueFactory(); 476 477 llvm::ImmutableList<SVal> CompoundSVals = BVF.getEmptySValList(); 478 CompoundSVals = BVF.prependSVal(Value, CompoundSVals); 479 480 // Wrap it with compound value. 481 return SVB.makeCompoundVal(ParamType, CompoundSVals); 482 } 483 484 return Value; 485 } 486 487 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 488 CallEvent::BindingsTy &Bindings, 489 SValBuilder &SVB, 490 const CallEvent &Call, 491 ArrayRef<ParmVarDecl*> parameters) { 492 MemRegionManager &MRMgr = SVB.getRegionManager(); 493 494 // If the function has fewer parameters than the call has arguments, we simply 495 // do not bind any values to them. 496 unsigned NumArgs = Call.getNumArgs(); 497 unsigned Idx = 0; 498 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end(); 499 for (; I != E && Idx < NumArgs; ++I, ++Idx) { 500 assert(*I && "Formal parameter has no decl?"); 501 502 // TODO: Support allocator calls. 503 if (Call.getKind() != CE_CXXAllocator) 504 if (Call.isArgumentConstructedDirectly(Call.getASTArgumentIndex(Idx))) 505 continue; 506 507 // TODO: Allocators should receive the correct size and possibly alignment, 508 // determined in compile-time but not represented as arg-expressions, 509 // which makes getArgSVal() fail and return UnknownVal. 510 SVal ArgVal = Call.getArgSVal(Idx); 511 const Expr *ArgExpr = Call.getArgExpr(Idx); 512 if (!ArgVal.isUnknown()) { 513 Loc ParamLoc = SVB.makeLoc( 514 MRMgr.getParamVarRegion(Call.getOriginExpr(), Idx, CalleeCtx)); 515 Bindings.push_back( 516 std::make_pair(ParamLoc, processArgument(ArgVal, ArgExpr, *I, SVB))); 517 } 518 } 519 520 // FIXME: Variadic arguments are not handled at all right now. 521 } 522 523 const ConstructionContext *CallEvent::getConstructionContext() const { 524 const StackFrameContext *StackFrame = getCalleeStackFrame(0); 525 if (!StackFrame) 526 return nullptr; 527 528 const CFGElement Element = StackFrame->getCallSiteCFGElement(); 529 if (const auto Ctor = Element.getAs<CFGConstructor>()) { 530 return Ctor->getConstructionContext(); 531 } 532 533 if (const auto RecCall = Element.getAs<CFGCXXRecordTypedCall>()) { 534 return RecCall->getConstructionContext(); 535 } 536 537 return nullptr; 538 } 539 540 Optional<SVal> 541 CallEvent::getReturnValueUnderConstruction() const { 542 const auto *CC = getConstructionContext(); 543 if (!CC) 544 return None; 545 546 EvalCallOptions CallOpts; 547 ExprEngine &Engine = getState()->getStateManager().getOwningEngine(); 548 SVal RetVal = 549 Engine.computeObjectUnderConstruction(getOriginExpr(), getState(), 550 getLocationContext(), CC, CallOpts); 551 return RetVal; 552 } 553 554 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const { 555 const FunctionDecl *D = getDecl(); 556 if (!D) 557 return None; 558 return D->parameters(); 559 } 560 561 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const { 562 const FunctionDecl *FD = getDecl(); 563 if (!FD) 564 return {}; 565 566 // Note that the AnalysisDeclContext will have the FunctionDecl with 567 // the definition (if one exists). 568 AnalysisDeclContext *AD = 569 getLocationContext()->getAnalysisDeclContext()-> 570 getManager()->getContext(FD); 571 bool IsAutosynthesized; 572 Stmt* Body = AD->getBody(IsAutosynthesized); 573 LLVM_DEBUG({ 574 if (IsAutosynthesized) 575 llvm::dbgs() << "Using autosynthesized body for " << FD->getName() 576 << "\n"; 577 }); 578 if (Body) { 579 const Decl* Decl = AD->getDecl(); 580 return RuntimeDefinition(Decl); 581 } 582 583 ExprEngine &Engine = getState()->getStateManager().getOwningEngine(); 584 AnalyzerOptions &Opts = Engine.getAnalysisManager().options; 585 586 // Try to get CTU definition only if CTUDir is provided. 587 if (!Opts.IsNaiveCTUEnabled) 588 return {}; 589 590 cross_tu::CrossTranslationUnitContext &CTUCtx = 591 *Engine.getCrossTranslationUnitContext(); 592 llvm::Expected<const FunctionDecl *> CTUDeclOrError = 593 CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName, 594 Opts.DisplayCTUProgress); 595 596 if (!CTUDeclOrError) { 597 handleAllErrors(CTUDeclOrError.takeError(), 598 [&](const cross_tu::IndexError &IE) { 599 CTUCtx.emitCrossTUDiagnostics(IE); 600 }); 601 return {}; 602 } 603 604 return RuntimeDefinition(*CTUDeclOrError); 605 } 606 607 void AnyFunctionCall::getInitialStackFrameContents( 608 const StackFrameContext *CalleeCtx, 609 BindingsTy &Bindings) const { 610 const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 611 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 612 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 613 D->parameters()); 614 } 615 616 bool AnyFunctionCall::argumentsMayEscape() const { 617 if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg()) 618 return true; 619 620 const FunctionDecl *D = getDecl(); 621 if (!D) 622 return true; 623 624 const IdentifierInfo *II = D->getIdentifier(); 625 if (!II) 626 return false; 627 628 // This set of "escaping" APIs is 629 630 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 631 // value into thread local storage. The value can later be retrieved with 632 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 633 // parameter is 'const void *', the region escapes through the call. 634 if (II->isStr("pthread_setspecific")) 635 return true; 636 637 // - xpc_connection_set_context stores a value which can be retrieved later 638 // with xpc_connection_get_context. 639 if (II->isStr("xpc_connection_set_context")) 640 return true; 641 642 // - funopen - sets a buffer for future IO calls. 643 if (II->isStr("funopen")) 644 return true; 645 646 // - __cxa_demangle - can reallocate memory and can return the pointer to 647 // the input buffer. 648 if (II->isStr("__cxa_demangle")) 649 return true; 650 651 StringRef FName = II->getName(); 652 653 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 654 // buffer even if it is const. 655 if (FName.endswith("NoCopy")) 656 return true; 657 658 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 659 // be deallocated by NSMapRemove. 660 if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos)) 661 return true; 662 663 // - Many CF containers allow objects to escape through custom 664 // allocators/deallocators upon container construction. (PR12101) 665 if (FName.startswith("CF") || FName.startswith("CG")) { 666 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 667 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 668 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 669 StrInStrNoCase(FName, "WithData") != StringRef::npos || 670 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 671 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 672 } 673 674 return false; 675 } 676 677 const FunctionDecl *SimpleFunctionCall::getDecl() const { 678 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 679 if (D) 680 return D; 681 682 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 683 } 684 685 const FunctionDecl *CXXInstanceCall::getDecl() const { 686 const auto *CE = cast_or_null<CallExpr>(getOriginExpr()); 687 if (!CE) 688 return AnyFunctionCall::getDecl(); 689 690 const FunctionDecl *D = CE->getDirectCallee(); 691 if (D) 692 return D; 693 694 return getSVal(CE->getCallee()).getAsFunctionDecl(); 695 } 696 697 void CXXInstanceCall::getExtraInvalidatedValues( 698 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 699 SVal ThisVal = getCXXThisVal(); 700 Values.push_back(ThisVal); 701 702 // Don't invalidate if the method is const and there are no mutable fields. 703 if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) { 704 if (!D->isConst()) 705 return; 706 // Get the record decl for the class of 'This'. D->getParent() may return a 707 // base class decl, rather than the class of the instance which needs to be 708 // checked for mutable fields. 709 // TODO: We might as well look at the dynamic type of the object. 710 const Expr *Ex = getCXXThisExpr()->IgnoreParenBaseCasts(); 711 QualType T = Ex->getType(); 712 if (T->isPointerType()) // Arrow or implicit-this syntax? 713 T = T->getPointeeType(); 714 const CXXRecordDecl *ParentRecord = T->getAsCXXRecordDecl(); 715 assert(ParentRecord); 716 if (ParentRecord->hasMutableFields()) 717 return; 718 // Preserve CXXThis. 719 const MemRegion *ThisRegion = ThisVal.getAsRegion(); 720 if (!ThisRegion) 721 return; 722 723 ETraits->setTrait(ThisRegion->getBaseRegion(), 724 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 725 } 726 } 727 728 SVal CXXInstanceCall::getCXXThisVal() const { 729 const Expr *Base = getCXXThisExpr(); 730 // FIXME: This doesn't handle an overloaded ->* operator. 731 if (!Base) 732 return UnknownVal(); 733 734 SVal ThisVal = getSVal(Base); 735 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 736 return ThisVal; 737 } 738 739 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 740 // Do we have a decl at all? 741 const Decl *D = getDecl(); 742 if (!D) 743 return {}; 744 745 // If the method is non-virtual, we know we can inline it. 746 const auto *MD = cast<CXXMethodDecl>(D); 747 if (!MD->isVirtual()) 748 return AnyFunctionCall::getRuntimeDefinition(); 749 750 // Do we know the implicit 'this' object being called? 751 const MemRegion *R = getCXXThisVal().getAsRegion(); 752 if (!R) 753 return {}; 754 755 // Do we know anything about the type of 'this'? 756 DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R); 757 if (!DynType.isValid()) 758 return {}; 759 760 // Is the type a C++ class? (This is mostly a defensive check.) 761 QualType RegionType = DynType.getType()->getPointeeType(); 762 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 763 764 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 765 if (!RD || !RD->hasDefinition()) 766 return {}; 767 768 // Find the decl for this method in that class. 769 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 770 if (!Result) { 771 // We might not even get the original statically-resolved method due to 772 // some particularly nasty casting (e.g. casts to sister classes). 773 // However, we should at least be able to search up and down our own class 774 // hierarchy, and some real bugs have been caught by checking this. 775 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 776 777 // FIXME: This is checking that our DynamicTypeInfo is at least as good as 778 // the static type. However, because we currently don't update 779 // DynamicTypeInfo when an object is cast, we can't actually be sure the 780 // DynamicTypeInfo is up to date. This assert should be re-enabled once 781 // this is fixed. <rdar://problem/12287087> 782 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 783 784 return {}; 785 } 786 787 // Does the decl that we found have an implementation? 788 const FunctionDecl *Definition; 789 if (!Result->hasBody(Definition)) { 790 if (!DynType.canBeASubClass()) 791 return AnyFunctionCall::getRuntimeDefinition(); 792 return {}; 793 } 794 795 // We found a definition. If we're not sure that this devirtualization is 796 // actually what will happen at runtime, make sure to provide the region so 797 // that ExprEngine can decide what to do with it. 798 if (DynType.canBeASubClass()) 799 return RuntimeDefinition(Definition, R->StripCasts()); 800 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr); 801 } 802 803 void CXXInstanceCall::getInitialStackFrameContents( 804 const StackFrameContext *CalleeCtx, 805 BindingsTy &Bindings) const { 806 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 807 808 // Handle the binding of 'this' in the new stack frame. 809 SVal ThisVal = getCXXThisVal(); 810 if (!ThisVal.isUnknown()) { 811 ProgramStateManager &StateMgr = getState()->getStateManager(); 812 SValBuilder &SVB = StateMgr.getSValBuilder(); 813 814 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 815 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 816 817 // If we devirtualized to a different member function, we need to make sure 818 // we have the proper layering of CXXBaseObjectRegions. 819 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 820 ASTContext &Ctx = SVB.getContext(); 821 const CXXRecordDecl *Class = MD->getParent(); 822 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 823 824 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 825 bool Failed; 826 ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed); 827 if (Failed) { 828 // We might have suffered some sort of placement new earlier, so 829 // we're constructing in a completely unexpected storage. 830 // Fall back to a generic pointer cast for this-value. 831 const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl()); 832 const CXXRecordDecl *StaticClass = StaticMD->getParent(); 833 QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass)); 834 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy); 835 } 836 } 837 838 if (!ThisVal.isUnknown()) 839 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 840 } 841 } 842 843 const Expr *CXXMemberCall::getCXXThisExpr() const { 844 return getOriginExpr()->getImplicitObjectArgument(); 845 } 846 847 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 848 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 849 // id-expression in the class member access expression is a qualified-id, 850 // that function is called. Otherwise, its final overrider in the dynamic type 851 // of the object expression is called. 852 if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 853 if (ME->hasQualifier()) 854 return AnyFunctionCall::getRuntimeDefinition(); 855 856 return CXXInstanceCall::getRuntimeDefinition(); 857 } 858 859 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 860 return getOriginExpr()->getArg(0); 861 } 862 863 const BlockDataRegion *BlockCall::getBlockRegion() const { 864 const Expr *Callee = getOriginExpr()->getCallee(); 865 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 866 867 return dyn_cast_or_null<BlockDataRegion>(DataReg); 868 } 869 870 ArrayRef<ParmVarDecl*> BlockCall::parameters() const { 871 const BlockDecl *D = getDecl(); 872 if (!D) 873 return None; 874 return D->parameters(); 875 } 876 877 void BlockCall::getExtraInvalidatedValues(ValueList &Values, 878 RegionAndSymbolInvalidationTraits *ETraits) const { 879 // FIXME: This also needs to invalidate captured globals. 880 if (const MemRegion *R = getBlockRegion()) 881 Values.push_back(loc::MemRegionVal(R)); 882 } 883 884 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 885 BindingsTy &Bindings) const { 886 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 887 ArrayRef<ParmVarDecl*> Params; 888 if (isConversionFromLambda()) { 889 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 890 Params = LambdaOperatorDecl->parameters(); 891 892 // For blocks converted from a C++ lambda, the callee declaration is the 893 // operator() method on the lambda so we bind "this" to 894 // the lambda captured by the block. 895 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda(); 896 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion); 897 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx); 898 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 899 } else { 900 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters(); 901 } 902 903 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 904 Params); 905 } 906 907 SVal AnyCXXConstructorCall::getCXXThisVal() const { 908 if (Data) 909 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 910 return UnknownVal(); 911 } 912 913 void AnyCXXConstructorCall::getExtraInvalidatedValues(ValueList &Values, 914 RegionAndSymbolInvalidationTraits *ETraits) const { 915 SVal V = getCXXThisVal(); 916 if (SymbolRef Sym = V.getAsSymbol(true)) 917 ETraits->setTrait(Sym, 918 RegionAndSymbolInvalidationTraits::TK_SuppressEscape); 919 Values.push_back(V); 920 } 921 922 void AnyCXXConstructorCall::getInitialStackFrameContents( 923 const StackFrameContext *CalleeCtx, 924 BindingsTy &Bindings) const { 925 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 926 927 SVal ThisVal = getCXXThisVal(); 928 if (!ThisVal.isUnknown()) { 929 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 930 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 931 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 932 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 933 } 934 } 935 936 const StackFrameContext * 937 CXXInheritedConstructorCall::getInheritingStackFrame() const { 938 const StackFrameContext *SFC = getLocationContext()->getStackFrame(); 939 while (isa<CXXInheritedCtorInitExpr>(SFC->getCallSite())) 940 SFC = SFC->getParent()->getStackFrame(); 941 return SFC; 942 } 943 944 SVal CXXDestructorCall::getCXXThisVal() const { 945 if (Data) 946 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 947 return UnknownVal(); 948 } 949 950 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 951 // Base destructors are always called non-virtually. 952 // Skip CXXInstanceCall's devirtualization logic in this case. 953 if (isBaseDestructor()) 954 return AnyFunctionCall::getRuntimeDefinition(); 955 956 return CXXInstanceCall::getRuntimeDefinition(); 957 } 958 959 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const { 960 const ObjCMethodDecl *D = getDecl(); 961 if (!D) 962 return None; 963 return D->parameters(); 964 } 965 966 void ObjCMethodCall::getExtraInvalidatedValues( 967 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 968 969 // If the method call is a setter for property known to be backed by 970 // an instance variable, don't invalidate the entire receiver, just 971 // the storage for that instance variable. 972 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) { 973 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) { 974 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal()); 975 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) { 976 ETraits->setTrait( 977 IvarRegion, 978 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 979 ETraits->setTrait( 980 IvarRegion, 981 RegionAndSymbolInvalidationTraits::TK_SuppressEscape); 982 Values.push_back(IvarLVal); 983 } 984 return; 985 } 986 } 987 988 Values.push_back(getReceiverSVal()); 989 } 990 991 SVal ObjCMethodCall::getReceiverSVal() const { 992 // FIXME: Is this the best way to handle class receivers? 993 if (!isInstanceMessage()) 994 return UnknownVal(); 995 996 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 997 return getSVal(RecE); 998 999 // An instance message with no expression means we are sending to super. 1000 // In this case the object reference is the same as 'self'. 1001 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 1002 SVal SelfVal = getState()->getSelfSVal(getLocationContext()); 1003 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 1004 return SelfVal; 1005 } 1006 1007 bool ObjCMethodCall::isReceiverSelfOrSuper() const { 1008 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 1009 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 1010 return true; 1011 1012 if (!isInstanceMessage()) 1013 return false; 1014 1015 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 1016 SVal SelfVal = getState()->getSelfSVal(getLocationContext()); 1017 1018 return (RecVal == SelfVal); 1019 } 1020 1021 SourceRange ObjCMethodCall::getSourceRange() const { 1022 switch (getMessageKind()) { 1023 case OCM_Message: 1024 return getOriginExpr()->getSourceRange(); 1025 case OCM_PropertyAccess: 1026 case OCM_Subscript: 1027 return getContainingPseudoObjectExpr()->getSourceRange(); 1028 } 1029 llvm_unreachable("unknown message kind"); 1030 } 1031 1032 using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>; 1033 1034 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 1035 assert(Data && "Lazy lookup not yet performed."); 1036 assert(getMessageKind() != OCM_Message && "Explicit message send."); 1037 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 1038 } 1039 1040 static const Expr * 1041 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) { 1042 const Expr *Syntactic = POE->getSyntacticForm(); 1043 1044 // This handles the funny case of assigning to the result of a getter. 1045 // This can happen if the getter returns a non-const reference. 1046 if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic)) 1047 Syntactic = BO->getLHS(); 1048 1049 return Syntactic; 1050 } 1051 1052 ObjCMessageKind ObjCMethodCall::getMessageKind() const { 1053 if (!Data) { 1054 // Find the parent, ignoring implicit casts. 1055 const ParentMap &PM = getLocationContext()->getParentMap(); 1056 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr()); 1057 1058 // Check if parent is a PseudoObjectExpr. 1059 if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 1060 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE); 1061 1062 ObjCMessageKind K; 1063 switch (Syntactic->getStmtClass()) { 1064 case Stmt::ObjCPropertyRefExprClass: 1065 K = OCM_PropertyAccess; 1066 break; 1067 case Stmt::ObjCSubscriptRefExprClass: 1068 K = OCM_Subscript; 1069 break; 1070 default: 1071 // FIXME: Can this ever happen? 1072 K = OCM_Message; 1073 break; 1074 } 1075 1076 if (K != OCM_Message) { 1077 const_cast<ObjCMethodCall *>(this)->Data 1078 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 1079 assert(getMessageKind() == K); 1080 return K; 1081 } 1082 } 1083 1084 const_cast<ObjCMethodCall *>(this)->Data 1085 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue(); 1086 assert(getMessageKind() == OCM_Message); 1087 return OCM_Message; 1088 } 1089 1090 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 1091 if (!Info.getPointer()) 1092 return OCM_Message; 1093 return static_cast<ObjCMessageKind>(Info.getInt()); 1094 } 1095 1096 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const { 1097 // Look for properties accessed with property syntax (foo.bar = ...) 1098 if (getMessageKind() == OCM_PropertyAccess) { 1099 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr(); 1100 assert(POE && "Property access without PseudoObjectExpr?"); 1101 1102 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE); 1103 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic); 1104 1105 if (RefExpr->isExplicitProperty()) 1106 return RefExpr->getExplicitProperty(); 1107 } 1108 1109 // Look for properties accessed with method syntax ([foo setBar:...]). 1110 const ObjCMethodDecl *MD = getDecl(); 1111 if (!MD || !MD->isPropertyAccessor()) 1112 return nullptr; 1113 1114 // Note: This is potentially quite slow. 1115 return MD->findPropertyDecl(); 1116 } 1117 1118 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 1119 Selector Sel) const { 1120 assert(IDecl); 1121 AnalysisManager &AMgr = 1122 getState()->getStateManager().getOwningEngine().getAnalysisManager(); 1123 // If the class interface is declared inside the main file, assume it is not 1124 // subcassed. 1125 // TODO: It could actually be subclassed if the subclass is private as well. 1126 // This is probably very rare. 1127 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 1128 if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc)) 1129 return false; 1130 1131 // Assume that property accessors are not overridden. 1132 if (getMessageKind() == OCM_PropertyAccess) 1133 return false; 1134 1135 // We assume that if the method is public (declared outside of main file) or 1136 // has a parent which publicly declares the method, the method could be 1137 // overridden in a subclass. 1138 1139 // Find the first declaration in the class hierarchy that declares 1140 // the selector. 1141 ObjCMethodDecl *D = nullptr; 1142 while (true) { 1143 D = IDecl->lookupMethod(Sel, true); 1144 1145 // Cannot find a public definition. 1146 if (!D) 1147 return false; 1148 1149 // If outside the main file, 1150 if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation())) 1151 return true; 1152 1153 if (D->isOverriding()) { 1154 // Search in the superclass on the next iteration. 1155 IDecl = D->getClassInterface(); 1156 if (!IDecl) 1157 return false; 1158 1159 IDecl = IDecl->getSuperClass(); 1160 if (!IDecl) 1161 return false; 1162 1163 continue; 1164 } 1165 1166 return false; 1167 }; 1168 1169 llvm_unreachable("The while loop should always terminate."); 1170 } 1171 1172 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) { 1173 if (!MD) 1174 return MD; 1175 1176 // Find the redeclaration that defines the method. 1177 if (!MD->hasBody()) { 1178 for (auto I : MD->redecls()) 1179 if (I->hasBody()) 1180 MD = cast<ObjCMethodDecl>(I); 1181 } 1182 return MD; 1183 } 1184 1185 struct PrivateMethodKey { 1186 const ObjCInterfaceDecl *Interface; 1187 Selector LookupSelector; 1188 bool IsClassMethod; 1189 }; 1190 1191 namespace llvm { 1192 template <> struct DenseMapInfo<PrivateMethodKey> { 1193 using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>; 1194 using SelectorInfo = DenseMapInfo<Selector>; 1195 1196 static inline PrivateMethodKey getEmptyKey() { 1197 return {InterfaceInfo::getEmptyKey(), SelectorInfo::getEmptyKey(), false}; 1198 } 1199 1200 static inline PrivateMethodKey getTombstoneKey() { 1201 return {InterfaceInfo::getTombstoneKey(), SelectorInfo::getTombstoneKey(), 1202 true}; 1203 } 1204 1205 static unsigned getHashValue(const PrivateMethodKey &Key) { 1206 return llvm::hash_combine( 1207 llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)), 1208 llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)), 1209 Key.IsClassMethod); 1210 } 1211 1212 static bool isEqual(const PrivateMethodKey &LHS, 1213 const PrivateMethodKey &RHS) { 1214 return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) && 1215 SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) && 1216 LHS.IsClassMethod == RHS.IsClassMethod; 1217 } 1218 }; 1219 } // end namespace llvm 1220 1221 static const ObjCMethodDecl * 1222 lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface, 1223 Selector LookupSelector, bool InstanceMethod) { 1224 // Repeatedly calling lookupPrivateMethod() is expensive, especially 1225 // when in many cases it returns null. We cache the results so 1226 // that repeated queries on the same ObjCIntefaceDecl and Selector 1227 // don't incur the same cost. On some test cases, we can see the 1228 // same query being issued thousands of times. 1229 // 1230 // NOTE: This cache is essentially a "global" variable, but it 1231 // only gets lazily created when we get here. The value of the 1232 // cache probably comes from it being global across ExprEngines, 1233 // where the same queries may get issued. If we are worried about 1234 // concurrency, or possibly loading/unloading ASTs, etc., we may 1235 // need to revisit this someday. In terms of memory, this table 1236 // stays around until clang quits, which also may be bad if we 1237 // need to release memory. 1238 using PrivateMethodCache = 1239 llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>; 1240 1241 static PrivateMethodCache PMC; 1242 Optional<const ObjCMethodDecl *> &Val = 1243 PMC[{Interface, LookupSelector, InstanceMethod}]; 1244 1245 // Query lookupPrivateMethod() if the cache does not hit. 1246 if (!Val.hasValue()) { 1247 Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod); 1248 1249 if (!*Val) { 1250 // Query 'lookupMethod' as a backup. 1251 Val = Interface->lookupMethod(LookupSelector, InstanceMethod); 1252 } 1253 } 1254 1255 return Val.getValue(); 1256 } 1257 1258 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 1259 const ObjCMessageExpr *E = getOriginExpr(); 1260 assert(E); 1261 Selector Sel = E->getSelector(); 1262 1263 if (E->isInstanceMessage()) { 1264 // Find the receiver type. 1265 const ObjCObjectType *ReceiverT = nullptr; 1266 bool CanBeSubClassed = false; 1267 bool LookingForInstanceMethod = true; 1268 QualType SupersType = E->getSuperType(); 1269 const MemRegion *Receiver = nullptr; 1270 1271 if (!SupersType.isNull()) { 1272 // The receiver is guaranteed to be 'super' in this case. 1273 // Super always means the type of immediate predecessor to the method 1274 // where the call occurs. 1275 ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType(); 1276 } else { 1277 Receiver = getReceiverSVal().getAsRegion(); 1278 if (!Receiver) 1279 return {}; 1280 1281 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver); 1282 if (!DTI.isValid()) { 1283 assert(isa<AllocaRegion>(Receiver) && 1284 "Unhandled untyped region class!"); 1285 return {}; 1286 } 1287 1288 QualType DynType = DTI.getType(); 1289 CanBeSubClassed = DTI.canBeASubClass(); 1290 1291 const auto *ReceiverDynT = 1292 dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType()); 1293 1294 if (ReceiverDynT) { 1295 ReceiverT = ReceiverDynT->getObjectType(); 1296 1297 // It can be actually class methods called with Class object as a 1298 // receiver. This type of messages is treated by the compiler as 1299 // instance (not class). 1300 if (ReceiverT->isObjCClass()) { 1301 1302 SVal SelfVal = getState()->getSelfSVal(getLocationContext()); 1303 // For [self classMethod], return compiler visible declaration. 1304 if (Receiver == SelfVal.getAsRegion()) { 1305 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl())); 1306 } 1307 1308 // Otherwise, let's check if we know something about the type 1309 // inside of this class object. 1310 if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) { 1311 DynamicTypeInfo DTI = 1312 getClassObjectDynamicTypeInfo(getState(), ReceiverSym); 1313 if (DTI.isValid()) { 1314 // Let's use this type for lookup. 1315 ReceiverT = 1316 cast<ObjCObjectType>(DTI.getType().getCanonicalType()); 1317 1318 CanBeSubClassed = DTI.canBeASubClass(); 1319 // And it should be a class method instead. 1320 LookingForInstanceMethod = false; 1321 } 1322 } 1323 } 1324 1325 if (CanBeSubClassed) 1326 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) 1327 // Even if `DynamicTypeInfo` told us that it can be 1328 // not necessarily this type, but its descendants, we still want 1329 // to check again if this selector can be actually overridden. 1330 CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel); 1331 } 1332 } 1333 1334 // Lookup the instance method implementation. 1335 if (ReceiverT) 1336 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) { 1337 const ObjCMethodDecl *MD = 1338 lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod); 1339 1340 if (MD && !MD->hasBody()) 1341 MD = MD->getCanonicalDecl(); 1342 1343 if (CanBeSubClassed) 1344 return RuntimeDefinition(MD, Receiver); 1345 else 1346 return RuntimeDefinition(MD, nullptr); 1347 } 1348 } else { 1349 // This is a class method. 1350 // If we have type info for the receiver class, we are calling via 1351 // class name. 1352 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 1353 // Find/Return the method implementation. 1354 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 1355 } 1356 } 1357 1358 return {}; 1359 } 1360 1361 bool ObjCMethodCall::argumentsMayEscape() const { 1362 if (isInSystemHeader() && !isInstanceMessage()) { 1363 Selector Sel = getSelector(); 1364 if (Sel.getNumArgs() == 1 && 1365 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer")) 1366 return true; 1367 } 1368 1369 return CallEvent::argumentsMayEscape(); 1370 } 1371 1372 void ObjCMethodCall::getInitialStackFrameContents( 1373 const StackFrameContext *CalleeCtx, 1374 BindingsTy &Bindings) const { 1375 const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 1376 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 1377 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 1378 D->parameters()); 1379 1380 SVal SelfVal = getReceiverSVal(); 1381 if (!SelfVal.isUnknown()) { 1382 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 1383 MemRegionManager &MRMgr = SVB.getRegionManager(); 1384 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 1385 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 1386 } 1387 } 1388 1389 CallEventRef<> 1390 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 1391 const LocationContext *LCtx) { 1392 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 1393 return create<CXXMemberCall>(MCE, State, LCtx); 1394 1395 if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 1396 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 1397 if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 1398 if (MD->isInstance()) 1399 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 1400 1401 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 1402 return create<BlockCall>(CE, State, LCtx); 1403 } 1404 1405 // Otherwise, it's a normal function call, static member function call, or 1406 // something we can't reason about. 1407 return create<SimpleFunctionCall>(CE, State, LCtx); 1408 } 1409 1410 CallEventRef<> 1411 CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 1412 ProgramStateRef State) { 1413 const LocationContext *ParentCtx = CalleeCtx->getParent(); 1414 const LocationContext *CallerCtx = ParentCtx->getStackFrame(); 1415 assert(CallerCtx && "This should not be used for top-level stack frames"); 1416 1417 const Stmt *CallSite = CalleeCtx->getCallSite(); 1418 1419 if (CallSite) { 1420 if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx)) 1421 return Out; 1422 1423 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1424 const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 1425 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 1426 SVal ThisVal = State->getSVal(ThisPtr); 1427 1428 if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite)) 1429 return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerCtx); 1430 else if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite)) 1431 return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State, 1432 CallerCtx); 1433 else { 1434 // All other cases are handled by getCall. 1435 llvm_unreachable("This is not an inlineable statement"); 1436 } 1437 } 1438 1439 // Fall back to the CFG. The only thing we haven't handled yet is 1440 // destructors, though this could change in the future. 1441 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 1442 CFGElement E = (*B)[CalleeCtx->getIndex()]; 1443 assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) && 1444 "All other CFG elements should have exprs"); 1445 1446 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1447 const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 1448 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 1449 SVal ThisVal = State->getSVal(ThisPtr); 1450 1451 const Stmt *Trigger; 1452 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 1453 Trigger = AutoDtor->getTriggerStmt(); 1454 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) 1455 Trigger = DeleteDtor->getDeleteExpr(); 1456 else 1457 Trigger = Dtor->getBody(); 1458 1459 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 1460 E.getAs<CFGBaseDtor>().hasValue(), State, 1461 CallerCtx); 1462 } 1463 1464 CallEventRef<> CallEventManager::getCall(const Stmt *S, ProgramStateRef State, 1465 const LocationContext *LC) { 1466 if (const auto *CE = dyn_cast<CallExpr>(S)) { 1467 return getSimpleCall(CE, State, LC); 1468 } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) { 1469 return getCXXAllocatorCall(NE, State, LC); 1470 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) { 1471 return getObjCMethodCall(ME, State, LC); 1472 } else { 1473 return nullptr; 1474 } 1475 } 1476