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