1 //=-- ExprEngineObjC.cpp - ExprEngine support for Objective-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 ExprEngine's support for Objective-C expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/StmtObjC.h"
15 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
16 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
17 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
18 
19 using namespace clang;
20 using namespace ento;
21 
22 void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
23                                           ExplodedNode *Pred,
24                                           ExplodedNodeSet &Dst) {
25   ProgramStateRef state = Pred->getState();
26   const LocationContext *LCtx = Pred->getLocationContext();
27   SVal baseVal = state->getSVal(Ex->getBase(), LCtx);
28 
29   // First check that the base object is valid.
30   ExplodedNodeSet DstLoc;
31   evalLocation(DstLoc, Ex, Ex, Pred, state, baseVal,
32                /*Tag=*/0, /*isLoad=*/true);
33 
34   // Bind the lvalue to the expression.
35   SVal location = state->getLValue(Ex->getDecl(), baseVal);
36 
37   ExplodedNodeSet dstIvar;
38   StmtNodeBuilder Bldr(DstLoc, dstIvar, *currBldrCtx);
39   for (ExplodedNodeSet::iterator I = DstLoc.begin(), E = DstLoc.end();
40        I != E; ++I) {
41     Bldr.generateNode(Ex, (*I), (*I)->getState()->BindExpr(Ex, LCtx, location));
42   }
43 
44   // Perform the post-condition check of the ObjCIvarRefExpr and store
45   // the created nodes in 'Dst'.
46   getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
47 }
48 
49 void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
50                                              ExplodedNode *Pred,
51                                              ExplodedNodeSet &Dst) {
52   getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
53 }
54 
55 void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
56                                             ExplodedNode *Pred,
57                                             ExplodedNodeSet &Dst) {
58 
59   // ObjCForCollectionStmts are processed in two places.  This method
60   // handles the case where an ObjCForCollectionStmt* occurs as one of the
61   // statements within a basic block.  This transfer function does two things:
62   //
63   //  (1) binds the next container value to 'element'.  This creates a new
64   //      node in the ExplodedGraph.
65   //
66   //  (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
67   //      whether or not the container has any more elements.  This value
68   //      will be tested in ProcessBranch.  We need to explicitly bind
69   //      this value because a container can contain nil elements.
70   //
71   // FIXME: Eventually this logic should actually do dispatches to
72   //   'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
73   //   This will require simulating a temporary NSFastEnumerationState, either
74   //   through an SVal or through the use of MemRegions.  This value can
75   //   be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
76   //   terminates we reclaim the temporary (it goes out of scope) and we
77   //   we can test if the SVal is 0 or if the MemRegion is null (depending
78   //   on what approach we take).
79   //
80   //  For now: simulate (1) by assigning either a symbol or nil if the
81   //    container is empty.  Thus this transfer function will by default
82   //    result in state splitting.
83 
84   const Stmt *elem = S->getElement();
85   ProgramStateRef state = Pred->getState();
86   SVal elementV;
87 
88   if (const DeclStmt *DS = dyn_cast<DeclStmt>(elem)) {
89     const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
90     assert(elemD->getInit() == 0);
91     elementV = state->getLValue(elemD, Pred->getLocationContext());
92   }
93   else {
94     elementV = state->getSVal(elem, Pred->getLocationContext());
95   }
96 
97   ExplodedNodeSet dstLocation;
98   evalLocation(dstLocation, S, elem, Pred, state, elementV, NULL, false);
99 
100   ExplodedNodeSet Tmp;
101   StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
102 
103   for (ExplodedNodeSet::iterator NI = dstLocation.begin(),
104        NE = dstLocation.end(); NI!=NE; ++NI) {
105     Pred = *NI;
106     ProgramStateRef state = Pred->getState();
107     const LocationContext *LCtx = Pred->getLocationContext();
108 
109     // Handle the case where the container still has elements.
110     SVal TrueV = svalBuilder.makeTruthVal(1);
111     ProgramStateRef hasElems = state->BindExpr(S, LCtx, TrueV);
112 
113     // Handle the case where the container has no elements.
114     SVal FalseV = svalBuilder.makeTruthVal(0);
115     ProgramStateRef noElems = state->BindExpr(S, LCtx, FalseV);
116 
117     if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV))
118       if (const TypedValueRegion *R =
119           dyn_cast<TypedValueRegion>(MV->getRegion())) {
120         // FIXME: The proper thing to do is to really iterate over the
121         //  container.  We will do this with dispatch logic to the store.
122         //  For now, just 'conjure' up a symbolic value.
123         QualType T = R->getValueType();
124         assert(Loc::isLocType(T));
125         SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
126                                              currBldrCtx->blockCount());
127         SVal V = svalBuilder.makeLoc(Sym);
128         hasElems = hasElems->bindLoc(elementV, V);
129 
130         // Bind the location to 'nil' on the false branch.
131         SVal nilV = svalBuilder.makeIntVal(0, T);
132         noElems = noElems->bindLoc(elementV, nilV);
133       }
134 
135     // Create the new nodes.
136     Bldr.generateNode(S, Pred, hasElems);
137     Bldr.generateNode(S, Pred, noElems);
138   }
139 
140   // Finally, run any custom checkers.
141   // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
142   getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
143 }
144 
145 void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME,
146                                   ExplodedNode *Pred,
147                                   ExplodedNodeSet &Dst) {
148   CallEventManager &CEMgr = getStateManager().getCallEventManager();
149   CallEventRef<ObjCMethodCall> Msg =
150     CEMgr.getObjCMethodCall(ME, Pred->getState(), Pred->getLocationContext());
151 
152   // Handle the previsits checks.
153   ExplodedNodeSet dstPrevisit;
154   getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
155                                                    *Msg, *this);
156   ExplodedNodeSet dstGenericPrevisit;
157   getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
158                                             *Msg, *this);
159 
160   // Proceed with evaluate the message expression.
161   ExplodedNodeSet dstEval;
162   StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
163 
164   for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
165        DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
166     ExplodedNode *Pred = *DI;
167     ProgramStateRef State = Pred->getState();
168     CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
169 
170     if (UpdatedMsg->isInstanceMessage()) {
171       SVal recVal = UpdatedMsg->getReceiverSVal();
172       if (!recVal.isUndef()) {
173         // Bifurcate the state into nil and non-nil ones.
174         DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
175 
176         ProgramStateRef notNilState, nilState;
177         llvm::tie(notNilState, nilState) = State->assume(receiverVal);
178 
179         // There are three cases: can be nil or non-nil, must be nil, must be
180         // non-nil. We ignore must be nil, and merge the rest two into non-nil.
181         // FIXME: This ignores many potential bugs (<rdar://problem/11733396>).
182         // Revisit once we have lazier constraints.
183         if (nilState && !notNilState) {
184           continue;
185         }
186 
187         // Check if the "raise" message was sent.
188         assert(notNilState);
189         if (ObjCNoRet.isImplicitNoReturn(ME)) {
190           // If we raise an exception, for now treat it as a sink.
191           // Eventually we will want to handle exceptions properly.
192           Bldr.generateSink(currStmt, Pred, State);
193           continue;
194         }
195 
196         // Generate a transition to non-Nil state.
197         if (notNilState != State) {
198           Pred = Bldr.generateNode(currStmt, Pred, notNilState);
199           assert(Pred && "Should have cached out already!");
200         }
201       }
202     } else {
203       // Check for special class methods that are known to not return
204       // and that we should treat as a sink.
205       if (ObjCNoRet.isImplicitNoReturn(ME)) {
206         // If we raise an exception, for now treat it as a sink.
207         // Eventually we will want to handle exceptions properly.
208         Bldr.generateSink(currStmt, Pred, Pred->getState());
209         continue;
210       }
211     }
212 
213     defaultEvalCall(Bldr, Pred, *UpdatedMsg);
214   }
215 
216   ExplodedNodeSet dstPostvisit;
217   getCheckerManager().runCheckersForPostCall(dstPostvisit, dstEval,
218                                              *Msg, *this);
219 
220   // Finally, perform the post-condition check of the ObjCMessageExpr and store
221   // the created nodes in 'Dst'.
222   getCheckerManager().runCheckersForPostObjCMessage(Dst, dstPostvisit,
223                                                     *Msg, *this);
224 }
225