CallEvent.cpp 32 KB

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