CallEvent.cpp 31 KB

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