ExprEngineCXX.cpp revision 1fc9111d85c3929018cd5c85dd14f3dbb5d23d68
1//===- ExprEngineCXX.cpp - ExprEngine support for C++ -----------*- 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 the C++ expression evaluation engine. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 15#include "clang/AST/DeclCXX.h" 16#include "clang/AST/StmtCXX.h" 17#include "clang/Basic/PrettyStackTrace.h" 18#include "clang/StaticAnalyzer/Core/CheckerManager.h" 19#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 20#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" 21 22using namespace clang; 23using namespace ento; 24 25void ExprEngine::CreateCXXTemporaryObject(const MaterializeTemporaryExpr *ME, 26 ExplodedNode *Pred, 27 ExplodedNodeSet &Dst) { 28 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 29 const Expr *tempExpr = ME->GetTemporaryExpr()->IgnoreParens(); 30 ProgramStateRef state = Pred->getState(); 31 const LocationContext *LCtx = Pred->getLocationContext(); 32 33 SVal V = state->getSVal(tempExpr, LCtx); 34 35 // If the value is already a CXXTempObjectRegion, it is fine as it is. 36 // Otherwise, create a new CXXTempObjectRegion, and copy the value into it. 37 // This is an optimization for when an rvalue is constructed and then 38 // immediately materialized. 39 const MemRegion *MR = V.getAsRegion(); 40 if (const CXXTempObjectRegion *TR = 41 dyn_cast_or_null<CXXTempObjectRegion>(MR)) { 42 if (getContext().hasSameUnqualifiedType(TR->getValueType(), ME->getType())) 43 state = state->BindExpr(ME, LCtx, V); 44 } 45 46 if (state == Pred->getState()) 47 state = createTemporaryRegionIfNeeded(state, LCtx, tempExpr, ME); 48 Bldr.generateNode(ME, Pred, state); 49} 50 51// FIXME: This is the sort of code that should eventually live in a Core 52// checker rather than as a special case in ExprEngine. 53void ExprEngine::performTrivialCopy(NodeBuilder &Bldr, ExplodedNode *Pred, 54 const CallEvent &Call) { 55 SVal ThisVal; 56 bool AlwaysReturnsLValue; 57 if (const CXXConstructorCall *Ctor = dyn_cast<CXXConstructorCall>(&Call)) { 58 assert(Ctor->getDecl()->isTrivial()); 59 assert(Ctor->getDecl()->isCopyOrMoveConstructor()); 60 ThisVal = Ctor->getCXXThisVal(); 61 AlwaysReturnsLValue = false; 62 } else { 63 assert(cast<CXXMethodDecl>(Call.getDecl())->isTrivial()); 64 assert(cast<CXXMethodDecl>(Call.getDecl())->getOverloadedOperator() == 65 OO_Equal); 66 ThisVal = cast<CXXInstanceCall>(Call).getCXXThisVal(); 67 AlwaysReturnsLValue = true; 68 } 69 70 const LocationContext *LCtx = Pred->getLocationContext(); 71 72 ExplodedNodeSet Dst; 73 Bldr.takeNodes(Pred); 74 75 SVal V = Call.getArgSVal(0); 76 77 // If the value being copied is not unknown, load from its location to get 78 // an aggregate rvalue. 79 if (Optional<Loc> L = V.getAs<Loc>()) 80 V = Pred->getState()->getSVal(*L); 81 else 82 assert(V.isUnknown()); 83 84 const Expr *CallExpr = Call.getOriginExpr(); 85 evalBind(Dst, CallExpr, Pred, ThisVal, V, true); 86 87 PostStmt PS(CallExpr, LCtx); 88 for (ExplodedNodeSet::iterator I = Dst.begin(), E = Dst.end(); 89 I != E; ++I) { 90 ProgramStateRef State = (*I)->getState(); 91 if (AlwaysReturnsLValue) 92 State = State->BindExpr(CallExpr, LCtx, ThisVal); 93 else 94 State = bindReturnValue(Call, LCtx, State); 95 Bldr.generateNode(PS, State, *I); 96 } 97} 98 99 100/// Returns a region representing the first element of a (possibly 101/// multi-dimensional) array. 102/// 103/// On return, \p Ty will be set to the base type of the array. 104/// 105/// If the type is not an array type at all, the original value is returned. 106static SVal makeZeroElementRegion(ProgramStateRef State, SVal LValue, 107 QualType &Ty) { 108 SValBuilder &SVB = State->getStateManager().getSValBuilder(); 109 ASTContext &Ctx = SVB.getContext(); 110 111 while (const ArrayType *AT = Ctx.getAsArrayType(Ty)) { 112 Ty = AT->getElementType(); 113 LValue = State->getLValue(Ty, SVB.makeZeroArrayIndex(), LValue); 114 } 115 116 return LValue; 117} 118 119void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE, 120 ExplodedNode *Pred, 121 ExplodedNodeSet &destNodes) { 122 const LocationContext *LCtx = Pred->getLocationContext(); 123 ProgramStateRef State = Pred->getState(); 124 125 const MemRegion *Target = 0; 126 127 // FIXME: Handle arrays, which run the same constructor for every element. 128 // For now, we just run the first constructor (which should still invalidate 129 // the entire array). 130 131 switch (CE->getConstructionKind()) { 132 case CXXConstructExpr::CK_Complete: { 133 // See if we're constructing an existing region by looking at the next 134 // element in the CFG. 135 const CFGBlock *B = currBldrCtx->getBlock(); 136 if (currStmtIdx + 1 < B->size()) { 137 CFGElement Next = (*B)[currStmtIdx+1]; 138 139 // Is this a constructor for a local variable? 140 if (Optional<CFGStmt> StmtElem = Next.getAs<CFGStmt>()) { 141 if (const DeclStmt *DS = dyn_cast<DeclStmt>(StmtElem->getStmt())) { 142 if (const VarDecl *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) { 143 if (Var->getInit()->IgnoreImplicit() == CE) { 144 SVal LValue = State->getLValue(Var, LCtx); 145 QualType Ty = Var->getType(); 146 LValue = makeZeroElementRegion(State, LValue, Ty); 147 Target = LValue.getAsRegion(); 148 } 149 } 150 } 151 } 152 153 // Is this a constructor for a member? 154 if (Optional<CFGInitializer> InitElem = Next.getAs<CFGInitializer>()) { 155 const CXXCtorInitializer *Init = InitElem->getInitializer(); 156 assert(Init->isAnyMemberInitializer()); 157 158 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 159 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 160 LCtx->getCurrentStackFrame()); 161 SVal ThisVal = State->getSVal(ThisPtr); 162 163 const ValueDecl *Field; 164 SVal FieldVal; 165 if (Init->isIndirectMemberInitializer()) { 166 Field = Init->getIndirectMember(); 167 FieldVal = State->getLValue(Init->getIndirectMember(), ThisVal); 168 } else { 169 Field = Init->getMember(); 170 FieldVal = State->getLValue(Init->getMember(), ThisVal); 171 } 172 173 QualType Ty = Field->getType(); 174 FieldVal = makeZeroElementRegion(State, FieldVal, Ty); 175 Target = FieldVal.getAsRegion(); 176 } 177 178 // FIXME: This will eventually need to handle new-expressions as well. 179 } 180 181 // If we couldn't find an existing region to construct into, assume we're 182 // constructing a temporary. 183 if (!Target) { 184 MemRegionManager &MRMgr = getSValBuilder().getRegionManager(); 185 Target = MRMgr.getCXXTempObjectRegion(CE, LCtx); 186 } 187 188 break; 189 } 190 case CXXConstructExpr::CK_VirtualBase: 191 // Make sure we are not calling virtual base class initializers twice. 192 // Only the most-derived object should initialize virtual base classes. 193 if (const Stmt *Outer = LCtx->getCurrentStackFrame()->getCallSite()) { 194 const CXXConstructExpr *OuterCtor = dyn_cast<CXXConstructExpr>(Outer); 195 if (OuterCtor) { 196 switch (OuterCtor->getConstructionKind()) { 197 case CXXConstructExpr::CK_NonVirtualBase: 198 case CXXConstructExpr::CK_VirtualBase: 199 // Bail out! 200 destNodes.Add(Pred); 201 return; 202 case CXXConstructExpr::CK_Complete: 203 case CXXConstructExpr::CK_Delegating: 204 break; 205 } 206 } 207 } 208 // FALLTHROUGH 209 case CXXConstructExpr::CK_NonVirtualBase: 210 case CXXConstructExpr::CK_Delegating: { 211 const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl()); 212 Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor, 213 LCtx->getCurrentStackFrame()); 214 SVal ThisVal = State->getSVal(ThisPtr); 215 216 if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) { 217 Target = ThisVal.getAsRegion(); 218 } else { 219 // Cast to the base type. 220 bool IsVirtual = 221 (CE->getConstructionKind() == CXXConstructExpr::CK_VirtualBase); 222 SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, CE->getType(), 223 IsVirtual); 224 Target = BaseVal.getAsRegion(); 225 } 226 break; 227 } 228 } 229 230 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 231 CallEventRef<CXXConstructorCall> Call = 232 CEMgr.getCXXConstructorCall(CE, Target, State, LCtx); 233 234 ExplodedNodeSet DstPreVisit; 235 getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this); 236 ExplodedNodeSet DstPreCall; 237 getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit, 238 *Call, *this); 239 240 ExplodedNodeSet DstEvaluated; 241 StmtNodeBuilder Bldr(DstPreCall, DstEvaluated, *currBldrCtx); 242 243 bool IsArray = isa<ElementRegion>(Target); 244 if (CE->getConstructor()->isTrivial() && 245 CE->getConstructor()->isCopyOrMoveConstructor() && 246 !IsArray) { 247 // FIXME: Handle other kinds of trivial constructors as well. 248 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 249 I != E; ++I) 250 performTrivialCopy(Bldr, *I, *Call); 251 252 } else { 253 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 254 I != E; ++I) 255 defaultEvalCall(Bldr, *I, *Call); 256 } 257 258 ExplodedNodeSet DstPostCall; 259 getCheckerManager().runCheckersForPostCall(DstPostCall, DstEvaluated, 260 *Call, *this); 261 getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this); 262} 263 264void ExprEngine::VisitCXXDestructor(QualType ObjectType, 265 const MemRegion *Dest, 266 const Stmt *S, 267 bool IsBaseDtor, 268 ExplodedNode *Pred, 269 ExplodedNodeSet &Dst) { 270 const LocationContext *LCtx = Pred->getLocationContext(); 271 ProgramStateRef State = Pred->getState(); 272 273 // FIXME: We need to run the same destructor on every element of the array. 274 // This workaround will just run the first destructor (which will still 275 // invalidate the entire array). 276 SVal DestVal = loc::MemRegionVal(Dest); 277 DestVal = makeZeroElementRegion(State, DestVal, ObjectType); 278 Dest = DestVal.getAsRegion(); 279 280 const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl(); 281 assert(RecordDecl && "Only CXXRecordDecls should have destructors"); 282 const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor(); 283 284 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 285 CallEventRef<CXXDestructorCall> Call = 286 CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx); 287 288 PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(), 289 Call->getSourceRange().getBegin(), 290 "Error evaluating destructor"); 291 292 ExplodedNodeSet DstPreCall; 293 getCheckerManager().runCheckersForPreCall(DstPreCall, Pred, 294 *Call, *this); 295 296 ExplodedNodeSet DstInvalidated; 297 StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx); 298 for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end(); 299 I != E; ++I) 300 defaultEvalCall(Bldr, *I, *Call); 301 302 ExplodedNodeSet DstPostCall; 303 getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated, 304 *Call, *this); 305} 306 307void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred, 308 ExplodedNodeSet &Dst) { 309 // FIXME: Much of this should eventually migrate to CXXAllocatorCall. 310 // Also, we need to decide how allocators actually work -- they're not 311 // really part of the CXXNewExpr because they happen BEFORE the 312 // CXXConstructExpr subexpression. See PR12014 for some discussion. 313 314 unsigned blockCount = currBldrCtx->blockCount(); 315 const LocationContext *LCtx = Pred->getLocationContext(); 316 DefinedOrUnknownSVal symVal = UnknownVal(); 317 FunctionDecl *FD = CNE->getOperatorNew(); 318 319 bool IsStandardGlobalOpNewFunction = false; 320 if (FD && !isa<CXXMethodDecl>(FD) && !FD->isVariadic()) { 321 if (FD->getNumParams() == 2) { 322 QualType T = FD->getParamDecl(1)->getType(); 323 if (const IdentifierInfo *II = T.getBaseTypeIdentifier()) 324 // NoThrow placement new behaves as a standard new. 325 IsStandardGlobalOpNewFunction = II->getName().equals("nothrow_t"); 326 } 327 else 328 // Placement forms are considered non-standard. 329 IsStandardGlobalOpNewFunction = (FD->getNumParams() == 1); 330 } 331 332 // We assume all standard global 'operator new' functions allocate memory in 333 // heap. We realize this is an approximation that might not correctly model 334 // a custom global allocator. 335 if (IsStandardGlobalOpNewFunction) 336 symVal = svalBuilder.getConjuredHeapSymbolVal(CNE, LCtx, blockCount); 337 else 338 symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx, CNE->getType(), 339 blockCount); 340 341 ProgramStateRef State = Pred->getState(); 342 CallEventManager &CEMgr = getStateManager().getCallEventManager(); 343 CallEventRef<CXXAllocatorCall> Call = 344 CEMgr.getCXXAllocatorCall(CNE, State, LCtx); 345 346 // Invalidate placement args. 347 // FIXME: Once we figure out how we want allocators to work, 348 // we should be using the usual pre-/(default-)eval-/post-call checks here. 349 State = Call->invalidateRegions(blockCount); 350 if (!State) 351 return; 352 353 // If we're compiling with exceptions enabled, and this allocation function 354 // is not declared as non-throwing, failures /must/ be signalled by 355 // exceptions, and thus the return value will never be NULL. 356 // C++11 [basic.stc.dynamic.allocation]p3. 357 if (FD && getContext().getLangOpts().CXXExceptions) { 358 QualType Ty = FD->getType(); 359 if (const FunctionProtoType *ProtoType = Ty->getAs<FunctionProtoType>()) 360 if (!ProtoType->isNothrow(getContext())) 361 State = State->assume(symVal, true); 362 } 363 364 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 365 366 if (CNE->isArray()) { 367 // FIXME: allocating an array requires simulating the constructors. 368 // For now, just return a symbolicated region. 369 const MemRegion *NewReg = symVal.castAs<loc::MemRegionVal>().getRegion(); 370 QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType(); 371 const ElementRegion *EleReg = 372 getStoreManager().GetElementZeroRegion(NewReg, ObjTy); 373 State = State->BindExpr(CNE, Pred->getLocationContext(), 374 loc::MemRegionVal(EleReg)); 375 Bldr.generateNode(CNE, Pred, State); 376 return; 377 } 378 379 // FIXME: Once we have proper support for CXXConstructExprs inside 380 // CXXNewExpr, we need to make sure that the constructed object is not 381 // immediately invalidated here. (The placement call should happen before 382 // the constructor call anyway.) 383 SVal Result = symVal; 384 if (FD && FD->isReservedGlobalPlacementOperator()) { 385 // Non-array placement new should always return the placement location. 386 SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx); 387 Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(), 388 CNE->getPlacementArg(0)->getType()); 389 } 390 391 // Bind the address of the object, then check to see if we cached out. 392 State = State->BindExpr(CNE, LCtx, Result); 393 ExplodedNode *NewN = Bldr.generateNode(CNE, Pred, State); 394 if (!NewN) 395 return; 396 397 // If the type is not a record, we won't have a CXXConstructExpr as an 398 // initializer. Copy the value over. 399 if (const Expr *Init = CNE->getInitializer()) { 400 if (!isa<CXXConstructExpr>(Init)) { 401 assert(Bldr.getResults().size() == 1); 402 Bldr.takeNodes(NewN); 403 404 assert(!CNE->getType()->getPointeeCXXRecordDecl()); 405 evalBind(Dst, CNE, NewN, Result, State->getSVal(Init, LCtx), 406 /*FirstInit=*/IsStandardGlobalOpNewFunction); 407 } 408 } 409} 410 411void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE, 412 ExplodedNode *Pred, ExplodedNodeSet &Dst) { 413 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 414 ProgramStateRef state = Pred->getState(); 415 Bldr.generateNode(CDE, Pred, state); 416} 417 418void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS, 419 ExplodedNode *Pred, 420 ExplodedNodeSet &Dst) { 421 const VarDecl *VD = CS->getExceptionDecl(); 422 if (!VD) { 423 Dst.Add(Pred); 424 return; 425 } 426 427 const LocationContext *LCtx = Pred->getLocationContext(); 428 SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(), 429 currBldrCtx->blockCount()); 430 ProgramStateRef state = Pred->getState(); 431 state = state->bindLoc(state->getLValue(VD, LCtx), V); 432 433 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 434 Bldr.generateNode(CS, Pred, state); 435} 436 437void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred, 438 ExplodedNodeSet &Dst) { 439 StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx); 440 441 // Get the this object region from StoreManager. 442 const LocationContext *LCtx = Pred->getLocationContext(); 443 const MemRegion *R = 444 svalBuilder.getRegionManager().getCXXThisRegion( 445 getContext().getCanonicalType(TE->getType()), 446 LCtx); 447 448 ProgramStateRef state = Pred->getState(); 449 SVal V = state->getSVal(loc::MemRegionVal(R)); 450 Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V)); 451} 452