ExprEngineObjC.cpp 10 KB

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