CallEvent.cpp 51 KB

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