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