ExprEngineCallAndReturn.cpp revision 3bbd8cd831788c506f2980293eb3c7e1b3ca2501
1//=-- ExprEngineCallAndReturn.cpp - Support for call/return -----*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines ExprEngine's support for calls and returns. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/StaticAnalyzer/Core/CheckerManager.h" 15#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 16#include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h" 17#include "llvm/Support/SaveAndRestore.h" 18#include "clang/AST/DeclCXX.h" 19 20using namespace clang; 21using namespace ento; 22 23void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) { 24 // Get the entry block in the CFG of the callee. 25 const StackFrameContext *calleeCtx = CE.getCalleeContext(); 26 const CFG *CalleeCFG = calleeCtx->getCFG(); 27 const CFGBlock *Entry = &(CalleeCFG->getEntry()); 28 29 // Validate the CFG. 30 assert(Entry->empty()); 31 assert(Entry->succ_size() == 1); 32 33 // Get the solitary sucessor. 34 const CFGBlock *Succ = *(Entry->succ_begin()); 35 36 // Construct an edge representing the starting location in the callee. 37 BlockEdge Loc(Entry, Succ, calleeCtx); 38 39 // Construct a new state which contains the mapping from actual to 40 // formal arguments. 41 const LocationContext *callerCtx = Pred->getLocationContext(); 42 ProgramStateRef state = Pred->getState()->enterStackFrame(callerCtx, 43 calleeCtx); 44 45 // Construct a new node and add it to the worklist. 46 bool isNew; 47 ExplodedNode *Node = G.getNode(Loc, state, false, &isNew); 48 Node->addPredecessor(Pred, G); 49 if (isNew) 50 Engine.getWorkList()->enqueue(Node); 51} 52 53static const ReturnStmt *getReturnStmt(const ExplodedNode *Node) { 54 while (Node) { 55 const ProgramPoint &PP = Node->getLocation(); 56 // Skip any BlockEdges. 57 if (isa<BlockEdge>(PP) || isa<CallExit>(PP)) { 58 assert(Node->pred_size() == 1); 59 Node = *Node->pred_begin(); 60 continue; 61 } 62 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) { 63 const Stmt *S = SP->getStmt(); 64 return dyn_cast<ReturnStmt>(S); 65 } 66 break; 67 } 68 return 0; 69} 70 71void ExprEngine::processCallExit(ExplodedNode *Pred) { 72 ProgramStateRef state = Pred->getState(); 73 const StackFrameContext *calleeCtx = 74 Pred->getLocationContext()->getCurrentStackFrame(); 75 const LocationContext *callerCtx = calleeCtx->getParent(); 76 const Stmt *CE = calleeCtx->getCallSite(); 77 78 // If the callee returns an expression, bind its value to CallExpr. 79 if (const ReturnStmt *RS = getReturnStmt(Pred)) { 80 const LocationContext *LCtx = Pred->getLocationContext(); 81 SVal V = state->getSVal(RS, LCtx); 82 state = state->BindExpr(CE, callerCtx, V); 83 } 84 85 // Bind the constructed object value to CXXConstructExpr. 86 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 87 const CXXThisRegion *ThisR = 88 getCXXThisRegion(CCE->getConstructor()->getParent(), calleeCtx); 89 90 SVal ThisV = state->getSVal(ThisR); 91 // Always bind the region to the CXXConstructExpr. 92 state = state->BindExpr(CCE, Pred->getLocationContext(), ThisV); 93 } 94 95 static SimpleProgramPointTag returnTag("ExprEngine : Call Return"); 96 PostStmt Loc(CE, callerCtx, &returnTag); 97 bool isNew; 98 ExplodedNode *N = G.getNode(Loc, state, false, &isNew); 99 N->addPredecessor(Pred, G); 100 if (!isNew) 101 return; 102 103 // Perform the post-condition check of the CallExpr. 104 ExplodedNodeSet Dst; 105 NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), N); 106 SaveAndRestore<const NodeBuilderContext*> NBCSave(currentBuilderContext, 107 &Ctx); 108 SaveAndRestore<unsigned> CBISave(currentStmtIdx, calleeCtx->getIndex()); 109 110 getCheckerManager().runCheckersForPostStmt(Dst, N, CE, *this, 111 /* wasInlined */ true); 112 113 // Enqueue the next element in the block. 114 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); I != E; ++I) { 115 Engine.getWorkList()->enqueue(*I, 116 calleeCtx->getCallSiteBlock(), 117 calleeCtx->getIndex()+1); 118 } 119} 120 121static unsigned getNumberStackFrames(const LocationContext *LCtx) { 122 unsigned count = 0; 123 while (LCtx) { 124 if (isa<StackFrameContext>(LCtx)) 125 ++count; 126 LCtx = LCtx->getParent(); 127 } 128 return count; 129} 130 131// Determine if we should inline the call. 132bool ExprEngine::shouldInlineDecl(const FunctionDecl *FD, ExplodedNode *Pred) { 133 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(FD); 134 const CFG *CalleeCFG = CalleeADC->getCFG(); 135 136 if (getNumberStackFrames(Pred->getLocationContext()) 137 == AMgr.InlineMaxStackDepth) 138 return false; 139 140 if (FunctionSummaries->hasReachedMaxBlockCount(FD)) 141 return false; 142 143 if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize) 144 return false; 145 146 return true; 147} 148 149// For now, skip inlining variadic functions. 150// We also don't inline blocks. 151static bool shouldInlineCallExpr(const CallExpr *CE, ExprEngine *E) { 152 if (!E->getAnalysisManager().shouldInlineCall()) 153 return false; 154 QualType callee = CE->getCallee()->getType(); 155 const FunctionProtoType *FT = 0; 156 if (const PointerType *PT = callee->getAs<PointerType>()) 157 FT = dyn_cast<FunctionProtoType>(PT->getPointeeType()); 158 else if (const BlockPointerType *BT = callee->getAs<BlockPointerType>()) { 159 // FIXME: inline blocks. 160 // FT = dyn_cast<FunctionProtoType>(BT->getPointeeType()); 161 (void) BT; 162 return false; 163 } 164 // If we have no prototype, assume the function is okay. 165 if (!FT) 166 return true; 167 168 // Skip inlining of variadic functions. 169 return !FT->isVariadic(); 170} 171 172bool ExprEngine::InlineCall(ExplodedNodeSet &Dst, 173 const CallExpr *CE, 174 ExplodedNode *Pred) { 175 if (!shouldInlineCallExpr(CE, this)) 176 return false; 177 178 ProgramStateRef state = Pred->getState(); 179 const Expr *Callee = CE->getCallee(); 180 const FunctionDecl *FD = 181 state->getSVal(Callee, Pred->getLocationContext()).getAsFunctionDecl(); 182 if (!FD || !FD->hasBody(FD)) 183 return false; 184 185 switch (CE->getStmtClass()) { 186 default: 187 // FIXME: Handle C++. 188 break; 189 case Stmt::CallExprClass: { 190 if (!shouldInlineDecl(FD, Pred)) 191 return false; 192 193 // Construct a new stack frame for the callee. 194 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(FD); 195 const StackFrameContext *CallerSFC = 196 Pred->getLocationContext()->getCurrentStackFrame(); 197 const StackFrameContext *CalleeSFC = 198 CalleeADC->getStackFrame(CallerSFC, CE, 199 currentBuilderContext->getBlock(), 200 currentStmtIdx); 201 202 CallEnter Loc(CE, CalleeSFC, Pred->getLocationContext()); 203 bool isNew; 204 ExplodedNode *N = G.getNode(Loc, state, false, &isNew); 205 N->addPredecessor(Pred, G); 206 if (isNew) 207 Engine.getWorkList()->enqueue(N); 208 return true; 209 } 210 } 211 return false; 212} 213 214static bool isPointerToConst(const ParmVarDecl *ParamDecl) { 215 QualType PointeeTy = ParamDecl->getOriginalType()->getPointeeType(); 216 if (PointeeTy != QualType() && PointeeTy.isConstQualified() && 217 !PointeeTy->isAnyPointerType() && !PointeeTy->isReferenceType()) { 218 return true; 219 } 220 return false; 221} 222 223// Try to retrieve the function declaration and find the function parameter 224// types which are pointers/references to a non-pointer const. 225// We do not invalidate the corresponding argument regions. 226static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs, 227 const CallOrObjCMessage &Call) { 228 const Decl *CallDecl = Call.getDecl(); 229 if (!CallDecl) 230 return; 231 232 if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(CallDecl)) { 233 const IdentifierInfo *II = FDecl->getIdentifier(); 234 235 // List the cases, where the region should be invalidated even if the 236 // argument is const. 237 if (II) { 238 StringRef FName = II->getName(); 239 // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a 240 // value into thread local storage. The value can later be retrieved with 241 // 'void *ptheread_getspecific(pthread_key)'. So even thought the 242 // parameter is 'const void *', the region escapes through the call. 243 // - funopen - sets a buffer for future IO calls. 244 // - ObjC functions that end with "NoCopy" can free memory, of the passed 245 // in buffer. 246 // - Many CF containers allow objects to escape through custom 247 // allocators/deallocators upon container construction. 248 if (FName == "pthread_setspecific" || 249 FName == "funopen" || 250 FName.endswith("NoCopy") || 251 Call.isCFCGAllowingEscape(FName)) 252 return; 253 } 254 255 for (unsigned Idx = 0, E = Call.getNumArgs(); Idx != E; ++Idx) { 256 if (FDecl && Idx < FDecl->getNumParams()) { 257 if (isPointerToConst(FDecl->getParamDecl(Idx))) 258 PreserveArgs.insert(Idx); 259 } 260 } 261 return; 262 } 263 264 if (const ObjCMethodDecl *MDecl = dyn_cast<ObjCMethodDecl>(CallDecl)) { 265 assert(MDecl->param_size() <= Call.getNumArgs()); 266 unsigned Idx = 0; 267 for (clang::ObjCMethodDecl::param_const_iterator 268 I = MDecl->param_begin(), E = MDecl->param_end(); I != E; ++I, ++Idx) { 269 if (isPointerToConst(*I)) 270 PreserveArgs.insert(Idx); 271 } 272 return; 273 } 274} 275 276ProgramStateRef 277ExprEngine::invalidateArguments(ProgramStateRef State, 278 const CallOrObjCMessage &Call, 279 const LocationContext *LC) { 280 SmallVector<const MemRegion *, 8> RegionsToInvalidate; 281 282 if (Call.isObjCMessage()) { 283 // Invalidate all instance variables of the receiver of an ObjC message. 284 // FIXME: We should be able to do better with inter-procedural analysis. 285 if (const MemRegion *MR = Call.getInstanceMessageReceiver(LC).getAsRegion()) 286 RegionsToInvalidate.push_back(MR); 287 288 } else if (Call.isCXXCall()) { 289 // Invalidate all instance variables for the callee of a C++ method call. 290 // FIXME: We should be able to do better with inter-procedural analysis. 291 // FIXME: We can probably do better for const versus non-const methods. 292 if (const MemRegion *Callee = Call.getCXXCallee().getAsRegion()) 293 RegionsToInvalidate.push_back(Callee); 294 295 } else if (Call.isFunctionCall()) { 296 // Block calls invalidate all captured-by-reference values. 297 SVal CalleeVal = Call.getFunctionCallee(); 298 if (const MemRegion *Callee = CalleeVal.getAsRegion()) { 299 if (isa<BlockDataRegion>(Callee)) 300 RegionsToInvalidate.push_back(Callee); 301 } 302 } 303 304 // Indexes of arguments whose values will be preserved by the call. 305 llvm::SmallSet<unsigned, 1> PreserveArgs; 306 findPtrToConstParams(PreserveArgs, Call); 307 308 for (unsigned idx = 0, e = Call.getNumArgs(); idx != e; ++idx) { 309 if (PreserveArgs.count(idx)) 310 continue; 311 312 SVal V = Call.getArgSVal(idx); 313 314 // If we are passing a location wrapped as an integer, unwrap it and 315 // invalidate the values referred by the location. 316 if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V)) 317 V = Wrapped->getLoc(); 318 else if (!isa<Loc>(V)) 319 continue; 320 321 if (const MemRegion *R = V.getAsRegion()) { 322 // Invalidate the value of the variable passed by reference. 323 324 // Are we dealing with an ElementRegion? If the element type is 325 // a basic integer type (e.g., char, int) and the underlying region 326 // is a variable region then strip off the ElementRegion. 327 // FIXME: We really need to think about this for the general case 328 // as sometimes we are reasoning about arrays and other times 329 // about (char*), etc., is just a form of passing raw bytes. 330 // e.g., void *p = alloca(); foo((char*)p); 331 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) { 332 // Checking for 'integral type' is probably too promiscuous, but 333 // we'll leave it in for now until we have a systematic way of 334 // handling all of these cases. Eventually we need to come up 335 // with an interface to StoreManager so that this logic can be 336 // appropriately delegated to the respective StoreManagers while 337 // still allowing us to do checker-specific logic (e.g., 338 // invalidating reference counts), probably via callbacks. 339 if (ER->getElementType()->isIntegralOrEnumerationType()) { 340 const MemRegion *superReg = ER->getSuperRegion(); 341 if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) || 342 isa<ObjCIvarRegion>(superReg)) 343 R = cast<TypedRegion>(superReg); 344 } 345 // FIXME: What about layers of ElementRegions? 346 } 347 348 // Mark this region for invalidation. We batch invalidate regions 349 // below for efficiency. 350 RegionsToInvalidate.push_back(R); 351 } else { 352 // Nuke all other arguments passed by reference. 353 // FIXME: is this necessary or correct? This handles the non-Region 354 // cases. Is it ever valid to store to these? 355 State = State->unbindLoc(cast<Loc>(V)); 356 } 357 } 358 359 // Invalidate designated regions using the batch invalidation API. 360 361 // FIXME: We can have collisions on the conjured symbol if the 362 // expression *I also creates conjured symbols. We probably want 363 // to identify conjured symbols by an expression pair: the enclosing 364 // expression (the context) and the expression itself. This should 365 // disambiguate conjured symbols. 366 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 367 StoreManager::InvalidatedSymbols IS; 368 369 // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate 370 // global variables. 371 return State->invalidateRegions(RegionsToInvalidate, 372 Call.getOriginExpr(), Count, LC, 373 &IS, &Call); 374 375} 376 377static ProgramStateRef getReplayWithoutInliningState(ExplodedNode *&N, 378 const CallExpr *CE) { 379 void *ReplayState = N->getState()->get<ReplayWithoutInlining>(); 380 if (!ReplayState) 381 return 0; 382 const CallExpr *ReplayCE = reinterpret_cast<const CallExpr*>(ReplayState); 383 if (CE == ReplayCE) { 384 return N->getState()->remove<ReplayWithoutInlining>(); 385 } 386 return 0; 387} 388 389void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 390 ExplodedNodeSet &dst) { 391 // Perform the previsit of the CallExpr. 392 ExplodedNodeSet dstPreVisit; 393 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this); 394 395 // Now evaluate the call itself. 396 class DefaultEval : public GraphExpander { 397 ExprEngine &Eng; 398 const CallExpr *CE; 399 public: 400 401 DefaultEval(ExprEngine &eng, const CallExpr *ce) 402 : Eng(eng), CE(ce) {} 403 virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) { 404 405 ProgramStateRef state = getReplayWithoutInliningState(Pred, CE); 406 407 // First, try to inline the call. 408 if (state == 0 && Eng.InlineCall(Dst, CE, Pred)) 409 return; 410 411 // First handle the return value. 412 StmtNodeBuilder Bldr(Pred, Dst, *Eng.currentBuilderContext); 413 414 // Get the callee. 415 const Expr *Callee = CE->getCallee()->IgnoreParens(); 416 if (state == 0) 417 state = Pred->getState(); 418 SVal L = state->getSVal(Callee, Pred->getLocationContext()); 419 420 // Figure out the result type. We do this dance to handle references. 421 QualType ResultTy; 422 if (const FunctionDecl *FD = L.getAsFunctionDecl()) 423 ResultTy = FD->getResultType(); 424 else 425 ResultTy = CE->getType(); 426 427 if (CE->isLValue()) 428 ResultTy = Eng.getContext().getPointerType(ResultTy); 429 430 // Conjure a symbol value to use as the result. 431 SValBuilder &SVB = Eng.getSValBuilder(); 432 unsigned Count = Eng.currentBuilderContext->getCurrentBlockCount(); 433 const LocationContext *LCtx = Pred->getLocationContext(); 434 SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count); 435 436 // Generate a new state with the return value set. 437 state = state->BindExpr(CE, LCtx, RetVal); 438 439 // Invalidate the arguments. 440 state = Eng.invalidateArguments(state, CallOrObjCMessage(CE, state, LCtx), 441 LCtx); 442 443 // And make the result node. 444 Bldr.generateNode(CE, Pred, state); 445 } 446 }; 447 448 // Finally, evaluate the function call. We try each of the checkers 449 // to see if the can evaluate the function call. 450 ExplodedNodeSet dstCallEvaluated; 451 DefaultEval defEval(*this, CE); 452 getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, 453 dstPreVisit, 454 CE, *this, &defEval); 455 456 // Finally, perform the post-condition check of the CallExpr and store 457 // the created nodes in 'Dst'. 458 getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE, 459 *this); 460} 461 462void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 463 ExplodedNodeSet &Dst) { 464 465 ExplodedNodeSet dstPreVisit; 466 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this); 467 468 StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext); 469 470 if (RS->getRetValue()) { 471 for (ExplodedNodeSet::iterator it = dstPreVisit.begin(), 472 ei = dstPreVisit.end(); it != ei; ++it) { 473 B.generateNode(RS, *it, (*it)->getState()); 474 } 475 } 476} 477