ExprEngineObjC.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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/StaticAnalyzer/Core/CheckerManager.h"
  14. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/ObjCMessage.h"
  16. using namespace clang;
  17. using namespace ento;
  18. void ExprEngine::VisitLvalObjCIvarRefExpr(const ObjCIvarRefExpr *Ex,
  19. ExplodedNode *Pred,
  20. ExplodedNodeSet &Dst) {
  21. const ProgramState *state = Pred->getState();
  22. SVal baseVal = state->getSVal(Ex->getBase());
  23. SVal location = state->getLValue(Ex->getDecl(), baseVal);
  24. ExplodedNodeSet dstIvar;
  25. StmtNodeBuilder Bldr(Pred, dstIvar, *currentBuilderContext);
  26. Bldr.generateNode(Ex, Pred, state->BindExpr(Ex, location));
  27. // Perform the post-condition check of the ObjCIvarRefExpr and store
  28. // the created nodes in 'Dst'.
  29. getCheckerManager().runCheckersForPostStmt(Dst, dstIvar, Ex, *this);
  30. }
  31. void ExprEngine::VisitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt *S,
  32. ExplodedNode *Pred,
  33. ExplodedNodeSet &Dst) {
  34. getCheckerManager().runCheckersForPreStmt(Dst, Pred, S, *this);
  35. }
  36. void ExprEngine::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S,
  37. ExplodedNode *Pred,
  38. ExplodedNodeSet &Dst) {
  39. // ObjCForCollectionStmts are processed in two places. This method
  40. // handles the case where an ObjCForCollectionStmt* occurs as one of the
  41. // statements within a basic block. This transfer function does two things:
  42. //
  43. // (1) binds the next container value to 'element'. This creates a new
  44. // node in the ExplodedGraph.
  45. //
  46. // (2) binds the value 0/1 to the ObjCForCollectionStmt* itself, indicating
  47. // whether or not the container has any more elements. This value
  48. // will be tested in ProcessBranch. We need to explicitly bind
  49. // this value because a container can contain nil elements.
  50. //
  51. // FIXME: Eventually this logic should actually do dispatches to
  52. // 'countByEnumeratingWithState:objects:count:' (NSFastEnumeration).
  53. // This will require simulating a temporary NSFastEnumerationState, either
  54. // through an SVal or through the use of MemRegions. This value can
  55. // be affixed to the ObjCForCollectionStmt* instead of 0/1; when the loop
  56. // terminates we reclaim the temporary (it goes out of scope) and we
  57. // we can test if the SVal is 0 or if the MemRegion is null (depending
  58. // on what approach we take).
  59. //
  60. // For now: simulate (1) by assigning either a symbol or nil if the
  61. // container is empty. Thus this transfer function will by default
  62. // result in state splitting.
  63. const Stmt *elem = S->getElement();
  64. const ProgramState *state = Pred->getState();
  65. SVal elementV;
  66. StmtNodeBuilder Bldr(Pred, Dst, *currentBuilderContext);
  67. if (const DeclStmt *DS = dyn_cast<DeclStmt>(elem)) {
  68. const VarDecl *elemD = cast<VarDecl>(DS->getSingleDecl());
  69. assert(elemD->getInit() == 0);
  70. elementV = state->getLValue(elemD, Pred->getLocationContext());
  71. }
  72. else {
  73. elementV = state->getSVal(elem);
  74. }
  75. ExplodedNodeSet dstLocation;
  76. Bldr.takeNodes(Pred);
  77. evalLocation(dstLocation, elem, Pred, state, elementV, NULL, false);
  78. Bldr.addNodes(dstLocation);
  79. for (ExplodedNodeSet::iterator NI = dstLocation.begin(),
  80. NE = dstLocation.end(); NI!=NE; ++NI) {
  81. Pred = *NI;
  82. const ProgramState *state = Pred->getState();
  83. // Handle the case where the container still has elements.
  84. SVal TrueV = svalBuilder.makeTruthVal(1);
  85. const ProgramState *hasElems = state->BindExpr(S, TrueV);
  86. // Handle the case where the container has no elements.
  87. SVal FalseV = svalBuilder.makeTruthVal(0);
  88. const ProgramState *noElems = state->BindExpr(S, FalseV);
  89. if (loc::MemRegionVal *MV = dyn_cast<loc::MemRegionVal>(&elementV))
  90. if (const TypedValueRegion *R =
  91. dyn_cast<TypedValueRegion>(MV->getRegion())) {
  92. // FIXME: The proper thing to do is to really iterate over the
  93. // container. We will do this with dispatch logic to the store.
  94. // For now, just 'conjure' up a symbolic value.
  95. QualType T = R->getValueType();
  96. assert(Loc::isLocType(T));
  97. unsigned Count = currentBuilderContext->getCurrentBlockCount();
  98. SymbolRef Sym = SymMgr.getConjuredSymbol(elem, T, Count);
  99. SVal V = svalBuilder.makeLoc(Sym);
  100. hasElems = hasElems->bindLoc(elementV, V);
  101. // Bind the location to 'nil' on the false branch.
  102. SVal nilV = svalBuilder.makeIntVal(0, T);
  103. noElems = noElems->bindLoc(elementV, nilV);
  104. }
  105. // Create the new nodes.
  106. Bldr.generateNode(S, Pred, hasElems);
  107. Bldr.generateNode(S, Pred, noElems);
  108. }
  109. }
  110. void ExprEngine::VisitObjCMessage(const ObjCMessage &msg,
  111. ExplodedNode *Pred,
  112. ExplodedNodeSet &Dst) {
  113. // Handle the previsits checks.
  114. ExplodedNodeSet dstPrevisit;
  115. getCheckerManager().runCheckersForPreObjCMessage(dstPrevisit, Pred,
  116. msg, *this);
  117. // Proceed with evaluate the message expression.
  118. ExplodedNodeSet dstEval;
  119. StmtNodeBuilder Bldr(dstPrevisit, dstEval, *currentBuilderContext);
  120. for (ExplodedNodeSet::iterator DI = dstPrevisit.begin(),
  121. DE = dstPrevisit.end(); DI != DE; ++DI) {
  122. ExplodedNode *Pred = *DI;
  123. bool RaisesException = false;
  124. if (const Expr *Receiver = msg.getInstanceReceiver()) {
  125. const ProgramState *state = Pred->getState();
  126. SVal recVal = state->getSVal(Receiver);
  127. if (!recVal.isUndef()) {
  128. // Bifurcate the state into nil and non-nil ones.
  129. DefinedOrUnknownSVal receiverVal = cast<DefinedOrUnknownSVal>(recVal);
  130. const ProgramState *notNilState, *nilState;
  131. llvm::tie(notNilState, nilState) = state->assume(receiverVal);
  132. // There are three cases: can be nil or non-nil, must be nil, must be
  133. // non-nil. We ignore must be nil, and merge the rest two into non-nil.
  134. if (nilState && !notNilState) {
  135. continue;
  136. }
  137. // Check if the "raise" message was sent.
  138. assert(notNilState);
  139. if (msg.getSelector() == RaiseSel)
  140. RaisesException = true;
  141. // If we raise an exception, for now treat it as a sink.
  142. // Eventually we will want to handle exceptions properly.
  143. // Dispatch to plug-in transfer function.
  144. evalObjCMessage(Bldr, msg, Pred, notNilState, RaisesException);
  145. }
  146. }
  147. else if (const ObjCInterfaceDecl *Iface = msg.getReceiverInterface()) {
  148. IdentifierInfo* ClsName = Iface->getIdentifier();
  149. Selector S = msg.getSelector();
  150. // Check for special instance methods.
  151. if (!NSExceptionII) {
  152. ASTContext &Ctx = getContext();
  153. NSExceptionII = &Ctx.Idents.get("NSException");
  154. }
  155. if (ClsName == NSExceptionII) {
  156. enum { NUM_RAISE_SELECTORS = 2 };
  157. // Lazily create a cache of the selectors.
  158. if (!NSExceptionInstanceRaiseSelectors) {
  159. ASTContext &Ctx = getContext();
  160. NSExceptionInstanceRaiseSelectors =
  161. new Selector[NUM_RAISE_SELECTORS];
  162. SmallVector<IdentifierInfo*, NUM_RAISE_SELECTORS> II;
  163. unsigned idx = 0;
  164. // raise:format:
  165. II.push_back(&Ctx.Idents.get("raise"));
  166. II.push_back(&Ctx.Idents.get("format"));
  167. NSExceptionInstanceRaiseSelectors[idx++] =
  168. Ctx.Selectors.getSelector(II.size(), &II[0]);
  169. // raise:format::arguments:
  170. II.push_back(&Ctx.Idents.get("arguments"));
  171. NSExceptionInstanceRaiseSelectors[idx++] =
  172. Ctx.Selectors.getSelector(II.size(), &II[0]);
  173. }
  174. for (unsigned i = 0; i < NUM_RAISE_SELECTORS; ++i)
  175. if (S == NSExceptionInstanceRaiseSelectors[i]) {
  176. RaisesException = true;
  177. break;
  178. }
  179. }
  180. // If we raise an exception, for now treat it as a sink.
  181. // Eventually we will want to handle exceptions properly.
  182. // Dispatch to plug-in transfer function.
  183. evalObjCMessage(Bldr, msg, Pred, Pred->getState(), RaisesException);
  184. }
  185. }
  186. // Finally, perform the post-condition check of the ObjCMessageExpr and store
  187. // the created nodes in 'Dst'.
  188. getCheckerManager().runCheckersForPostObjCMessage(Dst, dstEval, msg, *this);
  189. }
  190. void ExprEngine::evalObjCMessage(StmtNodeBuilder &Bldr,
  191. const ObjCMessage &msg,
  192. ExplodedNode *Pred,
  193. const ProgramState *state,
  194. bool GenSink) {
  195. // First handle the return value.
  196. SVal ReturnValue = UnknownVal();
  197. // Some method families have known return values.
  198. switch (msg.getMethodFamily()) {
  199. default:
  200. break;
  201. case OMF_autorelease:
  202. case OMF_retain:
  203. case OMF_self: {
  204. // These methods return their receivers.
  205. const Expr *ReceiverE = msg.getInstanceReceiver();
  206. if (ReceiverE)
  207. ReturnValue = state->getSVal(ReceiverE);
  208. break;
  209. }
  210. }
  211. // If we failed to figure out the return value, use a conjured value instead.
  212. if (ReturnValue.isUnknown()) {
  213. SValBuilder &SVB = getSValBuilder();
  214. QualType ResultTy = msg.getResultType(getContext());
  215. unsigned Count = currentBuilderContext->getCurrentBlockCount();
  216. const Expr *CurrentE = cast<Expr>(currentStmt);
  217. ReturnValue = SVB.getConjuredSymbolVal(NULL, CurrentE, ResultTy, Count);
  218. }
  219. // Bind the return value.
  220. state = state->BindExpr(currentStmt, ReturnValue);
  221. // Invalidate the arguments (and the receiver)
  222. const LocationContext *LC = Pred->getLocationContext();
  223. state = invalidateArguments(state, CallOrObjCMessage(msg, state), LC);
  224. // And create the new node.
  225. Bldr.generateNode(msg.getOriginExpr(), Pred, state, GenSink);
  226. assert(Bldr.hasGeneratedNodes());
  227. }