CallEvent.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270
  1. //===- CallEvent.cpp - Wrapper for all function and method calls ----------===//
  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/ASTContext.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclBase.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/ParentMap.h"
  25. #include "clang/AST/Stmt.h"
  26. #include "clang/AST/Type.h"
  27. #include "clang/Analysis/AnalysisDeclContext.h"
  28. #include "clang/Analysis/CFG.h"
  29. #include "clang/Analysis/ProgramPoint.h"
  30. #include "clang/CrossTU/CrossTranslationUnit.h"
  31. #include "clang/Basic/IdentifierTable.h"
  32. #include "clang/Basic/LLVM.h"
  33. #include "clang/Basic/SourceLocation.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Basic/Specifiers.h"
  36. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeInfo.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicTypeMap.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  42. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
  43. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  44. #include "clang/StaticAnalyzer/Core/PathSensitive/SValBuilder.h"
  45. #include "clang/StaticAnalyzer/Core/PathSensitive/Store.h"
  46. #include "llvm/ADT/ArrayRef.h"
  47. #include "llvm/ADT/DenseMap.h"
  48. #include "llvm/ADT/None.h"
  49. #include "llvm/ADT/Optional.h"
  50. #include "llvm/ADT/PointerIntPair.h"
  51. #include "llvm/ADT/SmallSet.h"
  52. #include "llvm/ADT/SmallVector.h"
  53. #include "llvm/ADT/StringExtras.h"
  54. #include "llvm/ADT/StringRef.h"
  55. #include "llvm/Support/Casting.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/Debug.h"
  58. #include "llvm/Support/ErrorHandling.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include <cassert>
  61. #include <utility>
  62. #define DEBUG_TYPE "static-analyzer-call-event"
  63. using namespace clang;
  64. using namespace ento;
  65. QualType CallEvent::getResultType() const {
  66. const Expr *E = getOriginExpr();
  67. assert(E && "Calls without origin expressions do not have results");
  68. QualType ResultTy = E->getType();
  69. ASTContext &Ctx = getState()->getStateManager().getContext();
  70. // A function that returns a reference to 'int' will have a result type
  71. // of simply 'int'. Check the origin expr's value kind to recover the
  72. // proper type.
  73. switch (E->getValueKind()) {
  74. case VK_LValue:
  75. ResultTy = Ctx.getLValueReferenceType(ResultTy);
  76. break;
  77. case VK_XValue:
  78. ResultTy = Ctx.getRValueReferenceType(ResultTy);
  79. break;
  80. case VK_RValue:
  81. // No adjustment is necessary.
  82. break;
  83. }
  84. return ResultTy;
  85. }
  86. static bool isCallback(QualType T) {
  87. // If a parameter is a block or a callback, assume it can modify pointer.
  88. if (T->isBlockPointerType() ||
  89. T->isFunctionPointerType() ||
  90. T->isObjCSelType())
  91. return true;
  92. // Check if a callback is passed inside a struct (for both, struct passed by
  93. // reference and by value). Dig just one level into the struct for now.
  94. if (T->isAnyPointerType() || T->isReferenceType())
  95. T = T->getPointeeType();
  96. if (const RecordType *RT = T->getAsStructureType()) {
  97. const RecordDecl *RD = RT->getDecl();
  98. for (const auto *I : RD->fields()) {
  99. QualType FieldT = I->getType();
  100. if (FieldT->isBlockPointerType() || FieldT->isFunctionPointerType())
  101. return true;
  102. }
  103. }
  104. return false;
  105. }
  106. static bool isVoidPointerToNonConst(QualType T) {
  107. if (const auto *PT = T->getAs<PointerType>()) {
  108. QualType PointeeTy = PT->getPointeeType();
  109. if (PointeeTy.isConstQualified())
  110. return false;
  111. return PointeeTy->isVoidType();
  112. } else
  113. return false;
  114. }
  115. bool CallEvent::hasNonNullArgumentsWithType(bool (*Condition)(QualType)) const {
  116. unsigned NumOfArgs = getNumArgs();
  117. // If calling using a function pointer, assume the function does not
  118. // satisfy the callback.
  119. // TODO: We could check the types of the arguments here.
  120. if (!getDecl())
  121. return false;
  122. unsigned Idx = 0;
  123. for (CallEvent::param_type_iterator I = param_type_begin(),
  124. E = param_type_end();
  125. I != E && Idx < NumOfArgs; ++I, ++Idx) {
  126. // If the parameter is 0, it's harmless.
  127. if (getArgSVal(Idx).isZeroConstant())
  128. continue;
  129. if (Condition(*I))
  130. return true;
  131. }
  132. return false;
  133. }
  134. bool CallEvent::hasNonZeroCallbackArg() const {
  135. return hasNonNullArgumentsWithType(isCallback);
  136. }
  137. bool CallEvent::hasVoidPointerToNonConstArg() const {
  138. return hasNonNullArgumentsWithType(isVoidPointerToNonConst);
  139. }
  140. bool CallEvent::isGlobalCFunction(StringRef FunctionName) const {
  141. const auto *FD = dyn_cast_or_null<FunctionDecl>(getDecl());
  142. if (!FD)
  143. return false;
  144. return CheckerContext::isCLibraryFunction(FD, FunctionName);
  145. }
  146. /// \brief Returns true if a type is a pointer-to-const or reference-to-const
  147. /// with no further indirection.
  148. static bool isPointerToConst(QualType Ty) {
  149. QualType PointeeTy = Ty->getPointeeType();
  150. if (PointeeTy == QualType())
  151. return false;
  152. if (!PointeeTy.isConstQualified())
  153. return false;
  154. if (PointeeTy->isAnyPointerType())
  155. return false;
  156. return true;
  157. }
  158. // Try to retrieve the function declaration and find the function parameter
  159. // types which are pointers/references to a non-pointer const.
  160. // We will not invalidate the corresponding argument regions.
  161. static void findPtrToConstParams(llvm::SmallSet<unsigned, 4> &PreserveArgs,
  162. const CallEvent &Call) {
  163. unsigned Idx = 0;
  164. for (CallEvent::param_type_iterator I = Call.param_type_begin(),
  165. E = Call.param_type_end();
  166. I != E; ++I, ++Idx) {
  167. if (isPointerToConst(*I))
  168. PreserveArgs.insert(Idx);
  169. }
  170. }
  171. ProgramStateRef CallEvent::invalidateRegions(unsigned BlockCount,
  172. ProgramStateRef Orig) const {
  173. ProgramStateRef Result = (Orig ? Orig : getState());
  174. // Don't invalidate anything if the callee is marked pure/const.
  175. if (const Decl *callee = getDecl())
  176. if (callee->hasAttr<PureAttr>() || callee->hasAttr<ConstAttr>())
  177. return Result;
  178. SmallVector<SVal, 8> ValuesToInvalidate;
  179. RegionAndSymbolInvalidationTraits ETraits;
  180. getExtraInvalidatedValues(ValuesToInvalidate, &ETraits);
  181. // Indexes of arguments whose values will be preserved by the call.
  182. llvm::SmallSet<unsigned, 4> PreserveArgs;
  183. if (!argumentsMayEscape())
  184. findPtrToConstParams(PreserveArgs, *this);
  185. for (unsigned Idx = 0, Count = getNumArgs(); Idx != Count; ++Idx) {
  186. // Mark this region for invalidation. We batch invalidate regions
  187. // below for efficiency.
  188. if (PreserveArgs.count(Idx))
  189. if (const MemRegion *MR = getArgSVal(Idx).getAsRegion())
  190. ETraits.setTrait(MR->getBaseRegion(),
  191. RegionAndSymbolInvalidationTraits::TK_PreserveContents);
  192. // TODO: Factor this out + handle the lower level const pointers.
  193. ValuesToInvalidate.push_back(getArgSVal(Idx));
  194. }
  195. // Invalidate designated regions using the batch invalidation API.
  196. // NOTE: Even if RegionsToInvalidate is empty, we may still invalidate
  197. // global variables.
  198. return Result->invalidateRegions(ValuesToInvalidate, getOriginExpr(),
  199. BlockCount, getLocationContext(),
  200. /*CausedByPointerEscape*/ true,
  201. /*Symbols=*/nullptr, this, &ETraits);
  202. }
  203. ProgramPoint CallEvent::getProgramPoint(bool IsPreVisit,
  204. const ProgramPointTag *Tag) const {
  205. if (const Expr *E = getOriginExpr()) {
  206. if (IsPreVisit)
  207. return PreStmt(E, getLocationContext(), Tag);
  208. return PostStmt(E, getLocationContext(), Tag);
  209. }
  210. const Decl *D = getDecl();
  211. assert(D && "Cannot get a program point without a statement or decl");
  212. SourceLocation Loc = getSourceRange().getBegin();
  213. if (IsPreVisit)
  214. return PreImplicitCall(D, Loc, getLocationContext(), Tag);
  215. return PostImplicitCall(D, Loc, getLocationContext(), Tag);
  216. }
  217. bool CallEvent::isCalled(const CallDescription &CD) const {
  218. // FIXME: Add ObjC Message support.
  219. if (getKind() == CE_ObjCMessage)
  220. return false;
  221. if (!CD.IsLookupDone) {
  222. CD.IsLookupDone = true;
  223. CD.II = &getState()->getStateManager().getContext().Idents.get(CD.FuncName);
  224. }
  225. const IdentifierInfo *II = getCalleeIdentifier();
  226. if (!II || II != CD.II)
  227. return false;
  228. return (CD.RequiredArgs == CallDescription::NoArgRequirement ||
  229. CD.RequiredArgs == getNumArgs());
  230. }
  231. SVal CallEvent::getArgSVal(unsigned Index) const {
  232. const Expr *ArgE = getArgExpr(Index);
  233. if (!ArgE)
  234. return UnknownVal();
  235. return getSVal(ArgE);
  236. }
  237. SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
  238. const Expr *ArgE = getArgExpr(Index);
  239. if (!ArgE)
  240. return {};
  241. return ArgE->getSourceRange();
  242. }
  243. SVal CallEvent::getReturnValue() const {
  244. const Expr *E = getOriginExpr();
  245. if (!E)
  246. return UndefinedVal();
  247. return getSVal(E);
  248. }
  249. LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
  250. void CallEvent::dump(raw_ostream &Out) const {
  251. ASTContext &Ctx = getState()->getStateManager().getContext();
  252. if (const Expr *E = getOriginExpr()) {
  253. E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
  254. Out << "\n";
  255. return;
  256. }
  257. if (const Decl *D = getDecl()) {
  258. Out << "Call to ";
  259. D->print(Out, Ctx.getPrintingPolicy());
  260. return;
  261. }
  262. // FIXME: a string representation of the kind would be nice.
  263. Out << "Unknown call (type " << getKind() << ")";
  264. }
  265. bool CallEvent::isCallStmt(const Stmt *S) {
  266. return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
  267. || isa<CXXConstructExpr>(S)
  268. || isa<CXXNewExpr>(S);
  269. }
  270. QualType CallEvent::getDeclaredResultType(const Decl *D) {
  271. assert(D);
  272. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  273. return FD->getReturnType();
  274. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  275. return MD->getReturnType();
  276. if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  277. // Blocks are difficult because the return type may not be stored in the
  278. // BlockDecl itself. The AST should probably be enhanced, but for now we
  279. // just do what we can.
  280. // If the block is declared without an explicit argument list, the
  281. // signature-as-written just includes the return type, not the entire
  282. // function type.
  283. // FIXME: All blocks should have signatures-as-written, even if the return
  284. // type is inferred. (That's signified with a dependent result type.)
  285. if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
  286. QualType Ty = TSI->getType();
  287. if (const FunctionType *FT = Ty->getAs<FunctionType>())
  288. Ty = FT->getReturnType();
  289. if (!Ty->isDependentType())
  290. return Ty;
  291. }
  292. return {};
  293. }
  294. llvm_unreachable("unknown callable kind");
  295. }
  296. bool CallEvent::isVariadic(const Decl *D) {
  297. assert(D);
  298. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  299. return FD->isVariadic();
  300. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  301. return MD->isVariadic();
  302. if (const auto *BD = dyn_cast<BlockDecl>(D))
  303. return BD->isVariadic();
  304. llvm_unreachable("unknown callable kind");
  305. }
  306. static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
  307. CallEvent::BindingsTy &Bindings,
  308. SValBuilder &SVB,
  309. const CallEvent &Call,
  310. ArrayRef<ParmVarDecl*> parameters) {
  311. MemRegionManager &MRMgr = SVB.getRegionManager();
  312. // If the function has fewer parameters than the call has arguments, we simply
  313. // do not bind any values to them.
  314. unsigned NumArgs = Call.getNumArgs();
  315. unsigned Idx = 0;
  316. ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
  317. for (; I != E && Idx < NumArgs; ++I, ++Idx) {
  318. const ParmVarDecl *ParamDecl = *I;
  319. assert(ParamDecl && "Formal parameter has no decl?");
  320. SVal ArgVal = Call.getArgSVal(Idx);
  321. if (!ArgVal.isUnknown()) {
  322. Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
  323. Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
  324. }
  325. }
  326. // FIXME: Variadic arguments are not handled at all right now.
  327. }
  328. ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
  329. const FunctionDecl *D = getDecl();
  330. if (!D)
  331. return None;
  332. return D->parameters();
  333. }
  334. RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
  335. const FunctionDecl *FD = getDecl();
  336. // Note that the AnalysisDeclContext will have the FunctionDecl with
  337. // the definition (if one exists).
  338. if (FD) {
  339. AnalysisDeclContext *AD =
  340. getLocationContext()->getAnalysisDeclContext()->
  341. getManager()->getContext(FD);
  342. bool IsAutosynthesized;
  343. Stmt* Body = AD->getBody(IsAutosynthesized);
  344. DEBUG({
  345. if (IsAutosynthesized)
  346. llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
  347. << "\n";
  348. });
  349. if (Body) {
  350. const Decl* Decl = AD->getDecl();
  351. return RuntimeDefinition(Decl);
  352. }
  353. }
  354. SubEngine *Engine = getState()->getStateManager().getOwningEngine();
  355. AnalyzerOptions &Opts = Engine->getAnalysisManager().options;
  356. // Try to get CTU definition only if CTUDir is provided.
  357. if (!Opts.naiveCTUEnabled())
  358. return RuntimeDefinition();
  359. cross_tu::CrossTranslationUnitContext &CTUCtx =
  360. *Engine->getCrossTranslationUnitContext();
  361. llvm::Expected<const FunctionDecl *> CTUDeclOrError =
  362. CTUCtx.getCrossTUDefinition(FD, Opts.getCTUDir(), Opts.getCTUIndexName());
  363. if (!CTUDeclOrError) {
  364. handleAllErrors(CTUDeclOrError.takeError(),
  365. [&](const cross_tu::IndexError &IE) {
  366. CTUCtx.emitCrossTUDiagnostics(IE);
  367. });
  368. return {};
  369. }
  370. return RuntimeDefinition(*CTUDeclOrError);
  371. }
  372. void AnyFunctionCall::getInitialStackFrameContents(
  373. const StackFrameContext *CalleeCtx,
  374. BindingsTy &Bindings) const {
  375. const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl());
  376. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  377. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  378. D->parameters());
  379. }
  380. bool AnyFunctionCall::argumentsMayEscape() const {
  381. if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
  382. return true;
  383. const FunctionDecl *D = getDecl();
  384. if (!D)
  385. return true;
  386. const IdentifierInfo *II = D->getIdentifier();
  387. if (!II)
  388. return false;
  389. // This set of "escaping" APIs is
  390. // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
  391. // value into thread local storage. The value can later be retrieved with
  392. // 'void *ptheread_getspecific(pthread_key)'. So even thought the
  393. // parameter is 'const void *', the region escapes through the call.
  394. if (II->isStr("pthread_setspecific"))
  395. return true;
  396. // - xpc_connection_set_context stores a value which can be retrieved later
  397. // with xpc_connection_get_context.
  398. if (II->isStr("xpc_connection_set_context"))
  399. return true;
  400. // - funopen - sets a buffer for future IO calls.
  401. if (II->isStr("funopen"))
  402. return true;
  403. // - __cxa_demangle - can reallocate memory and can return the pointer to
  404. // the input buffer.
  405. if (II->isStr("__cxa_demangle"))
  406. return true;
  407. StringRef FName = II->getName();
  408. // - CoreFoundation functions that end with "NoCopy" can free a passed-in
  409. // buffer even if it is const.
  410. if (FName.endswith("NoCopy"))
  411. return true;
  412. // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
  413. // be deallocated by NSMapRemove.
  414. if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
  415. return true;
  416. // - Many CF containers allow objects to escape through custom
  417. // allocators/deallocators upon container construction. (PR12101)
  418. if (FName.startswith("CF") || FName.startswith("CG")) {
  419. return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
  420. StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
  421. StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
  422. StrInStrNoCase(FName, "WithData") != StringRef::npos ||
  423. StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
  424. StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
  425. }
  426. return false;
  427. }
  428. const FunctionDecl *SimpleFunctionCall::getDecl() const {
  429. const FunctionDecl *D = getOriginExpr()->getDirectCallee();
  430. if (D)
  431. return D;
  432. return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
  433. }
  434. const FunctionDecl *CXXInstanceCall::getDecl() const {
  435. const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
  436. if (!CE)
  437. return AnyFunctionCall::getDecl();
  438. const FunctionDecl *D = CE->getDirectCallee();
  439. if (D)
  440. return D;
  441. return getSVal(CE->getCallee()).getAsFunctionDecl();
  442. }
  443. void CXXInstanceCall::getExtraInvalidatedValues(
  444. ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
  445. SVal ThisVal = getCXXThisVal();
  446. Values.push_back(ThisVal);
  447. // Don't invalidate if the method is const and there are no mutable fields.
  448. if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) {
  449. if (!D->isConst())
  450. return;
  451. // Get the record decl for the class of 'This'. D->getParent() may return a
  452. // base class decl, rather than the class of the instance which needs to be
  453. // checked for mutable fields.
  454. const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
  455. const CXXRecordDecl *ParentRecord = Ex->getType()->getAsCXXRecordDecl();
  456. if (!ParentRecord || ParentRecord->hasMutableFields())
  457. return;
  458. // Preserve CXXThis.
  459. const MemRegion *ThisRegion = ThisVal.getAsRegion();
  460. if (!ThisRegion)
  461. return;
  462. ETraits->setTrait(ThisRegion->getBaseRegion(),
  463. RegionAndSymbolInvalidationTraits::TK_PreserveContents);
  464. }
  465. }
  466. SVal CXXInstanceCall::getCXXThisVal() const {
  467. const Expr *Base = getCXXThisExpr();
  468. // FIXME: This doesn't handle an overloaded ->* operator.
  469. if (!Base)
  470. return UnknownVal();
  471. SVal ThisVal = getSVal(Base);
  472. assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
  473. return ThisVal;
  474. }
  475. RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
  476. // Do we have a decl at all?
  477. const Decl *D = getDecl();
  478. if (!D)
  479. return {};
  480. // If the method is non-virtual, we know we can inline it.
  481. const auto *MD = cast<CXXMethodDecl>(D);
  482. if (!MD->isVirtual())
  483. return AnyFunctionCall::getRuntimeDefinition();
  484. // Do we know the implicit 'this' object being called?
  485. const MemRegion *R = getCXXThisVal().getAsRegion();
  486. if (!R)
  487. return {};
  488. // Do we know anything about the type of 'this'?
  489. DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
  490. if (!DynType.isValid())
  491. return {};
  492. // Is the type a C++ class? (This is mostly a defensive check.)
  493. QualType RegionType = DynType.getType()->getPointeeType();
  494. assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
  495. const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
  496. if (!RD || !RD->hasDefinition())
  497. return {};
  498. // Find the decl for this method in that class.
  499. const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
  500. if (!Result) {
  501. // We might not even get the original statically-resolved method due to
  502. // some particularly nasty casting (e.g. casts to sister classes).
  503. // However, we should at least be able to search up and down our own class
  504. // hierarchy, and some real bugs have been caught by checking this.
  505. assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
  506. // FIXME: This is checking that our DynamicTypeInfo is at least as good as
  507. // the static type. However, because we currently don't update
  508. // DynamicTypeInfo when an object is cast, we can't actually be sure the
  509. // DynamicTypeInfo is up to date. This assert should be re-enabled once
  510. // this is fixed. <rdar://problem/12287087>
  511. //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
  512. return {};
  513. }
  514. // Does the decl that we found have an implementation?
  515. const FunctionDecl *Definition;
  516. if (!Result->hasBody(Definition))
  517. return {};
  518. // We found a definition. If we're not sure that this devirtualization is
  519. // actually what will happen at runtime, make sure to provide the region so
  520. // that ExprEngine can decide what to do with it.
  521. if (DynType.canBeASubClass())
  522. return RuntimeDefinition(Definition, R->StripCasts());
  523. return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
  524. }
  525. void CXXInstanceCall::getInitialStackFrameContents(
  526. const StackFrameContext *CalleeCtx,
  527. BindingsTy &Bindings) const {
  528. AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
  529. // Handle the binding of 'this' in the new stack frame.
  530. SVal ThisVal = getCXXThisVal();
  531. if (!ThisVal.isUnknown()) {
  532. ProgramStateManager &StateMgr = getState()->getStateManager();
  533. SValBuilder &SVB = StateMgr.getSValBuilder();
  534. const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  535. Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
  536. // If we devirtualized to a different member function, we need to make sure
  537. // we have the proper layering of CXXBaseObjectRegions.
  538. if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
  539. ASTContext &Ctx = SVB.getContext();
  540. const CXXRecordDecl *Class = MD->getParent();
  541. QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
  542. // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
  543. bool Failed;
  544. ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
  545. if (Failed) {
  546. // We might have suffered some sort of placement new earlier, so
  547. // we're constructing in a completely unexpected storage.
  548. // Fall back to a generic pointer cast for this-value.
  549. const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
  550. const CXXRecordDecl *StaticClass = StaticMD->getParent();
  551. QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
  552. ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
  553. }
  554. }
  555. if (!ThisVal.isUnknown())
  556. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  557. }
  558. }
  559. const Expr *CXXMemberCall::getCXXThisExpr() const {
  560. return getOriginExpr()->getImplicitObjectArgument();
  561. }
  562. RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
  563. // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
  564. // id-expression in the class member access expression is a qualified-id,
  565. // that function is called. Otherwise, its final overrider in the dynamic type
  566. // of the object expression is called.
  567. if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
  568. if (ME->hasQualifier())
  569. return AnyFunctionCall::getRuntimeDefinition();
  570. return CXXInstanceCall::getRuntimeDefinition();
  571. }
  572. const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
  573. return getOriginExpr()->getArg(0);
  574. }
  575. const BlockDataRegion *BlockCall::getBlockRegion() const {
  576. const Expr *Callee = getOriginExpr()->getCallee();
  577. const MemRegion *DataReg = getSVal(Callee).getAsRegion();
  578. return dyn_cast_or_null<BlockDataRegion>(DataReg);
  579. }
  580. ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
  581. const BlockDecl *D = getDecl();
  582. if (!D)
  583. return nullptr;
  584. return D->parameters();
  585. }
  586. void BlockCall::getExtraInvalidatedValues(ValueList &Values,
  587. RegionAndSymbolInvalidationTraits *ETraits) const {
  588. // FIXME: This also needs to invalidate captured globals.
  589. if (const MemRegion *R = getBlockRegion())
  590. Values.push_back(loc::MemRegionVal(R));
  591. }
  592. void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
  593. BindingsTy &Bindings) const {
  594. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  595. ArrayRef<ParmVarDecl*> Params;
  596. if (isConversionFromLambda()) {
  597. auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  598. Params = LambdaOperatorDecl->parameters();
  599. // For blocks converted from a C++ lambda, the callee declaration is the
  600. // operator() method on the lambda so we bind "this" to
  601. // the lambda captured by the block.
  602. const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
  603. SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
  604. Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
  605. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  606. } else {
  607. Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
  608. }
  609. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  610. Params);
  611. }
  612. SVal CXXConstructorCall::getCXXThisVal() const {
  613. if (Data)
  614. return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
  615. return UnknownVal();
  616. }
  617. void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
  618. RegionAndSymbolInvalidationTraits *ETraits) const {
  619. if (Data) {
  620. loc::MemRegionVal MV(static_cast<const MemRegion *>(Data));
  621. if (SymbolRef Sym = MV.getAsSymbol(true))
  622. ETraits->setTrait(Sym,
  623. RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
  624. Values.push_back(MV);
  625. }
  626. }
  627. void CXXConstructorCall::getInitialStackFrameContents(
  628. const StackFrameContext *CalleeCtx,
  629. BindingsTy &Bindings) const {
  630. AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
  631. SVal ThisVal = getCXXThisVal();
  632. if (!ThisVal.isUnknown()) {
  633. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  634. const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  635. Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
  636. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  637. }
  638. }
  639. SVal CXXDestructorCall::getCXXThisVal() const {
  640. if (Data)
  641. return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
  642. return UnknownVal();
  643. }
  644. RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
  645. // Base destructors are always called non-virtually.
  646. // Skip CXXInstanceCall's devirtualization logic in this case.
  647. if (isBaseDestructor())
  648. return AnyFunctionCall::getRuntimeDefinition();
  649. return CXXInstanceCall::getRuntimeDefinition();
  650. }
  651. ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
  652. const ObjCMethodDecl *D = getDecl();
  653. if (!D)
  654. return None;
  655. return D->parameters();
  656. }
  657. void ObjCMethodCall::getExtraInvalidatedValues(
  658. ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
  659. // If the method call is a setter for property known to be backed by
  660. // an instance variable, don't invalidate the entire receiver, just
  661. // the storage for that instance variable.
  662. if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
  663. if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
  664. SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
  665. if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
  666. ETraits->setTrait(
  667. IvarRegion,
  668. RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
  669. ETraits->setTrait(
  670. IvarRegion,
  671. RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
  672. Values.push_back(IvarLVal);
  673. }
  674. return;
  675. }
  676. }
  677. Values.push_back(getReceiverSVal());
  678. }
  679. SVal ObjCMethodCall::getSelfSVal() const {
  680. const LocationContext *LCtx = getLocationContext();
  681. const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
  682. if (!SelfDecl)
  683. return SVal();
  684. return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
  685. }
  686. SVal ObjCMethodCall::getReceiverSVal() const {
  687. // FIXME: Is this the best way to handle class receivers?
  688. if (!isInstanceMessage())
  689. return UnknownVal();
  690. if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
  691. return getSVal(RecE);
  692. // An instance message with no expression means we are sending to super.
  693. // In this case the object reference is the same as 'self'.
  694. assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  695. SVal SelfVal = getSelfSVal();
  696. assert(SelfVal.isValid() && "Calling super but not in ObjC method");
  697. return SelfVal;
  698. }
  699. bool ObjCMethodCall::isReceiverSelfOrSuper() const {
  700. if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
  701. getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
  702. return true;
  703. if (!isInstanceMessage())
  704. return false;
  705. SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
  706. return (RecVal == getSelfSVal());
  707. }
  708. SourceRange ObjCMethodCall::getSourceRange() const {
  709. switch (getMessageKind()) {
  710. case OCM_Message:
  711. return getOriginExpr()->getSourceRange();
  712. case OCM_PropertyAccess:
  713. case OCM_Subscript:
  714. return getContainingPseudoObjectExpr()->getSourceRange();
  715. }
  716. llvm_unreachable("unknown message kind");
  717. }
  718. using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
  719. const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
  720. assert(Data && "Lazy lookup not yet performed.");
  721. assert(getMessageKind() != OCM_Message && "Explicit message send.");
  722. return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
  723. }
  724. static const Expr *
  725. getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
  726. const Expr *Syntactic = POE->getSyntacticForm();
  727. // This handles the funny case of assigning to the result of a getter.
  728. // This can happen if the getter returns a non-const reference.
  729. if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
  730. Syntactic = BO->getLHS();
  731. return Syntactic;
  732. }
  733. ObjCMessageKind ObjCMethodCall::getMessageKind() const {
  734. if (!Data) {
  735. // Find the parent, ignoring implicit casts.
  736. ParentMap &PM = getLocationContext()->getParentMap();
  737. const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
  738. // Check if parent is a PseudoObjectExpr.
  739. if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
  740. const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
  741. ObjCMessageKind K;
  742. switch (Syntactic->getStmtClass()) {
  743. case Stmt::ObjCPropertyRefExprClass:
  744. K = OCM_PropertyAccess;
  745. break;
  746. case Stmt::ObjCSubscriptRefExprClass:
  747. K = OCM_Subscript;
  748. break;
  749. default:
  750. // FIXME: Can this ever happen?
  751. K = OCM_Message;
  752. break;
  753. }
  754. if (K != OCM_Message) {
  755. const_cast<ObjCMethodCall *>(this)->Data
  756. = ObjCMessageDataTy(POE, K).getOpaqueValue();
  757. assert(getMessageKind() == K);
  758. return K;
  759. }
  760. }
  761. const_cast<ObjCMethodCall *>(this)->Data
  762. = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
  763. assert(getMessageKind() == OCM_Message);
  764. return OCM_Message;
  765. }
  766. ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
  767. if (!Info.getPointer())
  768. return OCM_Message;
  769. return static_cast<ObjCMessageKind>(Info.getInt());
  770. }
  771. const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
  772. // Look for properties accessed with property syntax (foo.bar = ...)
  773. if ( getMessageKind() == OCM_PropertyAccess) {
  774. const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
  775. assert(POE && "Property access without PseudoObjectExpr?");
  776. const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
  777. auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
  778. if (RefExpr->isExplicitProperty())
  779. return RefExpr->getExplicitProperty();
  780. }
  781. // Look for properties accessed with method syntax ([foo setBar:...]).
  782. const ObjCMethodDecl *MD = getDecl();
  783. if (!MD || !MD->isPropertyAccessor())
  784. return nullptr;
  785. // Note: This is potentially quite slow.
  786. return MD->findPropertyDecl();
  787. }
  788. bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
  789. Selector Sel) const {
  790. assert(IDecl);
  791. const SourceManager &SM =
  792. getState()->getStateManager().getContext().getSourceManager();
  793. // If the class interface is declared inside the main file, assume it is not
  794. // subcassed.
  795. // TODO: It could actually be subclassed if the subclass is private as well.
  796. // This is probably very rare.
  797. SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
  798. if (InterfLoc.isValid() && SM.isInMainFile(InterfLoc))
  799. return false;
  800. // Assume that property accessors are not overridden.
  801. if (getMessageKind() == OCM_PropertyAccess)
  802. return false;
  803. // We assume that if the method is public (declared outside of main file) or
  804. // has a parent which publicly declares the method, the method could be
  805. // overridden in a subclass.
  806. // Find the first declaration in the class hierarchy that declares
  807. // the selector.
  808. ObjCMethodDecl *D = nullptr;
  809. while (true) {
  810. D = IDecl->lookupMethod(Sel, true);
  811. // Cannot find a public definition.
  812. if (!D)
  813. return false;
  814. // If outside the main file,
  815. if (D->getLocation().isValid() && !SM.isInMainFile(D->getLocation()))
  816. return true;
  817. if (D->isOverriding()) {
  818. // Search in the superclass on the next iteration.
  819. IDecl = D->getClassInterface();
  820. if (!IDecl)
  821. return false;
  822. IDecl = IDecl->getSuperClass();
  823. if (!IDecl)
  824. return false;
  825. continue;
  826. }
  827. return false;
  828. };
  829. llvm_unreachable("The while loop should always terminate.");
  830. }
  831. static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
  832. if (!MD)
  833. return MD;
  834. // Find the redeclaration that defines the method.
  835. if (!MD->hasBody()) {
  836. for (auto I : MD->redecls())
  837. if (I->hasBody())
  838. MD = cast<ObjCMethodDecl>(I);
  839. }
  840. return MD;
  841. }
  842. static bool isCallToSelfClass(const ObjCMessageExpr *ME) {
  843. const Expr* InstRec = ME->getInstanceReceiver();
  844. if (!InstRec)
  845. return false;
  846. const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts());
  847. // Check that receiver is called 'self'.
  848. if (!InstRecIg || !InstRecIg->getFoundDecl() ||
  849. !InstRecIg->getFoundDecl()->getName().equals("self"))
  850. return false;
  851. // Check that the method name is 'class'.
  852. if (ME->getSelector().getNumArgs() != 0 ||
  853. !ME->getSelector().getNameForSlot(0).equals("class"))
  854. return false;
  855. return true;
  856. }
  857. RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
  858. const ObjCMessageExpr *E = getOriginExpr();
  859. assert(E);
  860. Selector Sel = E->getSelector();
  861. if (E->isInstanceMessage()) {
  862. // Find the receiver type.
  863. const ObjCObjectPointerType *ReceiverT = nullptr;
  864. bool CanBeSubClassed = false;
  865. QualType SupersType = E->getSuperType();
  866. const MemRegion *Receiver = nullptr;
  867. if (!SupersType.isNull()) {
  868. // The receiver is guaranteed to be 'super' in this case.
  869. // Super always means the type of immediate predecessor to the method
  870. // where the call occurs.
  871. ReceiverT = cast<ObjCObjectPointerType>(SupersType);
  872. } else {
  873. Receiver = getReceiverSVal().getAsRegion();
  874. if (!Receiver)
  875. return {};
  876. DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
  877. if (!DTI.isValid()) {
  878. assert(isa<AllocaRegion>(Receiver) &&
  879. "Unhandled untyped region class!");
  880. return {};
  881. }
  882. QualType DynType = DTI.getType();
  883. CanBeSubClassed = DTI.canBeASubClass();
  884. ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
  885. if (ReceiverT && CanBeSubClassed)
  886. if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
  887. if (!canBeOverridenInSubclass(IDecl, Sel))
  888. CanBeSubClassed = false;
  889. }
  890. // Handle special cases of '[self classMethod]' and
  891. // '[[self class] classMethod]', which are treated by the compiler as
  892. // instance (not class) messages. We will statically dispatch to those.
  893. if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) {
  894. // For [self classMethod], return the compiler visible declaration.
  895. if (PT->getObjectType()->isObjCClass() &&
  896. Receiver == getSelfSVal().getAsRegion())
  897. return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
  898. // Similarly, handle [[self class] classMethod].
  899. // TODO: We are currently doing a syntactic match for this pattern with is
  900. // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m
  901. // shows. A better way would be to associate the meta type with the symbol
  902. // using the dynamic type info tracking and use it here. We can add a new
  903. // SVal for ObjC 'Class' values that know what interface declaration they
  904. // come from. Then 'self' in a class method would be filled in with
  905. // something meaningful in ObjCMethodCall::getReceiverSVal() and we could
  906. // do proper dynamic dispatch for class methods just like we do for
  907. // instance methods now.
  908. if (E->getInstanceReceiver())
  909. if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver()))
  910. if (isCallToSelfClass(M))
  911. return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
  912. }
  913. // Lookup the instance method implementation.
  914. if (ReceiverT)
  915. if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
  916. // Repeatedly calling lookupPrivateMethod() is expensive, especially
  917. // when in many cases it returns null. We cache the results so
  918. // that repeated queries on the same ObjCIntefaceDecl and Selector
  919. // don't incur the same cost. On some test cases, we can see the
  920. // same query being issued thousands of times.
  921. //
  922. // NOTE: This cache is essentially a "global" variable, but it
  923. // only gets lazily created when we get here. The value of the
  924. // cache probably comes from it being global across ExprEngines,
  925. // where the same queries may get issued. If we are worried about
  926. // concurrency, or possibly loading/unloading ASTs, etc., we may
  927. // need to revisit this someday. In terms of memory, this table
  928. // stays around until clang quits, which also may be bad if we
  929. // need to release memory.
  930. using PrivateMethodKey = std::pair<const ObjCInterfaceDecl *, Selector>;
  931. using PrivateMethodCache =
  932. llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>;
  933. static PrivateMethodCache PMC;
  934. Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
  935. // Query lookupPrivateMethod() if the cache does not hit.
  936. if (!Val.hasValue()) {
  937. Val = IDecl->lookupPrivateMethod(Sel);
  938. // If the method is a property accessor, we should try to "inline" it
  939. // even if we don't actually have an implementation.
  940. if (!*Val)
  941. if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
  942. if (CompileTimeMD->isPropertyAccessor()) {
  943. if (!CompileTimeMD->getSelfDecl() &&
  944. isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
  945. // If the method is an accessor in a category, and it doesn't
  946. // have a self declaration, first
  947. // try to find the method in a class extension. This
  948. // works around a bug in Sema where multiple accessors
  949. // are synthesized for properties in class
  950. // extensions that are redeclared in a category and the
  951. // the implicit parameters are not filled in for
  952. // the method on the category.
  953. // This ensures we find the accessor in the extension, which
  954. // has the implicit parameters filled in.
  955. auto *ID = CompileTimeMD->getClassInterface();
  956. for (auto *CatDecl : ID->visible_extensions()) {
  957. Val = CatDecl->getMethod(Sel,
  958. CompileTimeMD->isInstanceMethod());
  959. if (*Val)
  960. break;
  961. }
  962. }
  963. if (!*Val)
  964. Val = IDecl->lookupInstanceMethod(Sel);
  965. }
  966. }
  967. const ObjCMethodDecl *MD = Val.getValue();
  968. if (CanBeSubClassed)
  969. return RuntimeDefinition(MD, Receiver);
  970. else
  971. return RuntimeDefinition(MD, nullptr);
  972. }
  973. } else {
  974. // This is a class method.
  975. // If we have type info for the receiver class, we are calling via
  976. // class name.
  977. if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
  978. // Find/Return the method implementation.
  979. return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
  980. }
  981. }
  982. return {};
  983. }
  984. bool ObjCMethodCall::argumentsMayEscape() const {
  985. if (isInSystemHeader() && !isInstanceMessage()) {
  986. Selector Sel = getSelector();
  987. if (Sel.getNumArgs() == 1 &&
  988. Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
  989. return true;
  990. }
  991. return CallEvent::argumentsMayEscape();
  992. }
  993. void ObjCMethodCall::getInitialStackFrameContents(
  994. const StackFrameContext *CalleeCtx,
  995. BindingsTy &Bindings) const {
  996. const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
  997. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  998. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  999. D->parameters());
  1000. SVal SelfVal = getReceiverSVal();
  1001. if (!SelfVal.isUnknown()) {
  1002. const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
  1003. MemRegionManager &MRMgr = SVB.getRegionManager();
  1004. Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
  1005. Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
  1006. }
  1007. }
  1008. CallEventRef<>
  1009. CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
  1010. const LocationContext *LCtx) {
  1011. if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
  1012. return create<CXXMemberCall>(MCE, State, LCtx);
  1013. if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
  1014. const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
  1015. if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
  1016. if (MD->isInstance())
  1017. return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
  1018. } else if (CE->getCallee()->getType()->isBlockPointerType()) {
  1019. return create<BlockCall>(CE, State, LCtx);
  1020. }
  1021. // Otherwise, it's a normal function call, static member function call, or
  1022. // something we can't reason about.
  1023. return create<SimpleFunctionCall>(CE, State, LCtx);
  1024. }
  1025. CallEventRef<>
  1026. CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
  1027. ProgramStateRef State) {
  1028. const LocationContext *ParentCtx = CalleeCtx->getParent();
  1029. const LocationContext *CallerCtx = ParentCtx->getCurrentStackFrame();
  1030. assert(CallerCtx && "This should not be used for top-level stack frames");
  1031. const Stmt *CallSite = CalleeCtx->getCallSite();
  1032. if (CallSite) {
  1033. if (const CallExpr *CE = dyn_cast<CallExpr>(CallSite))
  1034. return getSimpleCall(CE, State, CallerCtx);
  1035. switch (CallSite->getStmtClass()) {
  1036. case Stmt::CXXConstructExprClass:
  1037. case Stmt::CXXTemporaryObjectExprClass: {
  1038. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  1039. const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  1040. Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
  1041. SVal ThisVal = State->getSVal(ThisPtr);
  1042. return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
  1043. ThisVal.getAsRegion(), State, CallerCtx);
  1044. }
  1045. case Stmt::CXXNewExprClass:
  1046. return getCXXAllocatorCall(cast<CXXNewExpr>(CallSite), State, CallerCtx);
  1047. case Stmt::ObjCMessageExprClass:
  1048. return getObjCMethodCall(cast<ObjCMessageExpr>(CallSite),
  1049. State, CallerCtx);
  1050. default:
  1051. llvm_unreachable("This is not an inlineable statement.");
  1052. }
  1053. }
  1054. // Fall back to the CFG. The only thing we haven't handled yet is
  1055. // destructors, though this could change in the future.
  1056. const CFGBlock *B = CalleeCtx->getCallSiteBlock();
  1057. CFGElement E = (*B)[CalleeCtx->getIndex()];
  1058. assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
  1059. "All other CFG elements should have exprs");
  1060. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  1061. const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
  1062. Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
  1063. SVal ThisVal = State->getSVal(ThisPtr);
  1064. const Stmt *Trigger;
  1065. if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
  1066. Trigger = AutoDtor->getTriggerStmt();
  1067. else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
  1068. Trigger = DeleteDtor->getDeleteExpr();
  1069. else
  1070. Trigger = Dtor->getBody();
  1071. return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
  1072. E.getAs<CFGBaseDtor>().hasValue(), State,
  1073. CallerCtx);
  1074. }