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