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 auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl()); 311 if (!FD) 312 return false; 313 314 if (CD.Flags & CDF_MaybeBuiltin) { 315 return CheckerContext::isCLibraryFunction(FD, CD.getFunctionName()) && 316 (!CD.RequiredArgs || CD.RequiredArgs <= getNumArgs()) && 317 (!CD.RequiredParams || CD.RequiredParams <= parameters().size()); 318 } 319 320 if (!CD.II.hasValue()) { 321 CD.II = &getState()->getStateManager().getContext().Idents.get( 322 CD.getFunctionName()); 323 } 324 325 const auto MatchNameOnly = [](const CallDescription &CD, 326 const NamedDecl *ND) -> bool { 327 DeclarationName Name = ND->getDeclName(); 328 if (const auto *II = Name.getAsIdentifierInfo()) 329 return II == CD.II.getValue(); // Fast case. 330 331 // Fallback to the slow stringification and comparison for: 332 // C++ overloaded operators, constructors, destructors, etc. 333 // FIXME This comparison is way SLOWER than comparing pointers. 334 // At some point in the future, we should compare FunctionDecl pointers. 335 return Name.getAsString() == CD.getFunctionName(); 336 }; 337 338 const auto ExactMatchArgAndParamCounts = 339 [](const CallEvent &Call, const CallDescription &CD) -> bool { 340 const bool ArgsMatch = 341 !CD.RequiredArgs || CD.RequiredArgs == Call.getNumArgs(); 342 const bool ParamsMatch = 343 !CD.RequiredParams || CD.RequiredParams == Call.parameters().size(); 344 return ArgsMatch && ParamsMatch; 345 }; 346 347 const auto MatchQualifiedNameParts = [](const CallDescription &CD, 348 const Decl *D) -> bool { 349 const auto FindNextNamespaceOrRecord = 350 [](const DeclContext *Ctx) -> const DeclContext * { 351 while (Ctx && !isa<NamespaceDecl, RecordDecl>(Ctx)) 352 Ctx = Ctx->getParent(); 353 return Ctx; 354 }; 355 356 auto QualifierPartsIt = CD.begin_qualified_name_parts(); 357 const auto QualifierPartsEndIt = CD.end_qualified_name_parts(); 358 359 // Match namespace and record names. Skip unrelated names if they don't 360 // match. 361 const DeclContext *Ctx = FindNextNamespaceOrRecord(D->getDeclContext()); 362 for (; Ctx && QualifierPartsIt != QualifierPartsEndIt; 363 Ctx = FindNextNamespaceOrRecord(Ctx->getParent())) { 364 // If not matched just continue and try matching for the next one. 365 if (cast<NamedDecl>(Ctx)->getName() != *QualifierPartsIt) 366 continue; 367 ++QualifierPartsIt; 368 } 369 370 // We matched if we consumed all expected qualifier segments. 371 return QualifierPartsIt == QualifierPartsEndIt; 372 }; 373 374 // Let's start matching... 375 if (!ExactMatchArgAndParamCounts(*this, CD)) 376 return false; 377 378 if (!MatchNameOnly(CD, FD)) 379 return false; 380 381 if (!CD.hasQualifiedNameParts()) 382 return true; 383 384 return MatchQualifiedNameParts(CD, FD); 385 } 386 387 SVal CallEvent::getArgSVal(unsigned Index) const { 388 const Expr *ArgE = getArgExpr(Index); 389 if (!ArgE) 390 return UnknownVal(); 391 return getSVal(ArgE); 392 } 393 394 SourceRange CallEvent::getArgSourceRange(unsigned Index) const { 395 const Expr *ArgE = getArgExpr(Index); 396 if (!ArgE) 397 return {}; 398 return ArgE->getSourceRange(); 399 } 400 401 SVal CallEvent::getReturnValue() const { 402 const Expr *E = getOriginExpr(); 403 if (!E) 404 return UndefinedVal(); 405 return getSVal(E); 406 } 407 408 LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); } 409 410 void CallEvent::dump(raw_ostream &Out) const { 411 ASTContext &Ctx = getState()->getStateManager().getContext(); 412 if (const Expr *E = getOriginExpr()) { 413 E->printPretty(Out, nullptr, Ctx.getPrintingPolicy()); 414 Out << "\n"; 415 return; 416 } 417 418 if (const Decl *D = getDecl()) { 419 Out << "Call to "; 420 D->print(Out, Ctx.getPrintingPolicy()); 421 return; 422 } 423 424 Out << "Unknown call (type " << getKindAsString() << ")"; 425 } 426 427 bool CallEvent::isCallStmt(const Stmt *S) { 428 return isa<CallExpr, ObjCMessageExpr, CXXConstructExpr, CXXNewExpr>(S); 429 } 430 431 QualType CallEvent::getDeclaredResultType(const Decl *D) { 432 assert(D); 433 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 434 return FD->getReturnType(); 435 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 436 return MD->getReturnType(); 437 if (const auto *BD = dyn_cast<BlockDecl>(D)) { 438 // Blocks are difficult because the return type may not be stored in the 439 // BlockDecl itself. The AST should probably be enhanced, but for now we 440 // just do what we can. 441 // If the block is declared without an explicit argument list, the 442 // signature-as-written just includes the return type, not the entire 443 // function type. 444 // FIXME: All blocks should have signatures-as-written, even if the return 445 // type is inferred. (That's signified with a dependent result type.) 446 if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) { 447 QualType Ty = TSI->getType(); 448 if (const FunctionType *FT = Ty->getAs<FunctionType>()) 449 Ty = FT->getReturnType(); 450 if (!Ty->isDependentType()) 451 return Ty; 452 } 453 454 return {}; 455 } 456 457 llvm_unreachable("unknown callable kind"); 458 } 459 460 bool CallEvent::isVariadic(const Decl *D) { 461 assert(D); 462 463 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 464 return FD->isVariadic(); 465 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 466 return MD->isVariadic(); 467 if (const auto *BD = dyn_cast<BlockDecl>(D)) 468 return BD->isVariadic(); 469 470 llvm_unreachable("unknown callable kind"); 471 } 472 473 static bool isTransparentUnion(QualType T) { 474 const RecordType *UT = T->getAsUnionType(); 475 return UT && UT->getDecl()->hasAttr<TransparentUnionAttr>(); 476 } 477 478 // In some cases, symbolic cases should be transformed before we associate 479 // them with parameters. This function incapsulates such cases. 480 static SVal processArgument(SVal Value, const Expr *ArgumentExpr, 481 const ParmVarDecl *Parameter, SValBuilder &SVB) { 482 QualType ParamType = Parameter->getType(); 483 QualType ArgumentType = ArgumentExpr->getType(); 484 485 // Transparent unions allow users to easily convert values of union field 486 // types into union-typed objects. 487 // 488 // Also, more importantly, they allow users to define functions with different 489 // different parameter types, substituting types matching transparent union 490 // field types with the union type itself. 491 // 492 // Here, we check specifically for latter cases and prevent binding 493 // field-typed values to union-typed regions. 494 if (isTransparentUnion(ParamType) && 495 // Let's check that we indeed trying to bind different types. 496 !isTransparentUnion(ArgumentType)) { 497 BasicValueFactory &BVF = SVB.getBasicValueFactory(); 498 499 llvm::ImmutableList<SVal> CompoundSVals = BVF.getEmptySValList(); 500 CompoundSVals = BVF.prependSVal(Value, CompoundSVals); 501 502 // Wrap it with compound value. 503 return SVB.makeCompoundVal(ParamType, CompoundSVals); 504 } 505 506 return Value; 507 } 508 509 static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx, 510 CallEvent::BindingsTy &Bindings, 511 SValBuilder &SVB, 512 const CallEvent &Call, 513 ArrayRef<ParmVarDecl*> parameters) { 514 MemRegionManager &MRMgr = SVB.getRegionManager(); 515 516 // If the function has fewer parameters than the call has arguments, we simply 517 // do not bind any values to them. 518 unsigned NumArgs = Call.getNumArgs(); 519 unsigned Idx = 0; 520 ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end(); 521 for (; I != E && Idx < NumArgs; ++I, ++Idx) { 522 assert(*I && "Formal parameter has no decl?"); 523 524 // TODO: Support allocator calls. 525 if (Call.getKind() != CE_CXXAllocator) 526 if (Call.isArgumentConstructedDirectly(Call.getASTArgumentIndex(Idx))) 527 continue; 528 529 // TODO: Allocators should receive the correct size and possibly alignment, 530 // determined in compile-time but not represented as arg-expressions, 531 // which makes getArgSVal() fail and return UnknownVal. 532 SVal ArgVal = Call.getArgSVal(Idx); 533 const Expr *ArgExpr = Call.getArgExpr(Idx); 534 if (!ArgVal.isUnknown()) { 535 Loc ParamLoc = SVB.makeLoc( 536 MRMgr.getParamVarRegion(Call.getOriginExpr(), Idx, CalleeCtx)); 537 Bindings.push_back( 538 std::make_pair(ParamLoc, processArgument(ArgVal, ArgExpr, *I, SVB))); 539 } 540 } 541 542 // FIXME: Variadic arguments are not handled at all right now. 543 } 544 545 const ConstructionContext *CallEvent::getConstructionContext() const { 546 const StackFrameContext *StackFrame = getCalleeStackFrame(0); 547 if (!StackFrame) 548 return nullptr; 549 550 const CFGElement Element = StackFrame->getCallSiteCFGElement(); 551 if (const auto Ctor = Element.getAs<CFGConstructor>()) { 552 return Ctor->getConstructionContext(); 553 } 554 555 if (const auto RecCall = Element.getAs<CFGCXXRecordTypedCall>()) { 556 return RecCall->getConstructionContext(); 557 } 558 559 return nullptr; 560 } 561 562 Optional<SVal> 563 CallEvent::getReturnValueUnderConstruction() const { 564 const auto *CC = getConstructionContext(); 565 if (!CC) 566 return None; 567 568 EvalCallOptions CallOpts; 569 ExprEngine &Engine = getState()->getStateManager().getOwningEngine(); 570 SVal RetVal = 571 Engine.computeObjectUnderConstruction(getOriginExpr(), getState(), 572 getLocationContext(), CC, CallOpts); 573 return RetVal; 574 } 575 576 ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const { 577 const FunctionDecl *D = getDecl(); 578 if (!D) 579 return None; 580 return D->parameters(); 581 } 582 583 RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const { 584 const FunctionDecl *FD = getDecl(); 585 if (!FD) 586 return {}; 587 588 // Note that the AnalysisDeclContext will have the FunctionDecl with 589 // the definition (if one exists). 590 AnalysisDeclContext *AD = 591 getLocationContext()->getAnalysisDeclContext()-> 592 getManager()->getContext(FD); 593 bool IsAutosynthesized; 594 Stmt* Body = AD->getBody(IsAutosynthesized); 595 LLVM_DEBUG({ 596 if (IsAutosynthesized) 597 llvm::dbgs() << "Using autosynthesized body for " << FD->getName() 598 << "\n"; 599 }); 600 if (Body) { 601 const Decl* Decl = AD->getDecl(); 602 return RuntimeDefinition(Decl); 603 } 604 605 ExprEngine &Engine = getState()->getStateManager().getOwningEngine(); 606 AnalyzerOptions &Opts = Engine.getAnalysisManager().options; 607 608 // Try to get CTU definition only if CTUDir is provided. 609 if (!Opts.IsNaiveCTUEnabled) 610 return {}; 611 612 cross_tu::CrossTranslationUnitContext &CTUCtx = 613 *Engine.getCrossTranslationUnitContext(); 614 llvm::Expected<const FunctionDecl *> CTUDeclOrError = 615 CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName, 616 Opts.DisplayCTUProgress); 617 618 if (!CTUDeclOrError) { 619 handleAllErrors(CTUDeclOrError.takeError(), 620 [&](const cross_tu::IndexError &IE) { 621 CTUCtx.emitCrossTUDiagnostics(IE); 622 }); 623 return {}; 624 } 625 626 return RuntimeDefinition(*CTUDeclOrError); 627 } 628 629 void AnyFunctionCall::getInitialStackFrameContents( 630 const StackFrameContext *CalleeCtx, 631 BindingsTy &Bindings) const { 632 const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl()); 633 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 634 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 635 D->parameters()); 636 } 637 638 bool AnyFunctionCall::argumentsMayEscape() const { 639 if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg()) 640 return true; 641 642 const FunctionDecl *D = getDecl(); 643 if (!D) 644 return true; 645 646 const IdentifierInfo *II = D->getIdentifier(); 647 if (!II) 648 return false; 649 650 // This set of "escaping" APIs is 651 652 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 653 // value into thread local storage. The value can later be retrieved with 654 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 655 // parameter is 'const void *', the region escapes through the call. 656 if (II->isStr("pthread_setspecific")) 657 return true; 658 659 // - xpc_connection_set_context stores a value which can be retrieved later 660 // with xpc_connection_get_context. 661 if (II->isStr("xpc_connection_set_context")) 662 return true; 663 664 // - funopen - sets a buffer for future IO calls. 665 if (II->isStr("funopen")) 666 return true; 667 668 // - __cxa_demangle - can reallocate memory and can return the pointer to 669 // the input buffer. 670 if (II->isStr("__cxa_demangle")) 671 return true; 672 673 StringRef FName = II->getName(); 674 675 // - CoreFoundation functions that end with "NoCopy" can free a passed-in 676 // buffer even if it is const. 677 if (FName.endswith("NoCopy")) 678 return true; 679 680 // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can 681 // be deallocated by NSMapRemove. 682 if (FName.startswith("NS") && FName.contains("Insert")) 683 return true; 684 685 // - Many CF containers allow objects to escape through custom 686 // allocators/deallocators upon container construction. (PR12101) 687 if (FName.startswith("CF") || FName.startswith("CG")) { 688 return StrInStrNoCase(FName, "InsertValue") != StringRef::npos || 689 StrInStrNoCase(FName, "AddValue") != StringRef::npos || 690 StrInStrNoCase(FName, "SetValue") != StringRef::npos || 691 StrInStrNoCase(FName, "WithData") != StringRef::npos || 692 StrInStrNoCase(FName, "AppendValue") != StringRef::npos || 693 StrInStrNoCase(FName, "SetAttribute") != StringRef::npos; 694 } 695 696 return false; 697 } 698 699 const FunctionDecl *SimpleFunctionCall::getDecl() const { 700 const FunctionDecl *D = getOriginExpr()->getDirectCallee(); 701 if (D) 702 return D; 703 704 return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl(); 705 } 706 707 const FunctionDecl *CXXInstanceCall::getDecl() const { 708 const auto *CE = cast_or_null<CallExpr>(getOriginExpr()); 709 if (!CE) 710 return AnyFunctionCall::getDecl(); 711 712 const FunctionDecl *D = CE->getDirectCallee(); 713 if (D) 714 return D; 715 716 return getSVal(CE->getCallee()).getAsFunctionDecl(); 717 } 718 719 void CXXInstanceCall::getExtraInvalidatedValues( 720 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 721 SVal ThisVal = getCXXThisVal(); 722 Values.push_back(ThisVal); 723 724 // Don't invalidate if the method is const and there are no mutable fields. 725 if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) { 726 if (!D->isConst()) 727 return; 728 // Get the record decl for the class of 'This'. D->getParent() may return a 729 // base class decl, rather than the class of the instance which needs to be 730 // checked for mutable fields. 731 // TODO: We might as well look at the dynamic type of the object. 732 const Expr *Ex = getCXXThisExpr()->IgnoreParenBaseCasts(); 733 QualType T = Ex->getType(); 734 if (T->isPointerType()) // Arrow or implicit-this syntax? 735 T = T->getPointeeType(); 736 const CXXRecordDecl *ParentRecord = T->getAsCXXRecordDecl(); 737 assert(ParentRecord); 738 if (ParentRecord->hasMutableFields()) 739 return; 740 // Preserve CXXThis. 741 const MemRegion *ThisRegion = ThisVal.getAsRegion(); 742 if (!ThisRegion) 743 return; 744 745 ETraits->setTrait(ThisRegion->getBaseRegion(), 746 RegionAndSymbolInvalidationTraits::TK_PreserveContents); 747 } 748 } 749 750 SVal CXXInstanceCall::getCXXThisVal() const { 751 const Expr *Base = getCXXThisExpr(); 752 // FIXME: This doesn't handle an overloaded ->* operator. 753 if (!Base) 754 return UnknownVal(); 755 756 SVal ThisVal = getSVal(Base); 757 assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>()); 758 return ThisVal; 759 } 760 761 RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const { 762 // Do we have a decl at all? 763 const Decl *D = getDecl(); 764 if (!D) 765 return {}; 766 767 // If the method is non-virtual, we know we can inline it. 768 const auto *MD = cast<CXXMethodDecl>(D); 769 if (!MD->isVirtual()) 770 return AnyFunctionCall::getRuntimeDefinition(); 771 772 // Do we know the implicit 'this' object being called? 773 const MemRegion *R = getCXXThisVal().getAsRegion(); 774 if (!R) 775 return {}; 776 777 // Do we know anything about the type of 'this'? 778 DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R); 779 if (!DynType.isValid()) 780 return {}; 781 782 // Is the type a C++ class? (This is mostly a defensive check.) 783 QualType RegionType = DynType.getType()->getPointeeType(); 784 assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer."); 785 786 const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl(); 787 if (!RD || !RD->hasDefinition()) 788 return {}; 789 790 // Find the decl for this method in that class. 791 const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true); 792 if (!Result) { 793 // We might not even get the original statically-resolved method due to 794 // some particularly nasty casting (e.g. casts to sister classes). 795 // However, we should at least be able to search up and down our own class 796 // hierarchy, and some real bugs have been caught by checking this. 797 assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method"); 798 799 // FIXME: This is checking that our DynamicTypeInfo is at least as good as 800 // the static type. However, because we currently don't update 801 // DynamicTypeInfo when an object is cast, we can't actually be sure the 802 // DynamicTypeInfo is up to date. This assert should be re-enabled once 803 // this is fixed. <rdar://problem/12287087> 804 //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo"); 805 806 return {}; 807 } 808 809 // Does the decl that we found have an implementation? 810 const FunctionDecl *Definition; 811 if (!Result->hasBody(Definition)) { 812 if (!DynType.canBeASubClass()) 813 return AnyFunctionCall::getRuntimeDefinition(); 814 return {}; 815 } 816 817 // We found a definition. If we're not sure that this devirtualization is 818 // actually what will happen at runtime, make sure to provide the region so 819 // that ExprEngine can decide what to do with it. 820 if (DynType.canBeASubClass()) 821 return RuntimeDefinition(Definition, R->StripCasts()); 822 return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr); 823 } 824 825 void CXXInstanceCall::getInitialStackFrameContents( 826 const StackFrameContext *CalleeCtx, 827 BindingsTy &Bindings) const { 828 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 829 830 // Handle the binding of 'this' in the new stack frame. 831 SVal ThisVal = getCXXThisVal(); 832 if (!ThisVal.isUnknown()) { 833 ProgramStateManager &StateMgr = getState()->getStateManager(); 834 SValBuilder &SVB = StateMgr.getSValBuilder(); 835 836 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 837 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 838 839 // If we devirtualized to a different member function, we need to make sure 840 // we have the proper layering of CXXBaseObjectRegions. 841 if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) { 842 ASTContext &Ctx = SVB.getContext(); 843 const CXXRecordDecl *Class = MD->getParent(); 844 QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class)); 845 846 // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager. 847 bool Failed; 848 ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed); 849 if (Failed) { 850 // We might have suffered some sort of placement new earlier, so 851 // we're constructing in a completely unexpected storage. 852 // Fall back to a generic pointer cast for this-value. 853 const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl()); 854 const CXXRecordDecl *StaticClass = StaticMD->getParent(); 855 QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass)); 856 ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy); 857 } 858 } 859 860 if (!ThisVal.isUnknown()) 861 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 862 } 863 } 864 865 const Expr *CXXMemberCall::getCXXThisExpr() const { 866 return getOriginExpr()->getImplicitObjectArgument(); 867 } 868 869 RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const { 870 // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the 871 // id-expression in the class member access expression is a qualified-id, 872 // that function is called. Otherwise, its final overrider in the dynamic type 873 // of the object expression is called. 874 if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee())) 875 if (ME->hasQualifier()) 876 return AnyFunctionCall::getRuntimeDefinition(); 877 878 return CXXInstanceCall::getRuntimeDefinition(); 879 } 880 881 const Expr *CXXMemberOperatorCall::getCXXThisExpr() const { 882 return getOriginExpr()->getArg(0); 883 } 884 885 const BlockDataRegion *BlockCall::getBlockRegion() const { 886 const Expr *Callee = getOriginExpr()->getCallee(); 887 const MemRegion *DataReg = getSVal(Callee).getAsRegion(); 888 889 return dyn_cast_or_null<BlockDataRegion>(DataReg); 890 } 891 892 ArrayRef<ParmVarDecl*> BlockCall::parameters() const { 893 const BlockDecl *D = getDecl(); 894 if (!D) 895 return None; 896 return D->parameters(); 897 } 898 899 void BlockCall::getExtraInvalidatedValues(ValueList &Values, 900 RegionAndSymbolInvalidationTraits *ETraits) const { 901 // FIXME: This also needs to invalidate captured globals. 902 if (const MemRegion *R = getBlockRegion()) 903 Values.push_back(loc::MemRegionVal(R)); 904 } 905 906 void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx, 907 BindingsTy &Bindings) const { 908 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 909 ArrayRef<ParmVarDecl*> Params; 910 if (isConversionFromLambda()) { 911 auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 912 Params = LambdaOperatorDecl->parameters(); 913 914 // For blocks converted from a C++ lambda, the callee declaration is the 915 // operator() method on the lambda so we bind "this" to 916 // the lambda captured by the block. 917 const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda(); 918 SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion); 919 Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx); 920 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 921 } else { 922 Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters(); 923 } 924 925 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 926 Params); 927 } 928 929 SVal AnyCXXConstructorCall::getCXXThisVal() const { 930 if (Data) 931 return loc::MemRegionVal(static_cast<const MemRegion *>(Data)); 932 return UnknownVal(); 933 } 934 935 void AnyCXXConstructorCall::getExtraInvalidatedValues(ValueList &Values, 936 RegionAndSymbolInvalidationTraits *ETraits) const { 937 SVal V = getCXXThisVal(); 938 if (SymbolRef Sym = V.getAsSymbol(true)) 939 ETraits->setTrait(Sym, 940 RegionAndSymbolInvalidationTraits::TK_SuppressEscape); 941 Values.push_back(V); 942 } 943 944 void AnyCXXConstructorCall::getInitialStackFrameContents( 945 const StackFrameContext *CalleeCtx, 946 BindingsTy &Bindings) const { 947 AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings); 948 949 SVal ThisVal = getCXXThisVal(); 950 if (!ThisVal.isUnknown()) { 951 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 952 const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 953 Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx); 954 Bindings.push_back(std::make_pair(ThisLoc, ThisVal)); 955 } 956 } 957 958 const StackFrameContext * 959 CXXInheritedConstructorCall::getInheritingStackFrame() const { 960 const StackFrameContext *SFC = getLocationContext()->getStackFrame(); 961 while (isa<CXXInheritedCtorInitExpr>(SFC->getCallSite())) 962 SFC = SFC->getParent()->getStackFrame(); 963 return SFC; 964 } 965 966 SVal CXXDestructorCall::getCXXThisVal() const { 967 if (Data) 968 return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer()); 969 return UnknownVal(); 970 } 971 972 RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const { 973 // Base destructors are always called non-virtually. 974 // Skip CXXInstanceCall's devirtualization logic in this case. 975 if (isBaseDestructor()) 976 return AnyFunctionCall::getRuntimeDefinition(); 977 978 return CXXInstanceCall::getRuntimeDefinition(); 979 } 980 981 ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const { 982 const ObjCMethodDecl *D = getDecl(); 983 if (!D) 984 return None; 985 return D->parameters(); 986 } 987 988 void ObjCMethodCall::getExtraInvalidatedValues( 989 ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const { 990 991 // If the method call is a setter for property known to be backed by 992 // an instance variable, don't invalidate the entire receiver, just 993 // the storage for that instance variable. 994 if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) { 995 if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) { 996 SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal()); 997 if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) { 998 ETraits->setTrait( 999 IvarRegion, 1000 RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion); 1001 ETraits->setTrait( 1002 IvarRegion, 1003 RegionAndSymbolInvalidationTraits::TK_SuppressEscape); 1004 Values.push_back(IvarLVal); 1005 } 1006 return; 1007 } 1008 } 1009 1010 Values.push_back(getReceiverSVal()); 1011 } 1012 1013 SVal ObjCMethodCall::getReceiverSVal() const { 1014 // FIXME: Is this the best way to handle class receivers? 1015 if (!isInstanceMessage()) 1016 return UnknownVal(); 1017 1018 if (const Expr *RecE = getOriginExpr()->getInstanceReceiver()) 1019 return getSVal(RecE); 1020 1021 // An instance message with no expression means we are sending to super. 1022 // In this case the object reference is the same as 'self'. 1023 assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance); 1024 SVal SelfVal = getState()->getSelfSVal(getLocationContext()); 1025 assert(SelfVal.isValid() && "Calling super but not in ObjC method"); 1026 return SelfVal; 1027 } 1028 1029 bool ObjCMethodCall::isReceiverSelfOrSuper() const { 1030 if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance || 1031 getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass) 1032 return true; 1033 1034 if (!isInstanceMessage()) 1035 return false; 1036 1037 SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver()); 1038 SVal SelfVal = getState()->getSelfSVal(getLocationContext()); 1039 1040 return (RecVal == SelfVal); 1041 } 1042 1043 SourceRange ObjCMethodCall::getSourceRange() const { 1044 switch (getMessageKind()) { 1045 case OCM_Message: 1046 return getOriginExpr()->getSourceRange(); 1047 case OCM_PropertyAccess: 1048 case OCM_Subscript: 1049 return getContainingPseudoObjectExpr()->getSourceRange(); 1050 } 1051 llvm_unreachable("unknown message kind"); 1052 } 1053 1054 using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>; 1055 1056 const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const { 1057 assert(Data && "Lazy lookup not yet performed."); 1058 assert(getMessageKind() != OCM_Message && "Explicit message send."); 1059 return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer(); 1060 } 1061 1062 static const Expr * 1063 getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) { 1064 const Expr *Syntactic = POE->getSyntacticForm()->IgnoreParens(); 1065 1066 // This handles the funny case of assigning to the result of a getter. 1067 // This can happen if the getter returns a non-const reference. 1068 if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic)) 1069 Syntactic = BO->getLHS()->IgnoreParens(); 1070 1071 return Syntactic; 1072 } 1073 1074 ObjCMessageKind ObjCMethodCall::getMessageKind() const { 1075 if (!Data) { 1076 // Find the parent, ignoring implicit casts. 1077 const ParentMap &PM = getLocationContext()->getParentMap(); 1078 const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr()); 1079 1080 // Check if parent is a PseudoObjectExpr. 1081 if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) { 1082 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE); 1083 1084 ObjCMessageKind K; 1085 switch (Syntactic->getStmtClass()) { 1086 case Stmt::ObjCPropertyRefExprClass: 1087 K = OCM_PropertyAccess; 1088 break; 1089 case Stmt::ObjCSubscriptRefExprClass: 1090 K = OCM_Subscript; 1091 break; 1092 default: 1093 // FIXME: Can this ever happen? 1094 K = OCM_Message; 1095 break; 1096 } 1097 1098 if (K != OCM_Message) { 1099 const_cast<ObjCMethodCall *>(this)->Data 1100 = ObjCMessageDataTy(POE, K).getOpaqueValue(); 1101 assert(getMessageKind() == K); 1102 return K; 1103 } 1104 } 1105 1106 const_cast<ObjCMethodCall *>(this)->Data 1107 = ObjCMessageDataTy(nullptr, 1).getOpaqueValue(); 1108 assert(getMessageKind() == OCM_Message); 1109 return OCM_Message; 1110 } 1111 1112 ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data); 1113 if (!Info.getPointer()) 1114 return OCM_Message; 1115 return static_cast<ObjCMessageKind>(Info.getInt()); 1116 } 1117 1118 const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const { 1119 // Look for properties accessed with property syntax (foo.bar = ...) 1120 if (getMessageKind() == OCM_PropertyAccess) { 1121 const PseudoObjectExpr *POE = getContainingPseudoObjectExpr(); 1122 assert(POE && "Property access without PseudoObjectExpr?"); 1123 1124 const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE); 1125 auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic); 1126 1127 if (RefExpr->isExplicitProperty()) 1128 return RefExpr->getExplicitProperty(); 1129 } 1130 1131 // Look for properties accessed with method syntax ([foo setBar:...]). 1132 const ObjCMethodDecl *MD = getDecl(); 1133 if (!MD || !MD->isPropertyAccessor()) 1134 return nullptr; 1135 1136 // Note: This is potentially quite slow. 1137 return MD->findPropertyDecl(); 1138 } 1139 1140 bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl, 1141 Selector Sel) const { 1142 assert(IDecl); 1143 AnalysisManager &AMgr = 1144 getState()->getStateManager().getOwningEngine().getAnalysisManager(); 1145 // If the class interface is declared inside the main file, assume it is not 1146 // subcassed. 1147 // TODO: It could actually be subclassed if the subclass is private as well. 1148 // This is probably very rare. 1149 SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc(); 1150 if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc)) 1151 return false; 1152 1153 // Assume that property accessors are not overridden. 1154 if (getMessageKind() == OCM_PropertyAccess) 1155 return false; 1156 1157 // We assume that if the method is public (declared outside of main file) or 1158 // has a parent which publicly declares the method, the method could be 1159 // overridden in a subclass. 1160 1161 // Find the first declaration in the class hierarchy that declares 1162 // the selector. 1163 ObjCMethodDecl *D = nullptr; 1164 while (true) { 1165 D = IDecl->lookupMethod(Sel, true); 1166 1167 // Cannot find a public definition. 1168 if (!D) 1169 return false; 1170 1171 // If outside the main file, 1172 if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation())) 1173 return true; 1174 1175 if (D->isOverriding()) { 1176 // Search in the superclass on the next iteration. 1177 IDecl = D->getClassInterface(); 1178 if (!IDecl) 1179 return false; 1180 1181 IDecl = IDecl->getSuperClass(); 1182 if (!IDecl) 1183 return false; 1184 1185 continue; 1186 } 1187 1188 return false; 1189 }; 1190 1191 llvm_unreachable("The while loop should always terminate."); 1192 } 1193 1194 static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) { 1195 if (!MD) 1196 return MD; 1197 1198 // Find the redeclaration that defines the method. 1199 if (!MD->hasBody()) { 1200 for (auto I : MD->redecls()) 1201 if (I->hasBody()) 1202 MD = cast<ObjCMethodDecl>(I); 1203 } 1204 return MD; 1205 } 1206 1207 struct PrivateMethodKey { 1208 const ObjCInterfaceDecl *Interface; 1209 Selector LookupSelector; 1210 bool IsClassMethod; 1211 }; 1212 1213 namespace llvm { 1214 template <> struct DenseMapInfo<PrivateMethodKey> { 1215 using InterfaceInfo = DenseMapInfo<const ObjCInterfaceDecl *>; 1216 using SelectorInfo = DenseMapInfo<Selector>; 1217 1218 static inline PrivateMethodKey getEmptyKey() { 1219 return {InterfaceInfo::getEmptyKey(), SelectorInfo::getEmptyKey(), false}; 1220 } 1221 1222 static inline PrivateMethodKey getTombstoneKey() { 1223 return {InterfaceInfo::getTombstoneKey(), SelectorInfo::getTombstoneKey(), 1224 true}; 1225 } 1226 1227 static unsigned getHashValue(const PrivateMethodKey &Key) { 1228 return llvm::hash_combine( 1229 llvm::hash_code(InterfaceInfo::getHashValue(Key.Interface)), 1230 llvm::hash_code(SelectorInfo::getHashValue(Key.LookupSelector)), 1231 Key.IsClassMethod); 1232 } 1233 1234 static bool isEqual(const PrivateMethodKey &LHS, 1235 const PrivateMethodKey &RHS) { 1236 return InterfaceInfo::isEqual(LHS.Interface, RHS.Interface) && 1237 SelectorInfo::isEqual(LHS.LookupSelector, RHS.LookupSelector) && 1238 LHS.IsClassMethod == RHS.IsClassMethod; 1239 } 1240 }; 1241 } // end namespace llvm 1242 1243 static const ObjCMethodDecl * 1244 lookupRuntimeDefinition(const ObjCInterfaceDecl *Interface, 1245 Selector LookupSelector, bool InstanceMethod) { 1246 // Repeatedly calling lookupPrivateMethod() is expensive, especially 1247 // when in many cases it returns null. We cache the results so 1248 // that repeated queries on the same ObjCIntefaceDecl and Selector 1249 // don't incur the same cost. On some test cases, we can see the 1250 // same query being issued thousands of times. 1251 // 1252 // NOTE: This cache is essentially a "global" variable, but it 1253 // only gets lazily created when we get here. The value of the 1254 // cache probably comes from it being global across ExprEngines, 1255 // where the same queries may get issued. If we are worried about 1256 // concurrency, or possibly loading/unloading ASTs, etc., we may 1257 // need to revisit this someday. In terms of memory, this table 1258 // stays around until clang quits, which also may be bad if we 1259 // need to release memory. 1260 using PrivateMethodCache = 1261 llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>; 1262 1263 static PrivateMethodCache PMC; 1264 Optional<const ObjCMethodDecl *> &Val = 1265 PMC[{Interface, LookupSelector, InstanceMethod}]; 1266 1267 // Query lookupPrivateMethod() if the cache does not hit. 1268 if (!Val.hasValue()) { 1269 Val = Interface->lookupPrivateMethod(LookupSelector, InstanceMethod); 1270 1271 if (!*Val) { 1272 // Query 'lookupMethod' as a backup. 1273 Val = Interface->lookupMethod(LookupSelector, InstanceMethod); 1274 } 1275 } 1276 1277 return Val.getValue(); 1278 } 1279 1280 RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const { 1281 const ObjCMessageExpr *E = getOriginExpr(); 1282 assert(E); 1283 Selector Sel = E->getSelector(); 1284 1285 if (E->isInstanceMessage()) { 1286 // Find the receiver type. 1287 const ObjCObjectType *ReceiverT = nullptr; 1288 bool CanBeSubClassed = false; 1289 bool LookingForInstanceMethod = true; 1290 QualType SupersType = E->getSuperType(); 1291 const MemRegion *Receiver = nullptr; 1292 1293 if (!SupersType.isNull()) { 1294 // The receiver is guaranteed to be 'super' in this case. 1295 // Super always means the type of immediate predecessor to the method 1296 // where the call occurs. 1297 ReceiverT = cast<ObjCObjectPointerType>(SupersType)->getObjectType(); 1298 } else { 1299 Receiver = getReceiverSVal().getAsRegion(); 1300 if (!Receiver) 1301 return {}; 1302 1303 DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver); 1304 if (!DTI.isValid()) { 1305 assert(isa<AllocaRegion>(Receiver) && 1306 "Unhandled untyped region class!"); 1307 return {}; 1308 } 1309 1310 QualType DynType = DTI.getType(); 1311 CanBeSubClassed = DTI.canBeASubClass(); 1312 1313 const auto *ReceiverDynT = 1314 dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType()); 1315 1316 if (ReceiverDynT) { 1317 ReceiverT = ReceiverDynT->getObjectType(); 1318 1319 // It can be actually class methods called with Class object as a 1320 // receiver. This type of messages is treated by the compiler as 1321 // instance (not class). 1322 if (ReceiverT->isObjCClass()) { 1323 1324 SVal SelfVal = getState()->getSelfSVal(getLocationContext()); 1325 // For [self classMethod], return compiler visible declaration. 1326 if (Receiver == SelfVal.getAsRegion()) { 1327 return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl())); 1328 } 1329 1330 // Otherwise, let's check if we know something about the type 1331 // inside of this class object. 1332 if (SymbolRef ReceiverSym = getReceiverSVal().getAsSymbol()) { 1333 DynamicTypeInfo DTI = 1334 getClassObjectDynamicTypeInfo(getState(), ReceiverSym); 1335 if (DTI.isValid()) { 1336 // Let's use this type for lookup. 1337 ReceiverT = 1338 cast<ObjCObjectType>(DTI.getType().getCanonicalType()); 1339 1340 CanBeSubClassed = DTI.canBeASubClass(); 1341 // And it should be a class method instead. 1342 LookingForInstanceMethod = false; 1343 } 1344 } 1345 } 1346 1347 if (CanBeSubClassed) 1348 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) 1349 // Even if `DynamicTypeInfo` told us that it can be 1350 // not necessarily this type, but its descendants, we still want 1351 // to check again if this selector can be actually overridden. 1352 CanBeSubClassed = canBeOverridenInSubclass(IDecl, Sel); 1353 } 1354 } 1355 1356 // Lookup the instance method implementation. 1357 if (ReceiverT) 1358 if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterface()) { 1359 const ObjCMethodDecl *MD = 1360 lookupRuntimeDefinition(IDecl, Sel, LookingForInstanceMethod); 1361 1362 if (MD && !MD->hasBody()) 1363 MD = MD->getCanonicalDecl(); 1364 1365 if (CanBeSubClassed) 1366 return RuntimeDefinition(MD, Receiver); 1367 else 1368 return RuntimeDefinition(MD, nullptr); 1369 } 1370 } else { 1371 // This is a class method. 1372 // If we have type info for the receiver class, we are calling via 1373 // class name. 1374 if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) { 1375 // Find/Return the method implementation. 1376 return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel)); 1377 } 1378 } 1379 1380 return {}; 1381 } 1382 1383 bool ObjCMethodCall::argumentsMayEscape() const { 1384 if (isInSystemHeader() && !isInstanceMessage()) { 1385 Selector Sel = getSelector(); 1386 if (Sel.getNumArgs() == 1 && 1387 Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer")) 1388 return true; 1389 } 1390 1391 return CallEvent::argumentsMayEscape(); 1392 } 1393 1394 void ObjCMethodCall::getInitialStackFrameContents( 1395 const StackFrameContext *CalleeCtx, 1396 BindingsTy &Bindings) const { 1397 const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl()); 1398 SValBuilder &SVB = getState()->getStateManager().getSValBuilder(); 1399 addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this, 1400 D->parameters()); 1401 1402 SVal SelfVal = getReceiverSVal(); 1403 if (!SelfVal.isUnknown()) { 1404 const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl(); 1405 MemRegionManager &MRMgr = SVB.getRegionManager(); 1406 Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx)); 1407 Bindings.push_back(std::make_pair(SelfLoc, SelfVal)); 1408 } 1409 } 1410 1411 CallEventRef<> 1412 CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State, 1413 const LocationContext *LCtx) { 1414 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE)) 1415 return create<CXXMemberCall>(MCE, State, LCtx); 1416 1417 if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) { 1418 const FunctionDecl *DirectCallee = OpCE->getDirectCallee(); 1419 if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 1420 if (MD->isInstance()) 1421 return create<CXXMemberOperatorCall>(OpCE, State, LCtx); 1422 1423 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 1424 return create<BlockCall>(CE, State, LCtx); 1425 } 1426 1427 // Otherwise, it's a normal function call, static member function call, or 1428 // something we can't reason about. 1429 return create<SimpleFunctionCall>(CE, State, LCtx); 1430 } 1431 1432 CallEventRef<> 1433 CallEventManager::getCaller(const StackFrameContext *CalleeCtx, 1434 ProgramStateRef State) { 1435 const LocationContext *ParentCtx = CalleeCtx->getParent(); 1436 const LocationContext *CallerCtx = ParentCtx->getStackFrame(); 1437 assert(CallerCtx && "This should not be used for top-level stack frames"); 1438 1439 const Stmt *CallSite = CalleeCtx->getCallSite(); 1440 1441 if (CallSite) { 1442 if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx)) 1443 return Out; 1444 1445 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1446 const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl()); 1447 Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx); 1448 SVal ThisVal = State->getSVal(ThisPtr); 1449 1450 if (const auto *CE = dyn_cast<CXXConstructExpr>(CallSite)) 1451 return getCXXConstructorCall(CE, ThisVal.getAsRegion(), State, CallerCtx); 1452 else if (const auto *CIE = dyn_cast<CXXInheritedCtorInitExpr>(CallSite)) 1453 return getCXXInheritedConstructorCall(CIE, ThisVal.getAsRegion(), State, 1454 CallerCtx); 1455 else { 1456 // All other cases are handled by getCall. 1457 llvm_unreachable("This is not an inlineable statement"); 1458 } 1459 } 1460 1461 // Fall back to the CFG. The only thing we haven't handled yet is 1462 // destructors, though this could change in the future. 1463 const CFGBlock *B = CalleeCtx->getCallSiteBlock(); 1464 CFGElement E = (*B)[CalleeCtx->getIndex()]; 1465 assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) && 1466 "All other CFG elements should have exprs"); 1467 1468 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 1469 const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl()); 1470 Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx); 1471 SVal ThisVal = State->getSVal(ThisPtr); 1472 1473 const Stmt *Trigger; 1474 if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>()) 1475 Trigger = AutoDtor->getTriggerStmt(); 1476 else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>()) 1477 Trigger = DeleteDtor->getDeleteExpr(); 1478 else 1479 Trigger = Dtor->getBody(); 1480 1481 return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(), 1482 E.getAs<CFGBaseDtor>().hasValue(), State, 1483 CallerCtx); 1484 } 1485 1486 CallEventRef<> CallEventManager::getCall(const Stmt *S, ProgramStateRef State, 1487 const LocationContext *LC) { 1488 if (const auto *CE = dyn_cast<CallExpr>(S)) { 1489 return getSimpleCall(CE, State, LC); 1490 } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) { 1491 return getCXXAllocatorCall(NE, State, LC); 1492 } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) { 1493 return getObjCMethodCall(ME, State, LC); 1494 } else { 1495 return nullptr; 1496 } 1497 } 1498