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