CallEvent.cpp 34 KB

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