Home | History | Annotate | Download | only in Core
      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/CheckerManager.h"
     15 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
     16 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
     17 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
     18 #include "clang/AST/DeclCXX.h"
     19 #include "clang/AST/StmtCXX.h"
     20 #include "clang/Basic/PrettyStackTrace.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   // Bind the temporary object to the value of the expression. Then bind
     34   // the expression to the location of the object.
     35   SVal V = state->getSVal(tempExpr, LCtx);
     36 
     37   // If the value is already a CXXTempObjectRegion, it is fine as it is.
     38   // Otherwise, create a new CXXTempObjectRegion, and copy the value into it.
     39   const MemRegion *MR = V.getAsRegion();
     40   if (!MR || !isa<CXXTempObjectRegion>(MR)) {
     41     const MemRegion *R =
     42       svalBuilder.getRegionManager().getCXXTempObjectRegion(ME, LCtx);
     43 
     44     SVal L = loc::MemRegionVal(R);
     45     state = state->bindLoc(L, V);
     46     V = L;
     47   }
     48 
     49   Bldr.generateNode(ME, Pred, state->BindExpr(ME, LCtx, V));
     50 }
     51 
     52 void ExprEngine::VisitCXXConstructExpr(const CXXConstructExpr *CE,
     53                                        ExplodedNode *Pred,
     54                                        ExplodedNodeSet &destNodes) {
     55   const LocationContext *LCtx = Pred->getLocationContext();
     56   ProgramStateRef State = Pred->getState();
     57 
     58   const MemRegion *Target = 0;
     59 
     60   switch (CE->getConstructionKind()) {
     61   case CXXConstructExpr::CK_Complete: {
     62     // See if we're constructing an existing region by looking at the next
     63     // element in the CFG.
     64     const CFGBlock *B = currBldrCtx->getBlock();
     65     if (currStmtIdx + 1 < B->size()) {
     66       CFGElement Next = (*B)[currStmtIdx+1];
     67 
     68       // Is this a constructor for a local variable?
     69       if (const CFGStmt *StmtElem = dyn_cast<CFGStmt>(&Next)) {
     70         if (const DeclStmt *DS = dyn_cast<DeclStmt>(StmtElem->getStmt())) {
     71           if (const VarDecl *Var = dyn_cast<VarDecl>(DS->getSingleDecl())) {
     72             if (Var->getInit()->IgnoreImplicit() == CE) {
     73               QualType Ty = Var->getType();
     74               if (const ArrayType *AT = getContext().getAsArrayType(Ty)) {
     75                 // FIXME: Handle arrays, which run the same constructor for
     76                 // every element. This workaround will just run the first
     77                 // constructor (which should still invalidate the entire array).
     78                 SVal Base = State->getLValue(Var, LCtx);
     79                 Target = State->getLValue(AT->getElementType(),
     80                                           getSValBuilder().makeZeroArrayIndex(),
     81                                           Base).getAsRegion();
     82               } else {
     83                 Target = State->getLValue(Var, LCtx).getAsRegion();
     84               }
     85             }
     86           }
     87         }
     88       }
     89 
     90       // Is this a constructor for a member?
     91       if (const CFGInitializer *InitElem = dyn_cast<CFGInitializer>(&Next)) {
     92         const CXXCtorInitializer *Init = InitElem->getInitializer();
     93         assert(Init->isAnyMemberInitializer());
     94 
     95         const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
     96         Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
     97                                                   LCtx->getCurrentStackFrame());
     98         SVal ThisVal = State->getSVal(ThisPtr);
     99 
    100         if (Init->isIndirectMemberInitializer()) {
    101           SVal Field = State->getLValue(Init->getIndirectMember(), ThisVal);
    102           Target = Field.getAsRegion();
    103         } else {
    104           SVal Field = State->getLValue(Init->getMember(), ThisVal);
    105           Target = Field.getAsRegion();
    106         }
    107       }
    108 
    109       // FIXME: This will eventually need to handle new-expressions as well.
    110     }
    111 
    112     // If we couldn't find an existing region to construct into, assume we're
    113     // constructing a temporary.
    114     if (!Target) {
    115       MemRegionManager &MRMgr = getSValBuilder().getRegionManager();
    116       Target = MRMgr.getCXXTempObjectRegion(CE, LCtx);
    117     }
    118 
    119     break;
    120   }
    121   case CXXConstructExpr::CK_NonVirtualBase:
    122   case CXXConstructExpr::CK_VirtualBase:
    123   case CXXConstructExpr::CK_Delegating: {
    124     const CXXMethodDecl *CurCtor = cast<CXXMethodDecl>(LCtx->getDecl());
    125     Loc ThisPtr = getSValBuilder().getCXXThis(CurCtor,
    126                                               LCtx->getCurrentStackFrame());
    127     SVal ThisVal = State->getSVal(ThisPtr);
    128 
    129     if (CE->getConstructionKind() == CXXConstructExpr::CK_Delegating) {
    130       Target = ThisVal.getAsRegion();
    131     } else {
    132       // Cast to the base type.
    133       QualType BaseTy = CE->getType();
    134       SVal BaseVal = getStoreManager().evalDerivedToBase(ThisVal, BaseTy);
    135       Target = BaseVal.getAsRegion();
    136     }
    137     break;
    138   }
    139   }
    140 
    141   CallEventManager &CEMgr = getStateManager().getCallEventManager();
    142   CallEventRef<CXXConstructorCall> Call =
    143     CEMgr.getCXXConstructorCall(CE, Target, State, LCtx);
    144 
    145   ExplodedNodeSet DstPreVisit;
    146   getCheckerManager().runCheckersForPreStmt(DstPreVisit, Pred, CE, *this);
    147   ExplodedNodeSet DstPreCall;
    148   getCheckerManager().runCheckersForPreCall(DstPreCall, DstPreVisit,
    149                                             *Call, *this);
    150 
    151   ExplodedNodeSet DstInvalidated;
    152   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
    153   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
    154        I != E; ++I)
    155     defaultEvalCall(Bldr, *I, *Call);
    156 
    157   ExplodedNodeSet DstPostCall;
    158   getCheckerManager().runCheckersForPostCall(DstPostCall, DstInvalidated,
    159                                              *Call, *this);
    160   getCheckerManager().runCheckersForPostStmt(destNodes, DstPostCall, CE, *this);
    161 }
    162 
    163 void ExprEngine::VisitCXXDestructor(QualType ObjectType,
    164                                     const MemRegion *Dest,
    165                                     const Stmt *S,
    166                                     bool IsBaseDtor,
    167                                     ExplodedNode *Pred,
    168                                     ExplodedNodeSet &Dst) {
    169   const LocationContext *LCtx = Pred->getLocationContext();
    170   ProgramStateRef State = Pred->getState();
    171 
    172   // FIXME: We need to run the same destructor on every element of the array.
    173   // This workaround will just run the first destructor (which will still
    174   // invalidate the entire array).
    175   if (const ArrayType *AT = getContext().getAsArrayType(ObjectType)) {
    176     ObjectType = AT->getElementType();
    177     Dest = State->getLValue(ObjectType, getSValBuilder().makeZeroArrayIndex(),
    178                             loc::MemRegionVal(Dest)).getAsRegion();
    179   }
    180 
    181   const CXXRecordDecl *RecordDecl = ObjectType->getAsCXXRecordDecl();
    182   assert(RecordDecl && "Only CXXRecordDecls should have destructors");
    183   const CXXDestructorDecl *DtorDecl = RecordDecl->getDestructor();
    184 
    185   CallEventManager &CEMgr = getStateManager().getCallEventManager();
    186   CallEventRef<CXXDestructorCall> Call =
    187     CEMgr.getCXXDestructorCall(DtorDecl, S, Dest, IsBaseDtor, State, LCtx);
    188 
    189   PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),
    190                                 Call->getSourceRange().getBegin(),
    191                                 "Error evaluating destructor");
    192 
    193   ExplodedNodeSet DstPreCall;
    194   getCheckerManager().runCheckersForPreCall(DstPreCall, Pred,
    195                                             *Call, *this);
    196 
    197   ExplodedNodeSet DstInvalidated;
    198   StmtNodeBuilder Bldr(DstPreCall, DstInvalidated, *currBldrCtx);
    199   for (ExplodedNodeSet::iterator I = DstPreCall.begin(), E = DstPreCall.end();
    200        I != E; ++I)
    201     defaultEvalCall(Bldr, *I, *Call);
    202 
    203   ExplodedNodeSet DstPostCall;
    204   getCheckerManager().runCheckersForPostCall(Dst, DstInvalidated,
    205                                              *Call, *this);
    206 }
    207 
    208 void ExprEngine::VisitCXXNewExpr(const CXXNewExpr *CNE, ExplodedNode *Pred,
    209                                    ExplodedNodeSet &Dst) {
    210   // FIXME: Much of this should eventually migrate to CXXAllocatorCall.
    211   // Also, we need to decide how allocators actually work -- they're not
    212   // really part of the CXXNewExpr because they happen BEFORE the
    213   // CXXConstructExpr subexpression. See PR12014 for some discussion.
    214   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
    215 
    216   unsigned blockCount = currBldrCtx->blockCount();
    217   const LocationContext *LCtx = Pred->getLocationContext();
    218   DefinedOrUnknownSVal symVal = svalBuilder.conjureSymbolVal(0, CNE, LCtx,
    219                                                              CNE->getType(),
    220                                                              blockCount);
    221   ProgramStateRef State = Pred->getState();
    222 
    223   CallEventManager &CEMgr = getStateManager().getCallEventManager();
    224   CallEventRef<CXXAllocatorCall> Call =
    225     CEMgr.getCXXAllocatorCall(CNE, State, LCtx);
    226 
    227   // Invalidate placement args.
    228   // FIXME: Once we figure out how we want allocators to work,
    229   // we should be using the usual pre-/(default-)eval-/post-call checks here.
    230   State = Call->invalidateRegions(blockCount);
    231 
    232   if (CNE->isArray()) {
    233     // FIXME: allocating an array requires simulating the constructors.
    234     // For now, just return a symbolicated region.
    235     const MemRegion *NewReg = cast<loc::MemRegionVal>(symVal).getRegion();
    236     QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
    237     const ElementRegion *EleReg =
    238       getStoreManager().GetElementZeroRegion(NewReg, ObjTy);
    239     State = State->BindExpr(CNE, Pred->getLocationContext(),
    240                             loc::MemRegionVal(EleReg));
    241     Bldr.generateNode(CNE, Pred, State);
    242     return;
    243   }
    244 
    245   // FIXME: Once we have proper support for CXXConstructExprs inside
    246   // CXXNewExpr, we need to make sure that the constructed object is not
    247   // immediately invalidated here. (The placement call should happen before
    248   // the constructor call anyway.)
    249   FunctionDecl *FD = CNE->getOperatorNew();
    250   if (FD && FD->isReservedGlobalPlacementOperator()) {
    251     // Non-array placement new should always return the placement location.
    252     SVal PlacementLoc = State->getSVal(CNE->getPlacementArg(0), LCtx);
    253     SVal Result = svalBuilder.evalCast(PlacementLoc, CNE->getType(),
    254                                        CNE->getPlacementArg(0)->getType());
    255     State = State->BindExpr(CNE, LCtx, Result);
    256   } else {
    257     State = State->BindExpr(CNE, LCtx, symVal);
    258   }
    259 
    260   // If the type is not a record, we won't have a CXXConstructExpr as an
    261   // initializer. Copy the value over.
    262   if (const Expr *Init = CNE->getInitializer()) {
    263     if (!isa<CXXConstructExpr>(Init)) {
    264       QualType ObjTy = CNE->getType()->getAs<PointerType>()->getPointeeType();
    265       (void)ObjTy;
    266       assert(!ObjTy->isRecordType());
    267       SVal Location = State->getSVal(CNE, LCtx);
    268       if (isa<Loc>(Location))
    269         State = State->bindLoc(cast<Loc>(Location), State->getSVal(Init, LCtx));
    270     }
    271   }
    272 
    273   Bldr.generateNode(CNE, Pred, State);
    274 }
    275 
    276 void ExprEngine::VisitCXXDeleteExpr(const CXXDeleteExpr *CDE,
    277                                     ExplodedNode *Pred, ExplodedNodeSet &Dst) {
    278   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
    279   ProgramStateRef state = Pred->getState();
    280   Bldr.generateNode(CDE, Pred, state);
    281 }
    282 
    283 void ExprEngine::VisitCXXCatchStmt(const CXXCatchStmt *CS,
    284                                    ExplodedNode *Pred,
    285                                    ExplodedNodeSet &Dst) {
    286   const VarDecl *VD = CS->getExceptionDecl();
    287   if (!VD) {
    288     Dst.Add(Pred);
    289     return;
    290   }
    291 
    292   const LocationContext *LCtx = Pred->getLocationContext();
    293   SVal V = svalBuilder.conjureSymbolVal(CS, LCtx, VD->getType(),
    294                                         currBldrCtx->blockCount());
    295   ProgramStateRef state = Pred->getState();
    296   state = state->bindLoc(state->getLValue(VD, LCtx), V);
    297 
    298   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
    299   Bldr.generateNode(CS, Pred, state);
    300 }
    301 
    302 void ExprEngine::VisitCXXThisExpr(const CXXThisExpr *TE, ExplodedNode *Pred,
    303                                     ExplodedNodeSet &Dst) {
    304   StmtNodeBuilder Bldr(Pred, Dst, *currBldrCtx);
    305 
    306   // Get the this object region from StoreManager.
    307   const LocationContext *LCtx = Pred->getLocationContext();
    308   const MemRegion *R =
    309     svalBuilder.getRegionManager().getCXXThisRegion(
    310                                   getContext().getCanonicalType(TE->getType()),
    311                                                     LCtx);
    312 
    313   ProgramStateRef state = Pred->getState();
    314   SVal V = state->getSVal(loc::MemRegionVal(R));
    315   Bldr.generateNode(TE, Pred, state->BindExpr(TE, LCtx, V));
    316 }
    317