Coverage Report

Created: 2020-09-22 08:39

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/ExprEngineObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//=-- ExprEngineObjC.cpp - ExprEngine support for Objective-C ---*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file defines ExprEngine's support for Objective-C expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/StmtObjC.h"
14
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
15
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
16
#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
17
18
using namespace clang;
19
using namespace ento;
20
21
void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
22
                                          ExplodedNode *Pred,
23
1.05k
                                          ExplodedNodeSet &Dst) {
24
1.05k
  ProgramStateRef state = Pred->getState();
25
1.05k
  const LocationContext *LCtx = Pred->getLocationContext();
26
1.05k
  SVal baseVal = state->getSVal(Ex->getBase(), LCtx);
27
1.05k
  SVal location = state->getLValue(Ex->getDecl(), baseVal);
28
29
1.05k
  ExplodedNodeSet dstIvar;
30
1.05k
  StmtNodeBuilder Bldr(Pred, dstIvar, *currBldrCtx);
31
1.05k
  Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, LCtx, location));
32
33
  // Perform the post-condition check of the ObjCIvarRefExpr and store
34
  // the created nodes in 'Dst'.
35
1.05k
  getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
36
1.05k
}
37
38
void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
39
                                             ExplodedNode *Pred,
40
19
                                             ExplodedNodeSet &Dst) {
41
19
  getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
42
19
}
43
44
/// Generate a node in \p Bldr for an iteration statement using ObjC
45
/// for-loop iterator.
46
static void populateObjCForDestinationSet(
47
    ExplodedNodeSet &dstLocation, SValBuilder &svalBuilder,
48
    const ObjCForCollectionStmt *S, const Stmt *elem, SVal elementV,
49
    SymbolManager &SymMgr, const NodeBuilderContext *currBldrCtx,
50
517
    StmtNodeBuilder &Bldr, bool hasElements) {
51
52
517
  for (ExplodedNode *Pred : dstLocation) {
53
517
    ProgramStateRef state = Pred->getState();
54
517
    const LocationContext *LCtx = Pred->getLocationContext();
55
56
517
    ProgramStateRef nextState =
57
517
        ExprEngine::setWhetherHasMoreIteration(state, S, LCtx, hasElements);
58
59
517
    if (auto MV = elementV.getAs<loc::MemRegionVal>())
60
517
      if (const auto *R = dyn_cast<TypedValueRegion>(MV->getRegion())) {
61
        // FIXME: The proper thing to do is to really iterate over the
62
        //  container.  We will do this with dispatch logic to the store.
63
        //  For now, just 'conjure' up a symbolic value.
64
517
        QualType T = R->getValueType();
65
517
        assert(Loc::isLocType(T));
66
67
517
        SVal V;
68
517
        if (hasElements) {
69
257
          SymbolRef Sym = SymMgr.conjureSymbol(elem, LCtx, T,
70
257
                                               currBldrCtx->blockCount());
71
257
          V = svalBuilder.makeLoc(Sym);
72
260
        } else {
73
260
          V = svalBuilder.makeIntVal(0, T);
74
260
        }
75
76
517
        nextState = nextState->bindLoc(elementV, V, LCtx);
77
517
      }
78
79
517
    Bldr.generateNode(S, Pred, nextState);
80
517
  }
81
517
}
82
83
void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
84
                                            ExplodedNode *Pred,
85
260
                                            ExplodedNodeSet &Dst) {
86
87
  // ObjCForCollectionStmts are processed in two places.  This method
88
  // handles the case where an ObjCForCollectionStmt* occurs as one of the
89
  // statements within a basic block.  This transfer function does two things:
90
  //
91
  //  (1) binds the next container value to 'element'.  This creates a new
92
  //      node in the ExplodedGraph.
93
  //
94
  //  (2) note whether the collection has any more elements (or in other words,
95
  //      whether the loop has more iterations). This will be tested in
96
  //      processBranch.
97
  //
98
  // FIXME: Eventually this logic should actually do dispatches to
99
  //   'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
100
  //   This will require simulating a temporary NSFastEnumerationState, either
101
  //   through an SVal or through the use of MemRegions.  This value can
102
  //   be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
103
  //   terminates we reclaim the temporary (it goes out of scope) and we
104
  //   we can test if the SVal is 0 or if the MemRegion is null (depending
105
  //   on what approach we take).
106
  //
107
  //  For now: simulate (1) by assigning either a symbol or nil if the
108
  //    container is empty.  Thus this transfer function will by default
109
  //    result in state splitting.
110
111
260
  const Stmt *elem = S->getElement();
112
260
  const Stmt *collection = S->getCollection();
113
260
  ProgramStateRef state = Pred->getState();
114
260
  SVal collectionV = state->getSVal(collection, Pred->getLocationContext());
115
116
260
  SVal elementV;
117
260
  if (const auto *DS = dyn_cast<DeclStmt>(elem)) {
118
127
    const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
119
127
    assert(elemD->getInit() == nullptr);
120
127
    elementV = state->getLValue(elemD, Pred->getLocationContext());
121
133
  } else {
122
133
    elementV = state->getSVal(elem, Pred->getLocationContext());
123
133
  }
124
125
260
  bool isContainerNull = state->isNull(collectionV).isConstrainedTrue();
126
127
260
  ExplodedNodeSet dstLocation;
128
260
  evalLocation(dstLocation, S, elem, Pred, state, elementV, false);
129
130
260
  ExplodedNodeSet Tmp;
131
260
  StmtNodeBuilder Bldr(Pred, Tmp, *currBldrCtx);
132
133
260
  if (!isContainerNull)
134
257
    populateObjCForDestinationSet(dstLocation, svalBuilder, S, elem, elementV,
135
257
                                  SymMgr, currBldrCtx, Bldr,
136
257
                                  /*hasElements=*/true);
137
138
260
  populateObjCForDestinationSet(dstLocation, svalBuilder, S, elem, elementV,
139
260
                                SymMgr, currBldrCtx, Bldr,
140
260
                                /*hasElements=*/false);
141
142
  // Finally, run any custom checkers.
143
  // FIXME: Eventually all pre- and post-checks should live in VisitStmt.
144
260
  getCheckerManager().runCheckersForPostStmt(Dst, Tmp, S, *this);
145
260
}
146
147
void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME,
148
                                  ExplodedNode *Pred,
149
4.18k
                                  ExplodedNodeSet &Dst) {
150
4.18k
  CallEventManager &CEMgr = getStateManager().getCallEventManager();
151
4.18k
  CallEventRef<ObjCMethodCall> Msg =
152
4.18k
    CEMgr.getObjCMethodCall(ME, Pred->getState(), Pred->getLocationContext());
153
154
  // There are three cases for the receiver:
155
  //   (1) it is definitely nil,
156
  //   (2) it is definitely non-nil, and
157
  //   (3) we don't know.
158
  //
159
  // If the receiver is definitely nil, we skip the pre/post callbacks and
160
  // instead call the ObjCMessageNil callbacks and return.
161
  //
162
  // If the receiver is definitely non-nil, we call the pre- callbacks,
163
  // evaluate the call, and call the post- callbacks.
164
  //
165
  // If we don't know, we drop the potential nil flow and instead
166
  // continue from the assumed non-nil state as in (2). This approach
167
  // intentionally drops coverage in order to prevent false alarms
168
  // in the following scenario:
169
  //
170
  // id result = [o someMethod]
171
  // if (result) {
172
  //   if (!o) {
173
  //     // <-- This program point should be unreachable because if o is nil
174
  //     // it must the case that result is nil as well.
175
  //   }
176
  // }
177
  //
178
  // We could avoid dropping coverage by performing an explicit case split
179
  // on each method call -- but this would get very expensive. An alternative
180
  // would be to introduce lazy constraints.
181
  // FIXME: This ignores many potential bugs (<rdar://problem/11733396>).
182
  // Revisit once we have lazier constraints.
183
4.18k
  if (Msg->isInstanceMessage()) {
184
3.17k
    SVal recVal = Msg->getReceiverSVal();
185
3.17k
    if (!recVal.isUndef()) {
186
      // Bifurcate the state into nil and non-nil ones.
187
3.16k
      DefinedOrUnknownSVal receiverVal =
188
3.16k
          recVal.castAs<DefinedOrUnknownSVal>();
189
3.16k
      ProgramStateRef State = Pred->getState();
190
191
3.16k
      ProgramStateRef notNilState, nilState;
192
3.16k
      std::tie(notNilState, nilState) = State->assume(receiverVal);
193
194
      // Receiver is definitely nil, so run ObjCMessageNil callbacks and return.
195
3.16k
      if (nilState && 
!notNilState1.88k
) {
196
96
        ExplodedNodeSet dstNil;
197
96
        StmtNodeBuilder Bldr(Pred, dstNil, *currBldrCtx);
198
96
        bool HasTag = Pred->getLocation().getTag();
199
96
        Pred = Bldr.generateNode(ME, Pred, nilState, nullptr,
200
96
                                 ProgramPoint::PreStmtKind);
201
96
        assert((Pred || HasTag) && "Should have cached out already!");
202
96
        (void)HasTag;
203
96
        if (!Pred)
204
0
          return;
205
206
96
        ExplodedNodeSet dstPostCheckers;
207
96
        getCheckerManager().runCheckersForObjCMessageNil(dstPostCheckers, Pred,
208
96
                                                         *Msg, *this);
209
96
        for (auto I : dstPostCheckers)
210
89
          finishArgumentConstruction(Dst, I, *Msg);
211
96
        return;
212
96
      }
213
214
3.07k
      ExplodedNodeSet dstNonNil;
215
3.07k
      StmtNodeBuilder Bldr(Pred, dstNonNil, *currBldrCtx);
216
      // Generate a transition to the non-nil state, dropping any potential
217
      // nil flow.
218
3.07k
      if (notNilState != State) {
219
1.78k
        bool HasTag = Pred->getLocation().getTag();
220
1.78k
        Pred = Bldr.generateNode(ME, Pred, notNilState);
221
1.78k
        assert((Pred || HasTag) && "Should have cached out already!");
222
1.78k
        (void)HasTag;
223
1.78k
        if (!Pred)
224
0
          return;
225
4.09k
      }
226
3.07k
    }
227
3.17k
  }
228
229
  // Handle the previsits checks.
230
4.09k
  ExplodedNodeSet dstPrevisit;
231
4.09k
  getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
232
4.09k
                                                   *Msg, *this);
233
4.09k
  ExplodedNodeSet dstGenericPrevisit;
234
4.09k
  getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
235
4.09k
                                            *Msg, *this);
236
237
  // Proceed with evaluate the message expression.
238
4.09k
  ExplodedNodeSet dstEval;
239
4.09k
  StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
240
241
4.09k
  for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
242
8.09k
       DE = dstGenericPrevisit.end(); DI != DE; 
++DI4.00k
) {
243
4.00k
    ExplodedNode *Pred = *DI;
244
4.00k
    ProgramStateRef State = Pred->getState();
245
4.00k
    CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
246
247
4.00k
    if (UpdatedMsg->isInstanceMessage()) {
248
3.00k
      SVal recVal = UpdatedMsg->getReceiverSVal();
249
3.00k
      if (!recVal.isUndef()) {
250
3.00k
        if (ObjCNoRet.isImplicitNoReturn(ME)) {
251
          // If we raise an exception, for now treat it as a sink.
252
          // Eventually we will want to handle exceptions properly.
253
2
          Bldr.generateSink(ME, Pred, State);
254
2
          continue;
255
2
        }
256
1.00k
      }
257
1.00k
    } else {
258
      // Check for special class methods that are known to not return
259
      // and that we should treat as a sink.
260
1.00k
      if (ObjCNoRet.isImplicitNoReturn(ME)) {
261
        // If we raise an exception, for now treat it as a sink.
262
        // Eventually we will want to handle exceptions properly.
263
5
        Bldr.generateSink(ME, Pred, Pred->getState());
264
5
        continue;
265
5
      }
266
4.00k
    }
267
268
4.00k
    defaultEvalCall(Bldr, Pred, *UpdatedMsg);
269
4.00k
  }
270
271
  // If there were constructors called for object-type arguments, clean them up.
272
4.09k
  ExplodedNodeSet dstArgCleanup;
273
4.09k
  for (auto I : dstEval)
274
3.45k
    finishArgumentConstruction(dstArgCleanup, I, *Msg);
275
276
4.09k
  ExplodedNodeSet dstPostvisit;
277
4.09k
  getCheckerManager().runCheckersForPostCall(dstPostvisit, dstArgCleanup,
278
4.09k
                                             *Msg, *this);
279
280
  // Finally, perform the post-condition check of the ObjCMessageExpr and store
281
  // the created nodes in 'Dst'.
282
4.09k
  getCheckerManager().runCheckersForPostObjCMessage(Dst, dstPostvisit,
283
4.09k
                                                    *Msg, *this);
284
4.09k
}