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