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