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