CallEvent.cpp 33 KB

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