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