ExprEngineObjC.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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() == 0);
  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, NULL, 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 (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV))
  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. static bool isSubclass(const ObjCInterfaceDecl *Class, IdentifierInfo *II) {
  116. if (!Class)
  117. return false;
  118. if (Class->getIdentifier() == II)
  119. return true;
  120. return isSubclass(Class->getSuperClass(), II);
  121. }
  122. void ExprEngine::VisitObjCMessage(const ObjCMessageExpr *ME,
  123. ExplodedNode *Pred,
  124. ExplodedNodeSet &Dst) {
  125. CallEventManager &CEMgr = getStateManager().getCallEventManager();
  126. CallEventRef<ObjCMethodCall> Msg =
  127. CEMgr.getObjCMethodCall(ME, Pred->getState(), Pred->getLocationContext());
  128. // Handle the previsits checks.
  129. ExplodedNodeSet dstPrevisit;
  130. getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
  131. *Msg, *this);
  132. ExplodedNodeSet dstGenericPrevisit;
  133. getCheckerManager().runCheckersForPreCall(dstGenericPrevisit, dstPrevisit,
  134. *Msg, *this);
  135. // Proceed with evaluate the message expression.
  136. ExplodedNodeSet dstEval;
  137. StmtNodeBuilder Bldr(dstGenericPrevisit, dstEval, *currBldrCtx);
  138. for (ExplodedNodeSet::iterator DI = dstGenericPrevisit.begin(),
  139. DE = dstGenericPrevisit.end(); DI != DE; ++DI) {
  140. ExplodedNode *Pred = *DI;
  141. ProgramStateRef State = Pred->getState();
  142. CallEventRef<ObjCMethodCall> UpdatedMsg = Msg.cloneWithState(State);
  143. if (UpdatedMsg->isInstanceMessage()) {
  144. SVal recVal = UpdatedMsg->getReceiverSVal();
  145. if (!recVal.isUndef()) {
  146. // Bifurcate the state into nil and non-nil ones.
  147. DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
  148. ProgramStateRef notNilState, nilState;
  149. llvm::tie(notNilState, nilState) = State->assume(receiverVal);
  150. // There are three cases: can be nil or non-nil, must be nil, must be
  151. // non-nil. We ignore must be nil, and merge the rest two into non-nil.
  152. // FIXME: This ignores many potential bugs (<rdar://problem/11733396>).
  153. // Revisit once we have lazier constraints.
  154. if (nilState && !notNilState) {
  155. continue;
  156. }
  157. // Check if the "raise" message was sent.
  158. assert(notNilState);
  159. if (Msg->getSelector() == RaiseSel) {
  160. // If we raise an exception, for now treat it as a sink.
  161. // Eventually we will want to handle exceptions properly.
  162. Bldr.generateSink(currStmt, Pred, State);
  163. continue;
  164. }
  165. // Generate a transition to non-Nil state.
  166. if (notNilState != State) {
  167. Pred = Bldr.generateNode(currStmt, Pred, notNilState);
  168. assert(Pred && "Should have cached out already!");
  169. }
  170. }
  171. } else {
  172. // Check for special class methods.
  173. if (const ObjCInterfaceDecl *Iface = Msg->getReceiverInterface()) {
  174. if (!NSExceptionII) {
  175. ASTContext &Ctx = getContext();
  176. NSExceptionII = &Ctx.Idents.get("NSException");
  177. }
  178. if (isSubclass(Iface, NSExceptionII)) {
  179. enum { NUM_RAISE_SELECTORS = 2 };
  180. // Lazily create a cache of the selectors.
  181. if (!NSExceptionInstanceRaiseSelectors) {
  182. ASTContext &Ctx = getContext();
  183. NSExceptionInstanceRaiseSelectors =
  184. new Selector[NUM_RAISE_SELECTORS];
  185. SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
  186. unsigned idx = 0;
  187. // raise:format:
  188. II.push_back(&Ctx.Idents.get("raise"));
  189. II.push_back(&Ctx.Idents.get("format"));
  190. NSExceptionInstanceRaiseSelectors[idx++] =
  191. Ctx.Selectors.getSelector(II.size(), &II[0]);
  192. // raise:format:arguments:
  193. II.push_back(&Ctx.Idents.get("arguments"));
  194. NSExceptionInstanceRaiseSelectors[idx++] =
  195. Ctx.Selectors.getSelector(II.size(), &II[0]);
  196. }
  197. Selector S = Msg->getSelector();
  198. bool RaisesException = false;
  199. for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i) {
  200. if (S == NSExceptionInstanceRaiseSelectors[i]) {
  201. RaisesException = true;
  202. break;
  203. }
  204. }
  205. if (RaisesException) {
  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. }
  214. defaultEvalCall(Bldr, Pred, *UpdatedMsg);
  215. }
  216. ExplodedNodeSet dstPostvisit;
  217. getCheckerManager().runCheckersForPostCall(dstPostvisit, dstEval,
  218. *Msg, *this);
  219. // Finally, perform the post-condition check of the ObjCMessageExpr and store
  220. // the created nodes in 'Dst'.
  221. getCheckerManager().runCheckersForPostObjCMessage(Dst, dstPostvisit,
  222. *Msg, *this);
  223. }