ExprEngineCallAndReturn.cpp revision 514f2c9dcb9e04b52929c5b141a6fe88bd68b33f
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.
132static bool shouldInline(const FunctionDecl *FD, ExplodedNode *Pred,
133                         AnalysisManager &AMgr) {
134  AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(FD);
135  const CFG *CalleeCFG = CalleeADC->getCFG();
136
137  if (getNumberStackFrames(Pred->getLocationContext())
138        == AMgr.InlineMaxStackDepth)
139    return false;
140
141  if (CalleeCFG->getNumBlockIDs() > AMgr.InlineMaxFunctionSize)
142    return false;
143
144  return true;
145}
146
147bool ExprEngine::InlineCall(ExplodedNodeSet &Dst,
148                            const CallExpr *CE,
149                            ExplodedNode *Pred) {
150  ProgramStateRef state = Pred->getState();
151  const Expr *Callee = CE->getCallee();
152  const FunctionDecl *FD =
153    state->getSVal(Callee, Pred->getLocationContext()).getAsFunctionDecl();
154  if (!FD || !FD->hasBody(FD))
155    return false;
156
157  switch (CE->getStmtClass()) {
158    default:
159      // FIXME: Handle C++.
160      break;
161    case Stmt::CallExprClass: {
162      if (!shouldInline(FD, Pred, AMgr))
163        return false;
164
165      // Construct a new stack frame for the callee.
166      AnalysisDeclContext *CalleeADC = AMgr.getAnalysisDeclContext(FD);
167      const StackFrameContext *CallerSFC =
168      Pred->getLocationContext()->getCurrentStackFrame();
169      const StackFrameContext *CalleeSFC =
170      CalleeADC->getStackFrame(CallerSFC, CE,
171                               currentBuilderContext->getBlock(),
172                               currentStmtIdx);
173
174      CallEnter Loc(CE, CalleeSFC, Pred->getLocationContext());
175      bool isNew;
176      ExplodedNode *N = G.getNode(Loc, state, false, &isNew);
177      N->addPredecessor(Pred, G);
178      if (isNew)
179        Engine.getWorkList()->enqueue(N);
180      return true;
181    }
182  }
183  return false;
184}
185
186static bool isPointerToConst(const ParmVarDecl *ParamDecl) {
187  QualType PointeeTy = ParamDecl->getOriginalType()->getPointeeType();
188  if (PointeeTy != QualType() && PointeeTy.isConstQualified() &&
189      !PointeeTy->isAnyPointerType() && !PointeeTy->isReferenceType()) {
190    return true;
191  }
192  return false;
193}
194
195// Try to retrieve the function declaration and find the function parameter
196// types which are pointers/references to a non-pointer const.
197// We do not invalidate the corresponding argument regions.
198static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
199                       const CallOrObjCMessage &Call) {
200  const Decl *CallDecl = Call.getDecl();
201  if (!CallDecl)
202    return;
203
204  if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(CallDecl)) {
205    const IdentifierInfo *II = FDecl->getIdentifier();
206
207    // List the cases, where the region should be invalidated even if the
208    // argument is const.
209    if (II) {
210      StringRef FName = II->getName();
211      //  - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
212      // value into thread local storage. The value can later be retrieved with
213      // 'void *ptheread_getspecific(pthread_key)'. So even thought the
214      // parameter is 'const void *', the region escapes through the call.
215      //  - funopen - sets a buffer for future IO calls.
216      //  - ObjC functions that end with "NoCopy" can free memory, of the passed
217      // in buffer.
218      // - Many CF containers allow objects to escape through custom
219      // allocators/deallocators upon container construction.
220      if (FName == "pthread_setspecific" ||
221          FName == "funopen" ||
222          FName.endswith("NoCopy") ||
223          Call.isCFCGAllowingEscape(FName))
224        return;
225    }
226
227    for (unsigned Idx = 0, E = Call.getNumArgs(); Idx != E; ++Idx) {
228      if (FDecl && Idx < FDecl->getNumParams()) {
229        if (isPointerToConst(FDecl->getParamDecl(Idx)))
230          PreserveArgs.insert(Idx);
231      }
232    }
233    return;
234  }
235
236  if (const ObjCMethodDecl *MDecl = dyn_cast<ObjCMethodDecl>(CallDecl)) {
237    assert(MDecl->param_size() <= Call.getNumArgs());
238    unsigned Idx = 0;
239    for (clang::ObjCMethodDecl::param_const_iterator
240         I = MDecl->param_begin(), E = MDecl->param_end(); I != E; ++I, ++Idx) {
241      if (isPointerToConst(*I))
242        PreserveArgs.insert(Idx);
243    }
244    return;
245  }
246}
247
248ProgramStateRef
249ExprEngine::invalidateArguments(ProgramStateRef State,
250                                const CallOrObjCMessage &Call,
251                                const LocationContext *LC) {
252  SmallVector<const MemRegion *, 8> RegionsToInvalidate;
253
254  if (Call.isObjCMessage()) {
255    // Invalidate all instance variables of the receiver of an ObjC message.
256    // FIXME: We should be able to do better with inter-procedural analysis.
257    if (const MemRegion *MR = Call.getInstanceMessageReceiver(LC).getAsRegion())
258      RegionsToInvalidate.push_back(MR);
259
260  } else if (Call.isCXXCall()) {
261    // Invalidate all instance variables for the callee of a C++ method call.
262    // FIXME: We should be able to do better with inter-procedural analysis.
263    // FIXME: We can probably do better for const versus non-const methods.
264    if (const MemRegion *Callee = Call.getCXXCallee().getAsRegion())
265      RegionsToInvalidate.push_back(Callee);
266
267  } else if (Call.isFunctionCall()) {
268    // Block calls invalidate all captured-by-reference values.
269    SVal CalleeVal = Call.getFunctionCallee();
270    if (const MemRegion *Callee = CalleeVal.getAsRegion()) {
271      if (isa<BlockDataRegion>(Callee))
272        RegionsToInvalidate.push_back(Callee);
273    }
274  }
275
276  // Indexes of arguments whose values will be preserved by the call.
277  llvm::SmallSet<unsigned, 1> PreserveArgs;
278  findPtrToConstParams(PreserveArgs, Call);
279
280  for (unsigned idx = 0, e = Call.getNumArgs(); idx != e; ++idx) {
281    if (PreserveArgs.count(idx))
282      continue;
283
284    SVal V = Call.getArgSVal(idx);
285
286    // If we are passing a location wrapped as an integer, unwrap it and
287    // invalidate the values referred by the location.
288    if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
289      V = Wrapped->getLoc();
290    else if (!isa<Loc>(V))
291      continue;
292
293    if (const MemRegion *R = V.getAsRegion()) {
294      // Invalidate the value of the variable passed by reference.
295
296      // Are we dealing with an ElementRegion?  If the element type is
297      // a basic integer type (e.g., char, int) and the underlying region
298      // is a variable region then strip off the ElementRegion.
299      // FIXME: We really need to think about this for the general case
300      //   as sometimes we are reasoning about arrays and other times
301      //   about (char*), etc., is just a form of passing raw bytes.
302      //   e.g., void *p = alloca(); foo((char*)p);
303      if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
304        // Checking for 'integral type' is probably too promiscuous, but
305        // we'll leave it in for now until we have a systematic way of
306        // handling all of these cases.  Eventually we need to come up
307        // with an interface to StoreManager so that this logic can be
308        // appropriately delegated to the respective StoreManagers while
309        // still allowing us to do checker-specific logic (e.g.,
310        // invalidating reference counts), probably via callbacks.
311        if (ER->getElementType()->isIntegralOrEnumerationType()) {
312          const MemRegion *superReg = ER->getSuperRegion();
313          if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
314              isa<ObjCIvarRegion>(superReg))
315            R = cast<TypedRegion>(superReg);
316        }
317        // FIXME: What about layers of ElementRegions?
318      }
319
320      // Mark this region for invalidation.  We batch invalidate regions
321      // below for efficiency.
322      RegionsToInvalidate.push_back(R);
323    } else {
324      // Nuke all other arguments passed by reference.
325      // FIXME: is this necessary or correct? This handles the non-Region
326      //  cases.  Is it ever valid to store to these?
327      State = State->unbindLoc(cast<Loc>(V));
328    }
329  }
330
331  // Invalidate designated regions using the batch invalidation API.
332
333  // FIXME: We can have collisions on the conjured symbol if the
334  //  expression *I also creates conjured symbols.  We probably want
335  //  to identify conjured symbols by an expression pair: the enclosing
336  //  expression (the context) and the expression itself.  This should
337  //  disambiguate conjured symbols.
338  unsigned Count = currentBuilderContext->getCurrentBlockCount();
339  StoreManager::InvalidatedSymbols IS;
340
341  // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
342  //  global variables.
343  return State->invalidateRegions(RegionsToInvalidate,
344                                  Call.getOriginExpr(), Count, LC,
345                                  &IS, &Call);
346
347}
348
349// For now, skip inlining variadic functions.
350// We also don't inline blocks.
351static bool shouldInlineCall(const CallExpr *CE, ExprEngine &Eng) {
352  if (!Eng.getAnalysisManager().shouldInlineCall())
353    return false;
354  QualType callee = CE->getCallee()->getType();
355  const FunctionProtoType *FT = 0;
356  if (const PointerType *PT = callee->getAs<PointerType>())
357    FT = dyn_cast<FunctionProtoType>(PT->getPointeeType());
358  else if (const BlockPointerType *BT = callee->getAs<BlockPointerType>()) {
359    // FIXME: inline blocks.
360    // FT = dyn_cast<FunctionProtoType>(BT->getPointeeType());
361    (void) BT;
362    return false;
363  }
364
365  // If we have no prototype, assume the function is okay.
366  if (!FT)
367    return true;
368
369  // Skip inlining of variadic functions.
370  return !FT->isVariadic();
371}
372
373void ExprEngine::VisitCallExpr(const CallExpr *CE, ExplodedNode *Pred,
374                               ExplodedNodeSet &dst) {
375  // Perform the previsit of the CallExpr.
376  ExplodedNodeSet dstPreVisit;
377  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, CE, *this);
378
379  // Now evaluate the call itself.
380  class DefaultEval : public GraphExpander {
381    ExprEngine &Eng;
382    const CallExpr *CE;
383  public:
384
385    DefaultEval(ExprEngine &eng, const CallExpr *ce)
386    : Eng(eng), CE(ce) {}
387    virtual void expandGraph(ExplodedNodeSet &Dst, ExplodedNode *Pred) {
388      // Should we inline the call?
389      if (shouldInlineCall(CE, Eng) &&
390          Eng.InlineCall(Dst, CE, Pred)) {
391        return;
392      }
393
394      // First handle the return value.
395      StmtNodeBuilder Bldr(Pred, Dst, *Eng.currentBuilderContext);
396
397      // Get the callee.
398      const Expr *Callee = CE->getCallee()->IgnoreParens();
399      ProgramStateRef state = Pred->getState();
400      SVal L = state->getSVal(Callee, Pred->getLocationContext());
401
402      // Figure out the result type. We do this dance to handle references.
403      QualType ResultTy;
404      if (const FunctionDecl *FD = L.getAsFunctionDecl())
405        ResultTy = FD->getResultType();
406      else
407        ResultTy = CE->getType();
408
409      if (CE->isLValue())
410        ResultTy = Eng.getContext().getPointerType(ResultTy);
411
412      // Conjure a symbol value to use as the result.
413      SValBuilder &SVB = Eng.getSValBuilder();
414      unsigned Count = Eng.currentBuilderContext->getCurrentBlockCount();
415      const LocationContext *LCtx = Pred->getLocationContext();
416      SVal RetVal = SVB.getConjuredSymbolVal(0, CE, LCtx, ResultTy, Count);
417
418      // Generate a new state with the return value set.
419      state = state->BindExpr(CE, LCtx, RetVal);
420
421      // Invalidate the arguments.
422      state = Eng.invalidateArguments(state, CallOrObjCMessage(CE, state, LCtx),
423                                      LCtx);
424
425      // And make the result node.
426      Bldr.generateNode(CE, Pred, state);
427    }
428  };
429
430  // Finally, evaluate the function call.  We try each of the checkers
431  // to see if the can evaluate the function call.
432  ExplodedNodeSet dstCallEvaluated;
433  DefaultEval defEval(*this, CE);
434  getCheckerManager().runCheckersForEvalCall(dstCallEvaluated,
435                                             dstPreVisit,
436                                             CE, *this, &defEval);
437
438  // Finally, perform the post-condition check of the CallExpr and store
439  // the created nodes in 'Dst'.
440  getCheckerManager().runCheckersForPostStmt(dst, dstCallEvaluated, CE,
441                                             *this);
442}
443
444void ExprEngine::VisitReturnStmt(const ReturnStmt *RS, ExplodedNode *Pred,
445                                 ExplodedNodeSet &Dst) {
446
447  ExplodedNodeSet dstPreVisit;
448  getCheckerManager().runCheckersForPreStmt(dstPreVisit, Pred, RS, *this);
449
450  StmtNodeBuilder B(dstPreVisit, Dst, *currentBuilderContext);
451
452  if (RS->getRetValue()) {
453    for (ExplodedNodeSet::iterator it = dstPreVisit.begin(),
454                                  ei = dstPreVisit.end(); it != ei; ++it) {
455      B.generateNode(RS, *it, (*it)->getState());
456    }
457  }
458}
459