CallEvent.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. //===- Calls.cpp - Wrapper for all function and method calls ------*- 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. /// \file This file defines CallEvent and its subclasses, which represent path-
  11. /// sensitive instances of different kinds of function and method calls
  12. /// (C, C++, and Objective-C).
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
  16. #include "clang/Analysis/ProgramPoint.h"
  17. #include "clang/AST/ParentMap.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. using namespace clang;
  21. using namespace ento;
  22. QualType CallEvent::getResultType() const {
  23. QualType ResultTy = getDeclaredResultType();
  24. if (ResultTy.isNull())
  25. ResultTy = getOriginExpr()->getType();
  26. return ResultTy;
  27. }
  28. static bool isCallbackArg(SVal V, QualType T) {
  29. // If the parameter is 0, it's harmless.
  30. if (V.isZeroConstant())
  31. return false;
  32. // If a parameter is a block or a callback, assume it can modify pointer.
  33. if (T->isBlockPointerType() ||
  34. T->isFunctionPointerType() ||
  35. T->isObjCSelType())
  36. return true;
  37. // Check if a callback is passed inside a struct (for both, struct passed by
  38. // reference and by value). Dig just one level into the struct for now.
  39. if (isa<PointerType>(T) || isa<ReferenceType>(T))
  40. T = T->getPointeeType();
  41. if (const RecordType *RT = T->getAsStructureType()) {
  42. const RecordDecl *RD = RT->getDecl();
  43. for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
  44. I != E; ++I) {
  45. QualType FieldT = I->getType();
  46. if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
  47. return true;
  48. }
  49. }
  50. return false;
  51. }
  52. bool CallEvent::hasNonZeroCallbackArg() const {
  53. unsigned NumOfArgs = getNumArgs();
  54. // If calling using a function pointer, assume the function does not
  55. // have a callback. TODO: We could check the types of the arguments here.
  56. if (!getDecl())
  57. return false;
  58. unsigned Idx = 0;
  59. for (CallEvent::param_type_iterator I = param_type_begin(),
  60. E = param_type_end();
  61. I != E && Idx < NumOfArgs; ++I, ++Idx) {
  62. if (NumOfArgs <= Idx)
  63. break;
  64. if (isCallbackArg(getArgSVal(Idx), *I))
  65. return true;
  66. }
  67. return false;
  68. }
  69. /// \brief Returns true if a type is a pointer-to-const or reference-to-const
  70. /// with no further indirection.
  71. static bool isPointerToConst(QualType Ty) {
  72. QualType PointeeTy = Ty->getPointeeType();
  73. if (PointeeTy == QualType())
  74. return false;
  75. if (!PointeeTy.isConstQualified())
  76. return false;
  77. if (PointeeTy->isAnyPointerType())
  78. return false;
  79. return true;
  80. }
  81. // Try to retrieve the function declaration and find the function parameter
  82. // types which are pointers/references to a non-pointer const.
  83. // We will not invalidate the corresponding argument regions.
  84. static void findPtrToConstParams(llvm::SmallSet<unsigned, 1> &PreserveArgs,
  85. const CallEvent &Call) {
  86. unsigned Idx = 0;
  87. for (CallEvent::param_type_iterator I = Call.param_type_begin(),
  88. E = Call.param_type_end();
  89. I != E; ++I, ++Idx) {
  90. if (isPointerToConst(*I))
  91. PreserveArgs.insert(Idx);
  92. }
  93. }
  94. ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
  95. ProgramStateRef Orig) const {
  96. ProgramStateRef Result = (Orig ? Orig : getState());
  97. SmallVector<const MemRegion *, 8> RegionsToInvalidate;
  98. getExtraInvalidatedRegions(RegionsToInvalidate);
  99. // Indexes of arguments whose values will be preserved by the call.
  100. llvm::SmallSet<unsigned, 1> PreserveArgs;
  101. if (!argumentsMayEscape())
  102. findPtrToConstParams(PreserveArgs, *this);
  103. for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
  104. if (PreserveArgs.count(Idx))
  105. continue;
  106. SVal V = getArgSVal(Idx);
  107. // If we are passing a location wrapped as an integer, unwrap it and
  108. // invalidate the values referred by the location.
  109. if (nonloc::LocAsInteger *Wrapped = dyn_cast<nonloc::LocAsInteger>(&V))
  110. V = Wrapped->getLoc();
  111. else if (!isa<Loc>(V))
  112. continue;
  113. if (const MemRegion *R = V.getAsRegion()) {
  114. // Invalidate the value of the variable passed by reference.
  115. // Are we dealing with an ElementRegion? If the element type is
  116. // a basic integer type (e.g., char, int) and the underlying region
  117. // is a variable region then strip off the ElementRegion.
  118. // FIXME: We really need to think about this for the general case
  119. // as sometimes we are reasoning about arrays and other times
  120. // about (char*), etc., is just a form of passing raw bytes.
  121. // e.g., void *p = alloca(); foo((char*)p);
  122. if (const ElementRegion *ER = dyn_cast<ElementRegion>(R)) {
  123. // Checking for 'integral type' is probably too promiscuous, but
  124. // we'll leave it in for now until we have a systematic way of
  125. // handling all of these cases. Eventually we need to come up
  126. // with an interface to StoreManager so that this logic can be
  127. // appropriately delegated to the respective StoreManagers while
  128. // still allowing us to do checker-specific logic (e.g.,
  129. // invalidating reference counts), probably via callbacks.
  130. if (ER->getElementType()->isIntegralOrEnumerationType()) {
  131. const MemRegion *superReg = ER->getSuperRegion();
  132. if (isa<VarRegion>(superReg) || isa<FieldRegion>(superReg) ||
  133. isa<ObjCIvarRegion>(superReg))
  134. R = cast<TypedRegion>(superReg);
  135. }
  136. // FIXME: What about layers of ElementRegions?
  137. }
  138. // Mark this region for invalidation. We batch invalidate regions
  139. // below for efficiency.
  140. RegionsToInvalidate.push_back(R);
  141. }
  142. }
  143. // Invalidate designated regions using the batch invalidation API.
  144. // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
  145. // global variables.
  146. return Result->invalidateRegions(RegionsToInvalidate, getOriginExpr(),
  147. BlockCount, getLocationContext(),
  148. /*Symbols=*/0, this);
  149. }
  150. ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
  151. const ProgramPointTag *Tag) const {
  152. if (const Expr *E = getOriginExpr()) {
  153. if (IsPreVisit)
  154. return PreStmt(E, getLocationContext(), Tag);
  155. return PostStmt(E, getLocationContext(), Tag);
  156. }
  157. const Decl *D = getDecl();
  158. assert(D && "Cannot get a program point without a statement or decl");
  159. SourceLocation Loc = getSourceRange().getBegin();
  160. if (IsPreVisit)
  161. return PreImplicitCall(D, Loc, getLocationContext(), Tag);
  162. return PostImplicitCall(D, Loc, getLocationContext(), Tag);
  163. }
  164. SVal CallEvent::getArgSVal(unsigned Index) const {
  165. const Expr *ArgE = getArgExpr(Index);
  166. if (!ArgE)
  167. return UnknownVal();
  168. return getSVal(ArgE);
  169. }
  170. SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
  171. const Expr *ArgE = getArgExpr(Index);
  172. if (!ArgE)
  173. return SourceRange();
  174. return ArgE->getSourceRange();
  175. }
  176. void CallEvent::dump() const {
  177. dump(llvm::errs());
  178. }
  179. void CallEvent::dump(raw_ostream &Out) const {
  180. ASTContext &Ctx = getState()->getStateManager().getContext();
  181. if (const Expr *E = getOriginExpr()) {
  182. E->printPretty(Out, 0, Ctx.getPrintingPolicy());
  183. Out << "\n";
  184. return;
  185. }
  186. if (const Decl *D = getDecl()) {
  187. Out << "Call to ";
  188. D->print(Out, Ctx.getPrintingPolicy());
  189. return;
  190. }
  191. // FIXME: a string representation of the kind would be nice.
  192. Out << "Unknown call (type " << getKind() << ")";
  193. }
  194. bool CallEvent::mayBeInlined(const Stmt *S) {
  195. // FIXME: Kill this.
  196. return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
  197. || isa<CXXConstructExpr>(S);
  198. }
  199. static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
  200. CallEvent::BindingsTy &Bindings,
  201. SValBuilder &SVB,
  202. const CallEvent &Call,
  203. CallEvent::param_iterator I,
  204. CallEvent::param_iterator E) {
  205. MemRegionManager &MRMgr = SVB.getRegionManager();
  206. unsigned Idx = 0;
  207. for (; I != E; ++I, ++Idx) {
  208. const ParmVarDecl *ParamDecl = *I;
  209. assert(ParamDecl && "Formal parameter has no decl?");
  210. SVal ArgVal = Call.getArgSVal(Idx);
  211. if (!ArgVal.isUnknown()) {
  212. Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
  213. Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
  214. }
  215. }
  216. // FIXME: Variadic arguments are not handled at all right now.
  217. }
  218. CallEvent::param_iterator AnyFunctionCall::param_begin() const {
  219. const FunctionDecl *D = getDecl();
  220. if (!D)
  221. return 0;
  222. return D->param_begin();
  223. }
  224. CallEvent::param_iterator AnyFunctionCall::param_end() const {
  225. const FunctionDecl *D = getDecl();
  226. if (!D)
  227. return 0;
  228. return D->param_end();
  229. }
  230. void AnyFunctionCall::getInitialStackFrameContents(
  231. const StackFrameContext *CalleeCtx,
  232. BindingsTy &Bindings) const {
  233. const FunctionDecl *D = cast<FunctionDecl>(CalleeCtx->getDecl());
  234. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  235. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  236. D->param_begin(), D->param_end());
  237. }
  238. QualType AnyFunctionCall::getDeclaredResultType() const {
  239. const FunctionDecl *D = getDecl();
  240. if (!D)
  241. return QualType();
  242. return D->getResultType();
  243. }
  244. bool AnyFunctionCall::argumentsMayEscape() const {
  245. if (hasNonZeroCallbackArg())
  246. return true;
  247. const FunctionDecl *D = getDecl();
  248. if (!D)
  249. return true;
  250. const IdentifierInfo *II = D->getIdentifier();
  251. if (!II)
  252. return true;
  253. // This set of "escaping" APIs is
  254. // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
  255. // value into thread local storage. The value can later be retrieved with
  256. // 'void *ptheread_getspecific(pthread_key)'. So even thought the
  257. // parameter is 'const void *', the region escapes through the call.
  258. if (II->isStr("pthread_setspecific"))
  259. return true;
  260. // - xpc_connection_set_context stores a value which can be retrieved later
  261. // with xpc_connection_get_context.
  262. if (II->isStr("xpc_connection_set_context"))
  263. return true;
  264. // - funopen - sets a buffer for future IO calls.
  265. if (II->isStr("funopen"))
  266. return true;
  267. StringRef FName = II->getName();
  268. // - CoreFoundation functions that end with "NoCopy" can free a passed-in
  269. // buffer even if it is const.
  270. if (FName.endswith("NoCopy"))
  271. return true;
  272. // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
  273. // be deallocated by NSMapRemove.
  274. if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
  275. return true;
  276. // - Many CF containers allow objects to escape through custom
  277. // allocators/deallocators upon container construction. (PR12101)
  278. if (FName.startswith("CF") || FName.startswith("CG")) {
  279. return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
  280. StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
  281. StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
  282. StrInStrNoCase(FName, "WithData") != StringRef::npos ||
  283. StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
  284. StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
  285. }
  286. return false;
  287. }
  288. const FunctionDecl *SimpleCall::getDecl() const {
  289. const FunctionDecl *D = getOriginExpr()->getDirectCallee();
  290. if (D)
  291. return D;
  292. return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
  293. }
  294. const FunctionDecl *CXXInstanceCall::getDecl() const {
  295. const CallExpr *CE = cast_or_null<CallExpr>(getOriginExpr());
  296. if (!CE)
  297. return AnyFunctionCall::getDecl();
  298. const FunctionDecl *D = CE->getDirectCallee();
  299. if (D)
  300. return D;
  301. return getSVal(CE->getCallee()).getAsFunctionDecl();
  302. }
  303. void CXXInstanceCall::getExtraInvalidatedRegions(RegionList &Regions) const {
  304. if (const MemRegion *R = getCXXThisVal().getAsRegion())
  305. Regions.push_back(R);
  306. }
  307. RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
  308. // Do we have a decl at all?
  309. const Decl *D = getDecl();
  310. if (!D)
  311. return RuntimeDefinition();
  312. // If the method is non-virtual, we know we can inline it.
  313. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  314. if (!MD->isVirtual())
  315. return AnyFunctionCall::getRuntimeDefinition();
  316. // Do we know the implicit 'this' object being called?
  317. const MemRegion *R = getCXXThisVal().getAsRegion();
  318. if (!R)
  319. return RuntimeDefinition();
  320. // Do we know anything about the type of 'this'?
  321. DynamicTypeInfo DynType = getState()->getDynamicTypeInfo(R);
  322. if (!DynType.isValid())
  323. return RuntimeDefinition();
  324. // Is the type a C++ class? (This is mostly a defensive check.)
  325. QualType RegionType = DynType.getType()->getPointeeType();
  326. const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
  327. if (!RD || !RD->hasDefinition())
  328. return RuntimeDefinition();
  329. // Find the decl for this method in that class.
  330. const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
  331. assert(Result && "At the very least the static decl should show up.");
  332. // Does the decl that we found have an implementation?
  333. const FunctionDecl *Definition;
  334. if (!Result->hasBody(Definition))
  335. return RuntimeDefinition();
  336. // We found a definition. If we're not sure that this devirtualization is
  337. // actually what will happen at runtime, make sure to provide the region so
  338. // that ExprEngine can decide what to do with it.
  339. if (DynType.canBeASubClass())
  340. return RuntimeDefinition(Definition, R->StripCasts());
  341. return RuntimeDefinition(Definition, /*DispatchRegion=*/0);
  342. }
  343. void CXXInstanceCall::getInitialStackFrameContents(
  344. const StackFrameContext *CalleeCtx,
  345. BindingsTy &Bindings) const {
  346. AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
  347. // Handle the binding of 'this' in the new stack frame.
  348. SVal ThisVal = getCXXThisVal();
  349. if (!ThisVal.isUnknown()) {
  350. ProgramStateManager &StateMgr = getState()->getStateManager();
  351. SValBuilder &SVB = StateMgr.getSValBuilder();
  352. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  353. Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
  354. // If we devirtualized to a different member function, we need to make sure
  355. // we have the proper layering of CXXBaseObjectRegions.
  356. if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
  357. ASTContext &Ctx = SVB.getContext();
  358. const CXXRecordDecl *Class = MD->getParent();
  359. QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
  360. // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
  361. bool Failed;
  362. ThisVal = StateMgr.getStoreManager().evalDynamicCast(ThisVal, Ty, Failed);
  363. assert(!Failed && "Calling an incorrectly devirtualized method");
  364. }
  365. if (!ThisVal.isUnknown())
  366. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  367. }
  368. }
  369. const Expr *CXXMemberCall::getCXXThisExpr() const {
  370. return getOriginExpr()->getImplicitObjectArgument();
  371. }
  372. const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
  373. return getOriginExpr()->getArg(0);
  374. }
  375. const BlockDataRegion *BlockCall::getBlockRegion() const {
  376. const Expr *Callee = getOriginExpr()->getCallee();
  377. const MemRegion *DataReg = getSVal(Callee).getAsRegion();
  378. return dyn_cast_or_null<BlockDataRegion>(DataReg);
  379. }
  380. CallEvent::param_iterator BlockCall::param_begin() const {
  381. const BlockDecl *D = getBlockDecl();
  382. if (!D)
  383. return 0;
  384. return D->param_begin();
  385. }
  386. CallEvent::param_iterator BlockCall::param_end() const {
  387. const BlockDecl *D = getBlockDecl();
  388. if (!D)
  389. return 0;
  390. return D->param_end();
  391. }
  392. void BlockCall::getExtraInvalidatedRegions(RegionList &Regions) const {
  393. // FIXME: This also needs to invalidate captured globals.
  394. if (const MemRegion *R = getBlockRegion())
  395. Regions.push_back(R);
  396. }
  397. void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
  398. BindingsTy &Bindings) const {
  399. const BlockDecl *D = cast<BlockDecl>(CalleeCtx->getDecl());
  400. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  401. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  402. D->param_begin(), D->param_end());
  403. }
  404. QualType BlockCall::getDeclaredResultType() const {
  405. const BlockDataRegion *BR = getBlockRegion();
  406. if (!BR)
  407. return QualType();
  408. QualType BlockTy = BR->getCodeRegion()->getLocationType();
  409. return cast<FunctionType>(BlockTy->getPointeeType())->getResultType();
  410. }
  411. SVal CXXConstructorCall::getCXXThisVal() const {
  412. if (Data)
  413. return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
  414. return UnknownVal();
  415. }
  416. void CXXConstructorCall::getExtraInvalidatedRegions(RegionList &Regions) const {
  417. if (Data)
  418. Regions.push_back(static_cast<const MemRegion *>(Data));
  419. }
  420. void CXXConstructorCall::getInitialStackFrameContents(
  421. const StackFrameContext *CalleeCtx,
  422. BindingsTy &Bindings) const {
  423. AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
  424. SVal ThisVal = getCXXThisVal();
  425. if (!ThisVal.isUnknown()) {
  426. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  427. const CXXMethodDecl *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  428. Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
  429. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  430. }
  431. }
  432. SVal CXXDestructorCall::getCXXThisVal() const {
  433. if (Data)
  434. return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
  435. return UnknownVal();
  436. }
  437. CallEvent::param_iterator ObjCMethodCall::param_begin() const {
  438. const ObjCMethodDecl *D = getDecl();
  439. if (!D)
  440. return 0;
  441. return D->param_begin();
  442. }
  443. CallEvent::param_iterator ObjCMethodCall::param_end() const {
  444. const ObjCMethodDecl *D = getDecl();
  445. if (!D)
  446. return 0;
  447. return D->param_end();
  448. }
  449. void
  450. ObjCMethodCall::getExtraInvalidatedRegions(RegionList &Regions) const {
  451. if (const MemRegion *R = getReceiverSVal().getAsRegion())
  452. Regions.push_back(R);
  453. }
  454. QualType ObjCMethodCall::getDeclaredResultType() const {
  455. const ObjCMethodDecl *D = getDecl();
  456. if (!D)
  457. return QualType();
  458. return D->getResultType();
  459. }
  460. SVal ObjCMethodCall::getReceiverSVal() const {
  461. // FIXME: Is this the best way to handle class receivers?
  462. if (!isInstanceMessage())
  463. return UnknownVal();
  464. if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
  465. return getSVal(RecE);
  466. // An instance message with no expression means we are sending to super.
  467. // In this case the object reference is the same as 'self'.
  468. const LocationContext *LCtx = getLocationContext();
  469. const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
  470. assert(SelfDecl && "No message receiver Expr, but not in an ObjC method");
  471. return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
  472. }
  473. SourceRange ObjCMethodCall::getSourceRange() const {
  474. switch (getMessageKind()) {
  475. case OCM_Message:
  476. return getOriginExpr()->getSourceRange();
  477. case OCM_PropertyAccess:
  478. case OCM_Subscript:
  479. return getContainingPseudoObjectExpr()->getSourceRange();
  480. }
  481. llvm_unreachable("unknown message kind");
  482. }
  483. typedef llvm::PointerIntPair<const PseudoObjectExpr *, 2> ObjCMessageDataTy;
  484. const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
  485. assert(Data != 0 && "Lazy lookup not yet performed.");
  486. assert(getMessageKind() != OCM_Message && "Explicit message send.");
  487. return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
  488. }
  489. ObjCMessageKind ObjCMethodCall::getMessageKind() const {
  490. if (Data == 0) {
  491. ParentMap &PM = getLocationContext()->getParentMap();
  492. const Stmt *S = PM.getParent(getOriginExpr());
  493. if (const PseudoObjectExpr *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
  494. const Expr *Syntactic = POE->getSyntacticForm();
  495. // This handles the funny case of assigning to the result of a getter.
  496. // This can happen if the getter returns a non-const reference.
  497. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Syntactic))
  498. Syntactic = BO->getLHS();
  499. ObjCMessageKind K;
  500. switch (Syntactic->getStmtClass()) {
  501. case Stmt::ObjCPropertyRefExprClass:
  502. K = OCM_PropertyAccess;
  503. break;
  504. case Stmt::ObjCSubscriptRefExprClass:
  505. K = OCM_Subscript;
  506. break;
  507. default:
  508. // FIXME: Can this ever happen?
  509. K = OCM_Message;
  510. break;
  511. }
  512. if (K != OCM_Message) {
  513. const_cast<ObjCMethodCall *>(this)->Data
  514. = ObjCMessageDataTy(POE, K).getOpaqueValue();
  515. assert(getMessageKind() == K);
  516. return K;
  517. }
  518. }
  519. const_cast<ObjCMethodCall *>(this)->Data
  520. = ObjCMessageDataTy(0, 1).getOpaqueValue();
  521. assert(getMessageKind() == OCM_Message);
  522. return OCM_Message;
  523. }
  524. ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
  525. if (!Info.getPointer())
  526. return OCM_Message;
  527. return static_cast<ObjCMessageKind>(Info.getInt());
  528. }
  529. bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
  530. Selector Sel) const {
  531. assert(IDecl);
  532. const SourceManager &SM =
  533. getState()->getStateManager().getContext().getSourceManager();
  534. // If the class interface is declared inside the main file, assume it is not
  535. // subcassed.
  536. // TODO: It could actually be subclassed if the subclass is private as well.
  537. // This is probably very rare.
  538. SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
  539. if (InterfLoc.isValid() && SM.isFromMainFile(InterfLoc))
  540. return false;
  541. // Assume that property accessors are not overridden.
  542. if (getMessageKind() == OCM_PropertyAccess)
  543. return false;
  544. // We assume that if the method is public (declared outside of main file) or
  545. // has a parent which publicly declares the method, the method could be
  546. // overridden in a subclass.
  547. // Find the first declaration in the class hierarchy that declares
  548. // the selector.
  549. ObjCMethodDecl *D = 0;
  550. while (true) {
  551. D = IDecl->lookupMethod(Sel, true);
  552. // Cannot find a public definition.
  553. if (!D)
  554. return false;
  555. // If outside the main file,
  556. if (D->getLocation().isValid() && !SM.isFromMainFile(D->getLocation()))
  557. return true;
  558. if (D->isOverriding()) {
  559. // Search in the superclass on the next iteration.
  560. IDecl = D->getClassInterface();
  561. if (!IDecl)
  562. return false;
  563. IDecl = IDecl->getSuperClass();
  564. if (!IDecl)
  565. return false;
  566. continue;
  567. }
  568. return false;
  569. };
  570. llvm_unreachable("The while loop should always terminate.");
  571. }
  572. RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
  573. const ObjCMessageExpr *E = getOriginExpr();
  574. assert(E);
  575. Selector Sel = E->getSelector();
  576. if (E->isInstanceMessage()) {
  577. // Find the the receiver type.
  578. const ObjCObjectPointerType *ReceiverT = 0;
  579. bool CanBeSubClassed = false;
  580. QualType SupersType = E->getSuperType();
  581. const MemRegion *Receiver = 0;
  582. if (!SupersType.isNull()) {
  583. // Super always means the type of immediate predecessor to the method
  584. // where the call occurs.
  585. ReceiverT = cast<ObjCObjectPointerType>(SupersType);
  586. } else {
  587. Receiver = getReceiverSVal().getAsRegion();
  588. if (!Receiver)
  589. return RuntimeDefinition();
  590. DynamicTypeInfo DTI = getState()->getDynamicTypeInfo(Receiver);
  591. QualType DynType = DTI.getType();
  592. CanBeSubClassed = DTI.canBeASubClass();
  593. ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType);
  594. if (ReceiverT && CanBeSubClassed)
  595. if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
  596. if (!canBeOverridenInSubclass(IDecl, Sel))
  597. CanBeSubClassed = false;
  598. }
  599. // Lookup the method implementation.
  600. if (ReceiverT)
  601. if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
  602. const ObjCMethodDecl *MD = IDecl->lookupPrivateMethod(Sel);
  603. if (CanBeSubClassed)
  604. return RuntimeDefinition(MD, Receiver);
  605. else
  606. return RuntimeDefinition(MD, 0);
  607. }
  608. } else {
  609. // This is a class method.
  610. // If we have type info for the receiver class, we are calling via
  611. // class name.
  612. if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
  613. // Find/Return the method implementation.
  614. return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
  615. }
  616. }
  617. return RuntimeDefinition();
  618. }
  619. void ObjCMethodCall::getInitialStackFrameContents(
  620. const StackFrameContext *CalleeCtx,
  621. BindingsTy &Bindings) const {
  622. const ObjCMethodDecl *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
  623. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  624. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  625. D->param_begin(), D->param_end());
  626. SVal SelfVal = getReceiverSVal();
  627. if (!SelfVal.isUnknown()) {
  628. const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
  629. MemRegionManager &MRMgr = SVB.getRegionManager();
  630. Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
  631. Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
  632. }
  633. }
  634. CallEventRef<>
  635. CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
  636. const LocationContext *LCtx) {
  637. if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE))
  638. return create<CXXMemberCall>(MCE, State, LCtx);
  639. if (const CXXOperatorCallExpr *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
  640. const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
  641. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
  642. if (MD->isInstance())
  643. return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
  644. } else if (CE->getCallee()->getType()->isBlockPointerType()) {
  645. return create<BlockCall>(CE, State, LCtx);
  646. }
  647. // Otherwise, it's a normal function call, static member function call, or
  648. // something we can't reason about.
  649. return create<FunctionCall>(CE, State, LCtx);
  650. }
  651. CallEventRef<>
  652. CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
  653. ProgramStateRef State) {
  654. const LocationContext *ParentCtx = CalleeCtx->getParent();
  655. const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
  656. assert(CallerCtx && "This should not be used for top-level stack frames");
  657. const Stmt *CallSite = CalleeCtx->getCallSite();
  658. if (CallSite) {
  659. if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
  660. return getSimpleCall(CE, State, CallerCtx);
  661. switch (CallSite->getStmtClass()) {
  662. case Stmt::CXXConstructExprClass: {
  663. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  664. const CXXMethodDecl *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  665. Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
  666. SVal ThisVal = State->getSVal(ThisPtr);
  667. return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
  668. ThisVal.getAsRegion(), State, CallerCtx);
  669. }
  670. case Stmt::CXXNewExprClass:
  671. return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
  672. case Stmt::ObjCMessageExprClass:
  673. return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
  674. State, CallerCtx);
  675. default:
  676. llvm_unreachable("This is not an inlineable statement.");
  677. }
  678. }
  679. // Fall back to the CFG. The only thing we haven't handled yet is
  680. // destructors, though this could change in the future.
  681. const CFGBlock *B = CalleeCtx->getCallSiteBlock();
  682. CFGElement E = (*B)[CalleeCtx->getIndex()];
  683. assert(isa<CFGImplicitDtor>(E) && "All other CFG elements should have exprs");
  684. assert(!isa<CFGTemporaryDtor>(E) && "We don't handle temporaries yet");
  685. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  686. const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
  687. Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
  688. SVal ThisVal = State->getSVal(ThisPtr);
  689. const Stmt *Trigger;
  690. if (const CFGAutomaticObjDtor *AutoDtor = dyn_cast<CFGAutomaticObjDtor>(&E))
  691. Trigger = AutoDtor->getTriggerStmt();
  692. else
  693. Trigger = Dtor->getBody();
  694. return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
  695. State, CallerCtx);
  696. }