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