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