CallEvent.cpp 33 KB

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