ExprEngineCallAndReturn.cpp revision 9dc5167e4017ef4c8b327abb6f72225eec2e0f19
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/Analysis/Analyses/LiveVariables.h" 15#include "clang/StaticAnalyzer/Core/CheckerManager.h" 16#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 17#include "clang/StaticAnalyzer/Core/PathSensitive/Calls.h" 18#include "clang/AST/DeclCXX.h" 19#include "llvm/ADT/SmallSet.h" 20#include "llvm/Support/SaveAndRestore.h" 21 22using namespace clang; 23using namespace ento; 24 25static CallEventKind classifyCallExpr(const CallExpr *CE) { 26 if (isa<CXXMemberCallExpr>(CE)) 27 return CE_CXXMember; 28 29 const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE); 30 if (OpCE) { 31 const FunctionDecl *DirectCallee = CE->getDirectCallee(); 32 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee)) 33 if (MD->isInstance()) 34 return CE_CXXMemberOperator; 35 } else if (CE->getCallee()->getType()->isBlockPointerType()) { 36 return CE_Block; 37 } 38 39 return CE_Function; 40} 41 42void ExprEngine::processCallEnter(CallEnter CE, ExplodedNode *Pred) { 43 // Get the entry block in the CFG of the callee. 44 const StackFrameContext *calleeCtx = CE.getCalleeContext(); 45 const CFG *CalleeCFG = calleeCtx->getCFG(); 46 const CFGBlock *Entry = &(CalleeCFG->getEntry()); 47 48 // Validate the CFG. 49 assert(Entry->empty()); 50 assert(Entry->succ_size() == 1); 51 52 // Get the solitary sucessor. 53 const CFGBlock *Succ = *(Entry->succ_begin()); 54 55 // Construct an edge representing the starting location in the callee. 56 BlockEdge Loc(Entry, Succ, calleeCtx); 57 58 ProgramStateRef state = Pred->getState(); 59 60 // Construct a new node and add it to the worklist. 61 bool isNew; 62 ExplodedNode *Node = G.getNode(Loc, state, false, &isNew); 63 Node->addPredecessor(Pred, G); 64 if (isNew) 65 Engine.getWorkList()->enqueue(Node); 66} 67 68// Find the last statement on the path to the exploded node and the 69// corresponding Block. 70static std::pair<const Stmt*, 71 const CFGBlock*> getLastStmt(const ExplodedNode *Node) { 72 const Stmt *S = 0; 73 const CFGBlock *Blk = 0; 74 const StackFrameContext *SF = 75 Node->getLocation().getLocationContext()->getCurrentStackFrame(); 76 while (Node) { 77 const ProgramPoint &PP = Node->getLocation(); 78 // Skip any BlockEdges, empty blocks, and the CallExitBegin node. 79 if (isa<BlockEdge>(PP) || isa<CallExitBegin>(PP) || isa<BlockEntrance>(PP)){ 80 assert(Node->pred_size() == 1); 81 Node = *Node->pred_begin(); 82 continue; 83 } 84 // If we reached the CallEnter, the function has no statements. 85 if (isa<CallEnter>(PP)) 86 break; 87 if (const StmtPoint *SP = dyn_cast<StmtPoint>(&PP)) { 88 S = SP->getStmt(); 89 // Now, get the enclosing basic block. 90 while (Node && Node->pred_size() >=1 ) { 91 const ProgramPoint &PP = Node->getLocation(); 92 if (isa<BlockEdge>(PP) && 93 (PP.getLocationContext()->getCurrentStackFrame() == SF)) { 94 BlockEdge &EPP = cast<BlockEdge>(PP); 95 Blk = EPP.getDst(); 96 break; 97 } 98 Node = *Node->pred_begin(); 99 } 100 break; 101 } 102 break; 103 } 104 return std::pair<const Stmt*, const CFGBlock*>(S, Blk); 105} 106 107/// The call exit is simulated with a sequence of nodes, which occur between 108/// CallExitBegin and CallExitEnd. The following operations occur between the 109/// two program points: 110/// 1. CallExitBegin (triggers the start of call exit sequence) 111/// 2. Bind the return value 112/// 3. Run Remove dead bindings to clean up the dead symbols from the callee. 113/// 4. CallExitEnd (switch to the caller context) 114/// 5. PostStmt<CallExpr> 115void ExprEngine::processCallExit(ExplodedNode *CEBNode) { 116 // Step 1 CEBNode was generated before the call. 117 118 const StackFrameContext *calleeCtx = 119 CEBNode->getLocationContext()->getCurrentStackFrame(); 120 121 // The parent context might not be a stack frame, so make sure we 122 // look up the first enclosing stack frame. 123 const StackFrameContext *callerCtx = 124 calleeCtx->getParent()->getCurrentStackFrame(); 125 126 const Stmt *CE = calleeCtx->getCallSite(); 127 ProgramStateRef state = CEBNode->getState(); 128 // Find the last statement in the function and the corresponding basic block. 129 const Stmt *LastSt = 0; 130 const CFGBlock *Blk = 0; 131 llvm::tie(LastSt, Blk) = getLastStmt(CEBNode); 132 133 // Step 2: generate node with bound return value: CEBNode -> BindedRetNode. 134 135 // If the callee returns an expression, bind its value to CallExpr. 136 if (CE) { 137 if (const ReturnStmt *RS = dyn_cast_or_null<ReturnStmt>(LastSt)) { 138 const LocationContext *LCtx = CEBNode->getLocationContext(); 139 SVal V = state->getSVal(RS, LCtx); 140 state = state->BindExpr(CE, calleeCtx->getParent(), V); 141 } 142 143 // Bind the constructed object value to CXXConstructExpr. 144 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(CE)) { 145 loc::MemRegionVal This = 146 svalBuilder.getCXXThis(CCE->getConstructor()->getParent(), calleeCtx); 147 SVal ThisV = state->getSVal(This); 148 149 // Always bind the region to the CXXConstructExpr. 150 state = state->BindExpr(CCE, calleeCtx->getParent(), ThisV); 151 } 152 } 153 154 // Step 3: BindedRetNode -> CleanedNodes 155 // If we can find a statement and a block in the inlined function, run remove 156 // dead bindings before returning from the call. This is important to ensure 157 // that we report the issues such as leaks in the stack contexts in which 158 // they occurred. 159 ExplodedNodeSet CleanedNodes; 160 if (LastSt && Blk) { 161 static SimpleProgramPointTag retValBind("ExprEngine : Bind Return Value"); 162 PostStmt Loc(LastSt, calleeCtx, &retValBind); 163 bool isNew; 164 ExplodedNode *BindedRetNode = G.getNode(Loc, state, false, &isNew); 165 BindedRetNode->addPredecessor(CEBNode, G); 166 if (!isNew) 167 return; 168 169 NodeBuilderContext Ctx(getCoreEngine(), Blk, BindedRetNode); 170 currentBuilderContext = &Ctx; 171 // Here, we call the Symbol Reaper with 0 statement and caller location 172 // context, telling it to clean up everything in the callee's context 173 // (and it's children). We use LastStmt as a diagnostic statement, which 174 // which the PreStmtPurge Dead point will be associated. 175 removeDead(BindedRetNode, CleanedNodes, 0, callerCtx, LastSt, 176 ProgramPoint::PostStmtPurgeDeadSymbolsKind); 177 currentBuilderContext = 0; 178 } else { 179 CleanedNodes.Add(CEBNode); 180 } 181 182 for (ExplodedNodeSet::iterator I = CleanedNodes.begin(), 183 E = CleanedNodes.end(); I != E; ++I) { 184 185 // Step 4: Generate the CallExit and leave the callee's context. 186 // CleanedNodes -> CEENode 187 CallExitEnd Loc(calleeCtx, callerCtx); 188 bool isNew; 189 ProgramStateRef CEEState = (*I == CEBNode) ? state : (*I)->getState(); 190 ExplodedNode *CEENode = G.getNode(Loc, CEEState, false, &isNew); 191 CEENode->addPredecessor(*I, G); 192 if (!isNew) 193 return; 194 195 // Step 5: Perform the post-condition check of the CallExpr and enqueue the 196 // result onto the work list. 197 // CEENode -> Dst -> WorkList 198 ExplodedNodeSet Dst; 199 NodeBuilderContext Ctx(Engine, calleeCtx->getCallSiteBlock(), CEENode); 200 SaveAndRestore<const NodeBuilderContext*> NBCSave(currentBuilderContext, 201 &Ctx); 202 SaveAndRestore<unsigned> CBISave(currentStmtIdx, calleeCtx->getIndex()); 203 204 // FIXME: This needs to call PostCall. 205 // FIXME: If/when we inline Objective-C messages, this also needs to call 206 // PostObjCMessage. 207 if (CE) 208 getCheckerManager().runCheckersForPostStmt(Dst, CEENode, CE, *this, true); 209 else 210 Dst.Add(CEENode); 211 212 // Enqueue the next element in the block. 213 for (ExplodedNodeSet::iterator PSI = Dst.begin(), PSE = Dst.end(); 214 PSI != PSE; ++PSI) { 215 Engine.getWorkList()->enqueue(*PSI, calleeCtx->getCallSiteBlock(), 216 calleeCtx->getIndex()+1); 217 } 218 } 219} 220 221static unsigned getNumberStackFrames(const LocationContext *LCtx) { 222 unsigned count = 0; 223 while (LCtx) { 224 if (isa<StackFrameContext>(LCtx)) 225 ++count; 226 LCtx = LCtx->getParent(); 227 } 228 return count; 229} 230 231// Determine if we should inline the call. 232bool ExprEngine::shouldInlineDecl(const Decl *D, ExplodedNode *Pred) { 233 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D); 234 const CFG *CalleeCFG = CalleeADC->getCFG(); 235 236 // It is possible that the CFG cannot be constructed. 237 // Be safe, and check if the CalleeCFG is valid. 238 if (!CalleeCFG) 239 return false; 240 241 if (getNumberStackFrames(Pred->getLocationContext()) 242 == AMgr.InlineMaxStackDepth) 243 return false; 244 245 if (Engine.FunctionSummaries->hasReachedMaxBlockCount(D)) 246 return false; 247 248 if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize) 249 return false; 250 251 // Do not inline variadic calls (for now). 252 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 253 if (BD->isVariadic()) 254 return false; 255 } 256 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 257 if (FD->isVariadic()) 258 return false; 259 } 260 261 // It is possible that the live variables analysis cannot be 262 // run. If so, bail out. 263 if (!CalleeADC->getAnalysis<RelaxedLiveVariables>()) 264 return false; 265 266 return true; 267} 268 269bool ExprEngine::inlineCall(const CallEvent &Call, 270 ExplodedNode *Pred) { 271 if (!getAnalysisManager().shouldInlineCall()) 272 return false; 273 274 const Decl *D = Call.getRuntimeDefinition(); 275 if (!D) 276 return false; 277 278 const LocationContext *CurLC = Pred->getLocationContext(); 279 const StackFrameContext *CallerSFC = CurLC->getCurrentStackFrame(); 280 const LocationContext *ParentOfCallee = 0; 281 282 switch (Call.getKind()) { 283 case CE_Function: 284 case CE_CXXMember: 285 case CE_CXXMemberOperator: 286 // These are always at least possible to inline. 287 break; 288 case CE_CXXConstructor: 289 case CE_CXXDestructor: 290 // Do not inline constructors until we can really model destructors. 291 // This is unfortunate, but basically necessary for smart pointers and such. 292 return false; 293 case CE_CXXAllocator: 294 // Do not inline allocators until we model deallocators. 295 // This is unfortunate, but basically necessary for smart pointers and such. 296 return false; 297 case CE_Block: { 298 const BlockDataRegion *BR = cast<BlockCall>(Call).getBlockRegion(); 299 assert(BR && "If we have the block definition we should have its region"); 300 AnalysisDeclContext *BlockCtx = AMgr.getAnalysisDeclContext(D); 301 ParentOfCallee = BlockCtx->getBlockInvocationContext(CallerSFC, 302 cast<BlockDecl>(D), 303 BR); 304 break; 305 } 306 case CE_ObjCMessage: 307 break; 308 } 309 310 if (!shouldInlineDecl(D, Pred)) 311 return false; 312 313 if (!ParentOfCallee) 314 ParentOfCallee = CallerSFC; 315 316 // This may be NULL, but that's fine. 317 const Expr *CallE = Call.getOriginExpr(); 318 319 // Construct a new stack frame for the callee. 320 AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(D); 321 const StackFrameContext *CalleeSFC = 322 CalleeADC->getStackFrame(ParentOfCallee, CallE, 323 currentBuilderContext->getBlock(), 324 currentStmtIdx); 325 326 CallEnter Loc(CallE, CalleeSFC, CurLC); 327 328 // Construct a new state which contains the mapping from actual to 329 // formal arguments. 330 ProgramStateRef State = Pred->getState()->enterStackFrame(Call, CalleeSFC); 331 332 bool isNew; 333 if (ExplodedNode *N = G.getNode(Loc, State, false, &isNew)) { 334 N->addPredecessor(Pred, G); 335 if (isNew) 336 Engine.getWorkList()->enqueue(N); 337 } 338 return true; 339} 340 341static ProgramStateRef getInlineFailedState(ProgramStateRef State, 342 const Stmt *CallE) { 343 void *ReplayState = State->get<ReplayWithoutInlining>(); 344 if (!ReplayState) 345 return 0; 346 347 assert(ReplayState == (const void*)CallE && "Backtracked to the wrong call."); 348 (void)CallE; 349 350 return State->remove<ReplayWithoutInlining>(); 351} 352 353void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred, 354 ExplodedNodeSet &dst) { 355 // Perform the previsit of the CallExpr. 356 ExplodedNodeSet dstPreVisit; 357 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this); 358 359 // Get the callee kind. 360 CallEventKind K = classifyCallExpr(CE); 361 362 // Evaluate the function call. We try each of the checkers 363 // to see if the can evaluate the function call. 364 ExplodedNodeSet dstCallEvaluated; 365 for (ExplodedNodeSet::iterator I = dstPreVisit.begin(), E = dstPreVisit.end(); 366 I != E; ++I) { 367 ProgramStateRef State = (*I)->getState(); 368 const LocationContext *LCtx = (*I)->getLocationContext(); 369 370 // Evaluate the call. 371 switch (K) { 372 case CE_Function: 373 evalCall(dstCallEvaluated, *I, FunctionCall(CE, State, LCtx)); 374 break; 375 case CE_CXXMember: 376 evalCall(dstCallEvaluated, *I, CXXMemberCall(cast<CXXMemberCallExpr>(CE), 377 State, LCtx)); 378 break; 379 case CE_CXXMemberOperator: 380 evalCall(dstCallEvaluated, *I, 381 CXXMemberOperatorCall(cast<CXXOperatorCallExpr>(CE), 382 State, LCtx)); 383 break; 384 case CE_Block: 385 evalCall(dstCallEvaluated, *I, BlockCall(CE, State, LCtx)); 386 break; 387 default: 388 llvm_unreachable("Non-CallExpr CallEventKind"); 389 } 390 } 391 392 // Finally, perform the post-condition check of the CallExpr and store 393 // the created nodes in 'Dst'. 394 // Note that if the call was inlined, dstCallEvaluated will be empty. 395 // The post-CallExpr check will occur in processCallExit. 396 getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE, 397 *this); 398} 399 400void ExprEngine::evalCall(ExplodedNodeSet &Dst, ExplodedNode *Pred, 401 const SimpleCall &Call) { 402 // Run any pre-call checks using the generic call interface. 403 ExplodedNodeSet dstPreVisit; 404 getCheckerManager().runCheckersForPreCall(dstPreVisit, Pred, Call, *this); 405 406 // Actually evaluate the function call. We try each of the checkers 407 // to see if the can evaluate the function call, and get a callback at 408 // defaultEvalCall if all of them fail. 409 ExplodedNodeSet dstCallEvaluated; 410 getCheckerManager().runCheckersForEvalCall(dstCallEvaluated, dstPreVisit, 411 Call, *this); 412 413 // Finally, run any post-call checks. 414 getCheckerManager().runCheckersForPostCall(Dst, dstCallEvaluated, 415 Call, *this); 416} 417 418ProgramStateRef ExprEngine::bindReturnValue(const CallEvent &Call, 419 const LocationContext *LCtx, 420 ProgramStateRef State) { 421 const Expr *E = Call.getOriginExpr(); 422 if (!E) 423 return State; 424 425 // Some method families have known return values. 426 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(&Call)) { 427 switch (Msg->getMethodFamily()) { 428 default: 429 break; 430 case OMF_autorelease: 431 case OMF_retain: 432 case OMF_self: { 433 // These methods return their receivers. 434 return State->BindExpr(E, LCtx, Msg->getReceiverSVal()); 435 } 436 } 437 } 438 439 // Conjure a symbol if the return value is unknown. 440 QualType ResultTy = Call.getResultType(); 441 SValBuilder &SVB = getSValBuilder(); 442 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 443 SVal R = SVB.getConjuredSymbolVal(0, E, LCtx, ResultTy, Count); 444 return State->BindExpr(E, LCtx, R); 445} 446 447void ExprEngine::defaultEvalCall(NodeBuilder &Bldr, ExplodedNode *Pred, 448 const CallEvent &Call) { 449 ProgramStateRef State = 0; 450 const Expr *E = Call.getOriginExpr(); 451 452 // Try to inline the call. 453 // The origin expression here is just used as a kind of checksum; 454 // for CallEvents that do not have origin expressions, this should still be 455 // safe. 456 State = getInlineFailedState(Pred->getState(), E); 457 if (State == 0 && inlineCall(Call, Pred)) { 458 // If we inlined the call, the successor has been manually added onto 459 // the work list and we should not consider it for subsequent call 460 // handling steps. 461 Bldr.takeNodes(Pred); 462 return; 463 } 464 465 // If we can't inline it, handle the return value and invalidate the regions. 466 if (State == 0) 467 State = Pred->getState(); 468 469 // Invalidate any regions touched by the call. 470 unsigned Count = currentBuilderContext->getCurrentBlockCount(); 471 State = Call.invalidateRegions(Count, State); 472 473 // Construct and bind the return value. 474 State = bindReturnValue(Call, Pred->getLocationContext(), State); 475 476 // And make the result node. 477 Bldr.generateNode(Call.getProgramPoint(), State, Pred); 478} 479 480void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred, 481 ExplodedNodeSet &Dst) { 482 483 ExplodedNodeSet dstPreVisit; 484 getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this); 485 486 StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext); 487 488 if (RS->getRetValue()) { 489 for (ExplodedNodeSet::iterator it = dstPreVisit.begin(), 490 ei = dstPreVisit.end(); it != ei; ++it) { 491 B.generateNode(RS, *it, (*it)->getState()); 492 } 493 } 494} 495