CallEvent.cpp 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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/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/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. }
  320. if (!CD.IsLookupDone) {
  321. CD.IsLookupDone = true;
  322. CD.II = &getState()->getStateManager().getContext().Idents.get(
  323. CD.getFunctionName());
  324. }
  325. if (II != CD.II)
  326. return false;
  327. // If CallDescription provides prefix names, use them to improve matching
  328. // accuracy.
  329. if (CD.QualifiedName.size() > 1 && FD) {
  330. const DeclContext *Ctx = FD->getDeclContext();
  331. // See if we'll be able to match them all.
  332. size_t NumUnmatched = CD.QualifiedName.size() - 1;
  333. for (; Ctx && isa<NamedDecl>(Ctx); Ctx = Ctx->getParent()) {
  334. if (NumUnmatched == 0)
  335. break;
  336. if (const auto *ND = dyn_cast<NamespaceDecl>(Ctx)) {
  337. if (ND->getName() == CD.QualifiedName[NumUnmatched - 1])
  338. --NumUnmatched;
  339. continue;
  340. }
  341. if (const auto *RD = dyn_cast<RecordDecl>(Ctx)) {
  342. if (RD->getName() == CD.QualifiedName[NumUnmatched - 1])
  343. --NumUnmatched;
  344. continue;
  345. }
  346. }
  347. if (NumUnmatched > 0)
  348. return false;
  349. }
  350. return (!CD.RequiredArgs || CD.RequiredArgs == getNumArgs());
  351. }
  352. SVal CallEvent::getArgSVal(unsigned Index) const {
  353. const Expr *ArgE = getArgExpr(Index);
  354. if (!ArgE)
  355. return UnknownVal();
  356. return getSVal(ArgE);
  357. }
  358. SourceRange CallEvent::getArgSourceRange(unsigned Index) const {
  359. const Expr *ArgE = getArgExpr(Index);
  360. if (!ArgE)
  361. return {};
  362. return ArgE->getSourceRange();
  363. }
  364. SVal CallEvent::getReturnValue() const {
  365. const Expr *E = getOriginExpr();
  366. if (!E)
  367. return UndefinedVal();
  368. return getSVal(E);
  369. }
  370. LLVM_DUMP_METHOD void CallEvent::dump() const { dump(llvm::errs()); }
  371. void CallEvent::dump(raw_ostream &Out) const {
  372. ASTContext &Ctx = getState()->getStateManager().getContext();
  373. if (const Expr *E = getOriginExpr()) {
  374. E->printPretty(Out, nullptr, Ctx.getPrintingPolicy());
  375. Out << "\n";
  376. return;
  377. }
  378. if (const Decl *D = getDecl()) {
  379. Out << "Call to ";
  380. D->print(Out, Ctx.getPrintingPolicy());
  381. return;
  382. }
  383. // FIXME: a string representation of the kind would be nice.
  384. Out << "Unknown call (type " << getKind() << ")";
  385. }
  386. bool CallEvent::isCallStmt(const Stmt *S) {
  387. return isa<CallExpr>(S) || isa<ObjCMessageExpr>(S)
  388. || isa<CXXConstructExpr>(S)
  389. || isa<CXXNewExpr>(S);
  390. }
  391. QualType CallEvent::getDeclaredResultType(const Decl *D) {
  392. assert(D);
  393. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  394. return FD->getReturnType();
  395. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  396. return MD->getReturnType();
  397. if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  398. // Blocks are difficult because the return type may not be stored in the
  399. // BlockDecl itself. The AST should probably be enhanced, but for now we
  400. // just do what we can.
  401. // If the block is declared without an explicit argument list, the
  402. // signature-as-written just includes the return type, not the entire
  403. // function type.
  404. // FIXME: All blocks should have signatures-as-written, even if the return
  405. // type is inferred. (That's signified with a dependent result type.)
  406. if (const TypeSourceInfo *TSI = BD->getSignatureAsWritten()) {
  407. QualType Ty = TSI->getType();
  408. if (const FunctionType *FT = Ty->getAs<FunctionType>())
  409. Ty = FT->getReturnType();
  410. if (!Ty->isDependentType())
  411. return Ty;
  412. }
  413. return {};
  414. }
  415. llvm_unreachable("unknown callable kind");
  416. }
  417. bool CallEvent::isVariadic(const Decl *D) {
  418. assert(D);
  419. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  420. return FD->isVariadic();
  421. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  422. return MD->isVariadic();
  423. if (const auto *BD = dyn_cast<BlockDecl>(D))
  424. return BD->isVariadic();
  425. llvm_unreachable("unknown callable kind");
  426. }
  427. static void addParameterValuesToBindings(const StackFrameContext *CalleeCtx,
  428. CallEvent::BindingsTy &Bindings,
  429. SValBuilder &SVB,
  430. const CallEvent &Call,
  431. ArrayRef<ParmVarDecl*> parameters) {
  432. MemRegionManager &MRMgr = SVB.getRegionManager();
  433. // If the function has fewer parameters than the call has arguments, we simply
  434. // do not bind any values to them.
  435. unsigned NumArgs = Call.getNumArgs();
  436. unsigned Idx = 0;
  437. ArrayRef<ParmVarDecl*>::iterator I = parameters.begin(), E = parameters.end();
  438. for (; I != E && Idx < NumArgs; ++I, ++Idx) {
  439. const ParmVarDecl *ParamDecl = *I;
  440. assert(ParamDecl && "Formal parameter has no decl?");
  441. // TODO: Support allocator calls.
  442. if (Call.getKind() != CE_CXXAllocator)
  443. if (Call.isArgumentConstructedDirectly(Idx))
  444. continue;
  445. // TODO: Allocators should receive the correct size and possibly alignment,
  446. // determined in compile-time but not represented as arg-expressions,
  447. // which makes getArgSVal() fail and return UnknownVal.
  448. SVal ArgVal = Call.getArgSVal(Idx);
  449. if (!ArgVal.isUnknown()) {
  450. Loc ParamLoc = SVB.makeLoc(MRMgr.getVarRegion(ParamDecl, CalleeCtx));
  451. Bindings.push_back(std::make_pair(ParamLoc, ArgVal));
  452. }
  453. }
  454. // FIXME: Variadic arguments are not handled at all right now.
  455. }
  456. ArrayRef<ParmVarDecl*> AnyFunctionCall::parameters() const {
  457. const FunctionDecl *D = getDecl();
  458. if (!D)
  459. return None;
  460. return D->parameters();
  461. }
  462. RuntimeDefinition AnyFunctionCall::getRuntimeDefinition() const {
  463. const FunctionDecl *FD = getDecl();
  464. if (!FD)
  465. return {};
  466. // Note that the AnalysisDeclContext will have the FunctionDecl with
  467. // the definition (if one exists).
  468. AnalysisDeclContext *AD =
  469. getLocationContext()->getAnalysisDeclContext()->
  470. getManager()->getContext(FD);
  471. bool IsAutosynthesized;
  472. Stmt* Body = AD->getBody(IsAutosynthesized);
  473. LLVM_DEBUG({
  474. if (IsAutosynthesized)
  475. llvm::dbgs() << "Using autosynthesized body for " << FD->getName()
  476. << "\n";
  477. });
  478. if (Body) {
  479. const Decl* Decl = AD->getDecl();
  480. return RuntimeDefinition(Decl);
  481. }
  482. SubEngine &Engine = getState()->getStateManager().getOwningEngine();
  483. AnalyzerOptions &Opts = Engine.getAnalysisManager().options;
  484. // Try to get CTU definition only if CTUDir is provided.
  485. if (!Opts.IsNaiveCTUEnabled)
  486. return {};
  487. cross_tu::CrossTranslationUnitContext &CTUCtx =
  488. *Engine.getCrossTranslationUnitContext();
  489. llvm::Expected<const FunctionDecl *> CTUDeclOrError =
  490. CTUCtx.getCrossTUDefinition(FD, Opts.CTUDir, Opts.CTUIndexName,
  491. Opts.DisplayCTUProgress);
  492. if (!CTUDeclOrError) {
  493. handleAllErrors(CTUDeclOrError.takeError(),
  494. [&](const cross_tu::IndexError &IE) {
  495. CTUCtx.emitCrossTUDiagnostics(IE);
  496. });
  497. return {};
  498. }
  499. return RuntimeDefinition(*CTUDeclOrError);
  500. }
  501. void AnyFunctionCall::getInitialStackFrameContents(
  502. const StackFrameContext *CalleeCtx,
  503. BindingsTy &Bindings) const {
  504. const auto *D = cast<FunctionDecl>(CalleeCtx->getDecl());
  505. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  506. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  507. D->parameters());
  508. }
  509. bool AnyFunctionCall::argumentsMayEscape() const {
  510. if (CallEvent::argumentsMayEscape() || hasVoidPointerToNonConstArg())
  511. return true;
  512. const FunctionDecl *D = getDecl();
  513. if (!D)
  514. return true;
  515. const IdentifierInfo *II = D->getIdentifier();
  516. if (!II)
  517. return false;
  518. // This set of "escaping" APIs is
  519. // - 'int pthread_setspecific(ptheread_key k, const void *)' stores a
  520. // value into thread local storage. The value can later be retrieved with
  521. // 'void *ptheread_getspecific(pthread_key)'. So even thought the
  522. // parameter is 'const void *', the region escapes through the call.
  523. if (II->isStr("pthread_setspecific"))
  524. return true;
  525. // - xpc_connection_set_context stores a value which can be retrieved later
  526. // with xpc_connection_get_context.
  527. if (II->isStr("xpc_connection_set_context"))
  528. return true;
  529. // - funopen - sets a buffer for future IO calls.
  530. if (II->isStr("funopen"))
  531. return true;
  532. // - __cxa_demangle - can reallocate memory and can return the pointer to
  533. // the input buffer.
  534. if (II->isStr("__cxa_demangle"))
  535. return true;
  536. StringRef FName = II->getName();
  537. // - CoreFoundation functions that end with "NoCopy" can free a passed-in
  538. // buffer even if it is const.
  539. if (FName.endswith("NoCopy"))
  540. return true;
  541. // - NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
  542. // be deallocated by NSMapRemove.
  543. if (FName.startswith("NS") && (FName.find("Insert") != StringRef::npos))
  544. return true;
  545. // - Many CF containers allow objects to escape through custom
  546. // allocators/deallocators upon container construction. (PR12101)
  547. if (FName.startswith("CF") || FName.startswith("CG")) {
  548. return StrInStrNoCase(FName, "InsertValue") != StringRef::npos ||
  549. StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
  550. StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
  551. StrInStrNoCase(FName, "WithData") != StringRef::npos ||
  552. StrInStrNoCase(FName, "AppendValue") != StringRef::npos ||
  553. StrInStrNoCase(FName, "SetAttribute") != StringRef::npos;
  554. }
  555. return false;
  556. }
  557. const FunctionDecl *SimpleFunctionCall::getDecl() const {
  558. const FunctionDecl *D = getOriginExpr()->getDirectCallee();
  559. if (D)
  560. return D;
  561. return getSVal(getOriginExpr()->getCallee()).getAsFunctionDecl();
  562. }
  563. const FunctionDecl *CXXInstanceCall::getDecl() const {
  564. const auto *CE = cast_or_null<CallExpr>(getOriginExpr());
  565. if (!CE)
  566. return AnyFunctionCall::getDecl();
  567. const FunctionDecl *D = CE->getDirectCallee();
  568. if (D)
  569. return D;
  570. return getSVal(CE->getCallee()).getAsFunctionDecl();
  571. }
  572. void CXXInstanceCall::getExtraInvalidatedValues(
  573. ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
  574. SVal ThisVal = getCXXThisVal();
  575. Values.push_back(ThisVal);
  576. // Don't invalidate if the method is const and there are no mutable fields.
  577. if (const auto *D = cast_or_null<CXXMethodDecl>(getDecl())) {
  578. if (!D->isConst())
  579. return;
  580. // Get the record decl for the class of 'This'. D->getParent() may return a
  581. // base class decl, rather than the class of the instance which needs to be
  582. // checked for mutable fields.
  583. // TODO: We might as well look at the dynamic type of the object.
  584. const Expr *Ex = getCXXThisExpr()->ignoreParenBaseCasts();
  585. QualType T = Ex->getType();
  586. if (T->isPointerType()) // Arrow or implicit-this syntax?
  587. T = T->getPointeeType();
  588. const CXXRecordDecl *ParentRecord = T->getAsCXXRecordDecl();
  589. assert(ParentRecord);
  590. if (ParentRecord->hasMutableFields())
  591. return;
  592. // Preserve CXXThis.
  593. const MemRegion *ThisRegion = ThisVal.getAsRegion();
  594. if (!ThisRegion)
  595. return;
  596. ETraits->setTrait(ThisRegion->getBaseRegion(),
  597. RegionAndSymbolInvalidationTraits::TK_PreserveContents);
  598. }
  599. }
  600. SVal CXXInstanceCall::getCXXThisVal() const {
  601. const Expr *Base = getCXXThisExpr();
  602. // FIXME: This doesn't handle an overloaded ->* operator.
  603. if (!Base)
  604. return UnknownVal();
  605. SVal ThisVal = getSVal(Base);
  606. assert(ThisVal.isUnknownOrUndef() || ThisVal.getAs<Loc>());
  607. return ThisVal;
  608. }
  609. RuntimeDefinition CXXInstanceCall::getRuntimeDefinition() const {
  610. // Do we have a decl at all?
  611. const Decl *D = getDecl();
  612. if (!D)
  613. return {};
  614. // If the method is non-virtual, we know we can inline it.
  615. const auto *MD = cast<CXXMethodDecl>(D);
  616. if (!MD->isVirtual())
  617. return AnyFunctionCall::getRuntimeDefinition();
  618. // Do we know the implicit 'this' object being called?
  619. const MemRegion *R = getCXXThisVal().getAsRegion();
  620. if (!R)
  621. return {};
  622. // Do we know anything about the type of 'this'?
  623. DynamicTypeInfo DynType = getDynamicTypeInfo(getState(), R);
  624. if (!DynType.isValid())
  625. return {};
  626. // Is the type a C++ class? (This is mostly a defensive check.)
  627. QualType RegionType = DynType.getType()->getPointeeType();
  628. assert(!RegionType.isNull() && "DynamicTypeInfo should always be a pointer.");
  629. const CXXRecordDecl *RD = RegionType->getAsCXXRecordDecl();
  630. if (!RD || !RD->hasDefinition())
  631. return {};
  632. // Find the decl for this method in that class.
  633. const CXXMethodDecl *Result = MD->getCorrespondingMethodInClass(RD, true);
  634. if (!Result) {
  635. // We might not even get the original statically-resolved method due to
  636. // some particularly nasty casting (e.g. casts to sister classes).
  637. // However, we should at least be able to search up and down our own class
  638. // hierarchy, and some real bugs have been caught by checking this.
  639. assert(!RD->isDerivedFrom(MD->getParent()) && "Couldn't find known method");
  640. // FIXME: This is checking that our DynamicTypeInfo is at least as good as
  641. // the static type. However, because we currently don't update
  642. // DynamicTypeInfo when an object is cast, we can't actually be sure the
  643. // DynamicTypeInfo is up to date. This assert should be re-enabled once
  644. // this is fixed. <rdar://problem/12287087>
  645. //assert(!MD->getParent()->isDerivedFrom(RD) && "Bad DynamicTypeInfo");
  646. return {};
  647. }
  648. // Does the decl that we found have an implementation?
  649. const FunctionDecl *Definition;
  650. if (!Result->hasBody(Definition)) {
  651. if (!DynType.canBeASubClass())
  652. return AnyFunctionCall::getRuntimeDefinition();
  653. return {};
  654. }
  655. // We found a definition. If we're not sure that this devirtualization is
  656. // actually what will happen at runtime, make sure to provide the region so
  657. // that ExprEngine can decide what to do with it.
  658. if (DynType.canBeASubClass())
  659. return RuntimeDefinition(Definition, R->StripCasts());
  660. return RuntimeDefinition(Definition, /*DispatchRegion=*/nullptr);
  661. }
  662. void CXXInstanceCall::getInitialStackFrameContents(
  663. const StackFrameContext *CalleeCtx,
  664. BindingsTy &Bindings) const {
  665. AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
  666. // Handle the binding of 'this' in the new stack frame.
  667. SVal ThisVal = getCXXThisVal();
  668. if (!ThisVal.isUnknown()) {
  669. ProgramStateManager &StateMgr = getState()->getStateManager();
  670. SValBuilder &SVB = StateMgr.getSValBuilder();
  671. const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  672. Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
  673. // If we devirtualized to a different member function, we need to make sure
  674. // we have the proper layering of CXXBaseObjectRegions.
  675. if (MD->getCanonicalDecl() != getDecl()->getCanonicalDecl()) {
  676. ASTContext &Ctx = SVB.getContext();
  677. const CXXRecordDecl *Class = MD->getParent();
  678. QualType Ty = Ctx.getPointerType(Ctx.getRecordType(Class));
  679. // FIXME: CallEvent maybe shouldn't be directly accessing StoreManager.
  680. bool Failed;
  681. ThisVal = StateMgr.getStoreManager().attemptDownCast(ThisVal, Ty, Failed);
  682. if (Failed) {
  683. // We might have suffered some sort of placement new earlier, so
  684. // we're constructing in a completely unexpected storage.
  685. // Fall back to a generic pointer cast for this-value.
  686. const CXXMethodDecl *StaticMD = cast<CXXMethodDecl>(getDecl());
  687. const CXXRecordDecl *StaticClass = StaticMD->getParent();
  688. QualType StaticTy = Ctx.getPointerType(Ctx.getRecordType(StaticClass));
  689. ThisVal = SVB.evalCast(ThisVal, Ty, StaticTy);
  690. }
  691. }
  692. if (!ThisVal.isUnknown())
  693. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  694. }
  695. }
  696. const Expr *CXXMemberCall::getCXXThisExpr() const {
  697. return getOriginExpr()->getImplicitObjectArgument();
  698. }
  699. RuntimeDefinition CXXMemberCall::getRuntimeDefinition() const {
  700. // C++11 [expr.call]p1: ...If the selected function is non-virtual, or if the
  701. // id-expression in the class member access expression is a qualified-id,
  702. // that function is called. Otherwise, its final overrider in the dynamic type
  703. // of the object expression is called.
  704. if (const auto *ME = dyn_cast<MemberExpr>(getOriginExpr()->getCallee()))
  705. if (ME->hasQualifier())
  706. return AnyFunctionCall::getRuntimeDefinition();
  707. return CXXInstanceCall::getRuntimeDefinition();
  708. }
  709. const Expr *CXXMemberOperatorCall::getCXXThisExpr() const {
  710. return getOriginExpr()->getArg(0);
  711. }
  712. const BlockDataRegion *BlockCall::getBlockRegion() const {
  713. const Expr *Callee = getOriginExpr()->getCallee();
  714. const MemRegion *DataReg = getSVal(Callee).getAsRegion();
  715. return dyn_cast_or_null<BlockDataRegion>(DataReg);
  716. }
  717. ArrayRef<ParmVarDecl*> BlockCall::parameters() const {
  718. const BlockDecl *D = getDecl();
  719. if (!D)
  720. return None;
  721. return D->parameters();
  722. }
  723. void BlockCall::getExtraInvalidatedValues(ValueList &Values,
  724. RegionAndSymbolInvalidationTraits *ETraits) const {
  725. // FIXME: This also needs to invalidate captured globals.
  726. if (const MemRegion *R = getBlockRegion())
  727. Values.push_back(loc::MemRegionVal(R));
  728. }
  729. void BlockCall::getInitialStackFrameContents(const StackFrameContext *CalleeCtx,
  730. BindingsTy &Bindings) const {
  731. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  732. ArrayRef<ParmVarDecl*> Params;
  733. if (isConversionFromLambda()) {
  734. auto *LambdaOperatorDecl = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  735. Params = LambdaOperatorDecl->parameters();
  736. // For blocks converted from a C++ lambda, the callee declaration is the
  737. // operator() method on the lambda so we bind "this" to
  738. // the lambda captured by the block.
  739. const VarRegion *CapturedLambdaRegion = getRegionStoringCapturedLambda();
  740. SVal ThisVal = loc::MemRegionVal(CapturedLambdaRegion);
  741. Loc ThisLoc = SVB.getCXXThis(LambdaOperatorDecl, CalleeCtx);
  742. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  743. } else {
  744. Params = cast<BlockDecl>(CalleeCtx->getDecl())->parameters();
  745. }
  746. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  747. Params);
  748. }
  749. SVal CXXConstructorCall::getCXXThisVal() const {
  750. if (Data)
  751. return loc::MemRegionVal(static_cast<const MemRegion *>(Data));
  752. return UnknownVal();
  753. }
  754. void CXXConstructorCall::getExtraInvalidatedValues(ValueList &Values,
  755. RegionAndSymbolInvalidationTraits *ETraits) const {
  756. if (Data) {
  757. loc::MemRegionVal MV(static_cast<const MemRegion *>(Data));
  758. if (SymbolRef Sym = MV.getAsSymbol(true))
  759. ETraits->setTrait(Sym,
  760. RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
  761. Values.push_back(MV);
  762. }
  763. }
  764. void CXXConstructorCall::getInitialStackFrameContents(
  765. const StackFrameContext *CalleeCtx,
  766. BindingsTy &Bindings) const {
  767. AnyFunctionCall::getInitialStackFrameContents(CalleeCtx, Bindings);
  768. SVal ThisVal = getCXXThisVal();
  769. if (!ThisVal.isUnknown()) {
  770. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  771. const auto *MD = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  772. Loc ThisLoc = SVB.getCXXThis(MD, CalleeCtx);
  773. Bindings.push_back(std::make_pair(ThisLoc, ThisVal));
  774. }
  775. }
  776. SVal CXXDestructorCall::getCXXThisVal() const {
  777. if (Data)
  778. return loc::MemRegionVal(DtorDataTy::getFromOpaqueValue(Data).getPointer());
  779. return UnknownVal();
  780. }
  781. RuntimeDefinition CXXDestructorCall::getRuntimeDefinition() const {
  782. // Base destructors are always called non-virtually.
  783. // Skip CXXInstanceCall's devirtualization logic in this case.
  784. if (isBaseDestructor())
  785. return AnyFunctionCall::getRuntimeDefinition();
  786. return CXXInstanceCall::getRuntimeDefinition();
  787. }
  788. ArrayRef<ParmVarDecl*> ObjCMethodCall::parameters() const {
  789. const ObjCMethodDecl *D = getDecl();
  790. if (!D)
  791. return None;
  792. return D->parameters();
  793. }
  794. void ObjCMethodCall::getExtraInvalidatedValues(
  795. ValueList &Values, RegionAndSymbolInvalidationTraits *ETraits) const {
  796. // If the method call is a setter for property known to be backed by
  797. // an instance variable, don't invalidate the entire receiver, just
  798. // the storage for that instance variable.
  799. if (const ObjCPropertyDecl *PropDecl = getAccessedProperty()) {
  800. if (const ObjCIvarDecl *PropIvar = PropDecl->getPropertyIvarDecl()) {
  801. SVal IvarLVal = getState()->getLValue(PropIvar, getReceiverSVal());
  802. if (const MemRegion *IvarRegion = IvarLVal.getAsRegion()) {
  803. ETraits->setTrait(
  804. IvarRegion,
  805. RegionAndSymbolInvalidationTraits::TK_DoNotInvalidateSuperRegion);
  806. ETraits->setTrait(
  807. IvarRegion,
  808. RegionAndSymbolInvalidationTraits::TK_SuppressEscape);
  809. Values.push_back(IvarLVal);
  810. }
  811. return;
  812. }
  813. }
  814. Values.push_back(getReceiverSVal());
  815. }
  816. SVal ObjCMethodCall::getSelfSVal() const {
  817. const LocationContext *LCtx = getLocationContext();
  818. const ImplicitParamDecl *SelfDecl = LCtx->getSelfDecl();
  819. if (!SelfDecl)
  820. return SVal();
  821. return getState()->getSVal(getState()->getRegion(SelfDecl, LCtx));
  822. }
  823. SVal ObjCMethodCall::getReceiverSVal() const {
  824. // FIXME: Is this the best way to handle class receivers?
  825. if (!isInstanceMessage())
  826. return UnknownVal();
  827. if (const Expr *RecE = getOriginExpr()->getInstanceReceiver())
  828. return getSVal(RecE);
  829. // An instance message with no expression means we are sending to super.
  830. // In this case the object reference is the same as 'self'.
  831. assert(getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  832. SVal SelfVal = getSelfSVal();
  833. assert(SelfVal.isValid() && "Calling super but not in ObjC method");
  834. return SelfVal;
  835. }
  836. bool ObjCMethodCall::isReceiverSelfOrSuper() const {
  837. if (getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperInstance ||
  838. getOriginExpr()->getReceiverKind() == ObjCMessageExpr::SuperClass)
  839. return true;
  840. if (!isInstanceMessage())
  841. return false;
  842. SVal RecVal = getSVal(getOriginExpr()->getInstanceReceiver());
  843. return (RecVal == getSelfSVal());
  844. }
  845. SourceRange ObjCMethodCall::getSourceRange() const {
  846. switch (getMessageKind()) {
  847. case OCM_Message:
  848. return getOriginExpr()->getSourceRange();
  849. case OCM_PropertyAccess:
  850. case OCM_Subscript:
  851. return getContainingPseudoObjectExpr()->getSourceRange();
  852. }
  853. llvm_unreachable("unknown message kind");
  854. }
  855. using ObjCMessageDataTy = llvm::PointerIntPair<const PseudoObjectExpr *, 2>;
  856. const PseudoObjectExpr *ObjCMethodCall::getContainingPseudoObjectExpr() const {
  857. assert(Data && "Lazy lookup not yet performed.");
  858. assert(getMessageKind() != OCM_Message && "Explicit message send.");
  859. return ObjCMessageDataTy::getFromOpaqueValue(Data).getPointer();
  860. }
  861. static const Expr *
  862. getSyntacticFromForPseudoObjectExpr(const PseudoObjectExpr *POE) {
  863. const Expr *Syntactic = POE->getSyntacticForm();
  864. // This handles the funny case of assigning to the result of a getter.
  865. // This can happen if the getter returns a non-const reference.
  866. if (const auto *BO = dyn_cast<BinaryOperator>(Syntactic))
  867. Syntactic = BO->getLHS();
  868. return Syntactic;
  869. }
  870. ObjCMessageKind ObjCMethodCall::getMessageKind() const {
  871. if (!Data) {
  872. // Find the parent, ignoring implicit casts.
  873. const ParentMap &PM = getLocationContext()->getParentMap();
  874. const Stmt *S = PM.getParentIgnoreParenCasts(getOriginExpr());
  875. // Check if parent is a PseudoObjectExpr.
  876. if (const auto *POE = dyn_cast_or_null<PseudoObjectExpr>(S)) {
  877. const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
  878. ObjCMessageKind K;
  879. switch (Syntactic->getStmtClass()) {
  880. case Stmt::ObjCPropertyRefExprClass:
  881. K = OCM_PropertyAccess;
  882. break;
  883. case Stmt::ObjCSubscriptRefExprClass:
  884. K = OCM_Subscript;
  885. break;
  886. default:
  887. // FIXME: Can this ever happen?
  888. K = OCM_Message;
  889. break;
  890. }
  891. if (K != OCM_Message) {
  892. const_cast<ObjCMethodCall *>(this)->Data
  893. = ObjCMessageDataTy(POE, K).getOpaqueValue();
  894. assert(getMessageKind() == K);
  895. return K;
  896. }
  897. }
  898. const_cast<ObjCMethodCall *>(this)->Data
  899. = ObjCMessageDataTy(nullptr, 1).getOpaqueValue();
  900. assert(getMessageKind() == OCM_Message);
  901. return OCM_Message;
  902. }
  903. ObjCMessageDataTy Info = ObjCMessageDataTy::getFromOpaqueValue(Data);
  904. if (!Info.getPointer())
  905. return OCM_Message;
  906. return static_cast<ObjCMessageKind>(Info.getInt());
  907. }
  908. const ObjCPropertyDecl *ObjCMethodCall::getAccessedProperty() const {
  909. // Look for properties accessed with property syntax (foo.bar = ...)
  910. if ( getMessageKind() == OCM_PropertyAccess) {
  911. const PseudoObjectExpr *POE = getContainingPseudoObjectExpr();
  912. assert(POE && "Property access without PseudoObjectExpr?");
  913. const Expr *Syntactic = getSyntacticFromForPseudoObjectExpr(POE);
  914. auto *RefExpr = cast<ObjCPropertyRefExpr>(Syntactic);
  915. if (RefExpr->isExplicitProperty())
  916. return RefExpr->getExplicitProperty();
  917. }
  918. // Look for properties accessed with method syntax ([foo setBar:...]).
  919. const ObjCMethodDecl *MD = getDecl();
  920. if (!MD || !MD->isPropertyAccessor())
  921. return nullptr;
  922. // Note: This is potentially quite slow.
  923. return MD->findPropertyDecl();
  924. }
  925. bool ObjCMethodCall::canBeOverridenInSubclass(ObjCInterfaceDecl *IDecl,
  926. Selector Sel) const {
  927. assert(IDecl);
  928. AnalysisManager &AMgr =
  929. getState()->getStateManager().getOwningEngine().getAnalysisManager();
  930. // If the class interface is declared inside the main file, assume it is not
  931. // subcassed.
  932. // TODO: It could actually be subclassed if the subclass is private as well.
  933. // This is probably very rare.
  934. SourceLocation InterfLoc = IDecl->getEndOfDefinitionLoc();
  935. if (InterfLoc.isValid() && AMgr.isInCodeFile(InterfLoc))
  936. return false;
  937. // Assume that property accessors are not overridden.
  938. if (getMessageKind() == OCM_PropertyAccess)
  939. return false;
  940. // We assume that if the method is public (declared outside of main file) or
  941. // has a parent which publicly declares the method, the method could be
  942. // overridden in a subclass.
  943. // Find the first declaration in the class hierarchy that declares
  944. // the selector.
  945. ObjCMethodDecl *D = nullptr;
  946. while (true) {
  947. D = IDecl->lookupMethod(Sel, true);
  948. // Cannot find a public definition.
  949. if (!D)
  950. return false;
  951. // If outside the main file,
  952. if (D->getLocation().isValid() && !AMgr.isInCodeFile(D->getLocation()))
  953. return true;
  954. if (D->isOverriding()) {
  955. // Search in the superclass on the next iteration.
  956. IDecl = D->getClassInterface();
  957. if (!IDecl)
  958. return false;
  959. IDecl = IDecl->getSuperClass();
  960. if (!IDecl)
  961. return false;
  962. continue;
  963. }
  964. return false;
  965. };
  966. llvm_unreachable("The while loop should always terminate.");
  967. }
  968. static const ObjCMethodDecl *findDefiningRedecl(const ObjCMethodDecl *MD) {
  969. if (!MD)
  970. return MD;
  971. // Find the redeclaration that defines the method.
  972. if (!MD->hasBody()) {
  973. for (auto I : MD->redecls())
  974. if (I->hasBody())
  975. MD = cast<ObjCMethodDecl>(I);
  976. }
  977. return MD;
  978. }
  979. static bool isCallToSelfClass(const ObjCMessageExpr *ME) {
  980. const Expr* InstRec = ME->getInstanceReceiver();
  981. if (!InstRec)
  982. return false;
  983. const auto *InstRecIg = dyn_cast<DeclRefExpr>(InstRec->IgnoreParenImpCasts());
  984. // Check that receiver is called 'self'.
  985. if (!InstRecIg || !InstRecIg->getFoundDecl() ||
  986. !InstRecIg->getFoundDecl()->getName().equals("self"))
  987. return false;
  988. // Check that the method name is 'class'.
  989. if (ME->getSelector().getNumArgs() != 0 ||
  990. !ME->getSelector().getNameForSlot(0).equals("class"))
  991. return false;
  992. return true;
  993. }
  994. RuntimeDefinition ObjCMethodCall::getRuntimeDefinition() const {
  995. const ObjCMessageExpr *E = getOriginExpr();
  996. assert(E);
  997. Selector Sel = E->getSelector();
  998. if (E->isInstanceMessage()) {
  999. // Find the receiver type.
  1000. const ObjCObjectPointerType *ReceiverT = nullptr;
  1001. bool CanBeSubClassed = false;
  1002. QualType SupersType = E->getSuperType();
  1003. const MemRegion *Receiver = nullptr;
  1004. if (!SupersType.isNull()) {
  1005. // The receiver is guaranteed to be 'super' in this case.
  1006. // Super always means the type of immediate predecessor to the method
  1007. // where the call occurs.
  1008. ReceiverT = cast<ObjCObjectPointerType>(SupersType);
  1009. } else {
  1010. Receiver = getReceiverSVal().getAsRegion();
  1011. if (!Receiver)
  1012. return {};
  1013. DynamicTypeInfo DTI = getDynamicTypeInfo(getState(), Receiver);
  1014. if (!DTI.isValid()) {
  1015. assert(isa<AllocaRegion>(Receiver) &&
  1016. "Unhandled untyped region class!");
  1017. return {};
  1018. }
  1019. QualType DynType = DTI.getType();
  1020. CanBeSubClassed = DTI.canBeASubClass();
  1021. ReceiverT = dyn_cast<ObjCObjectPointerType>(DynType.getCanonicalType());
  1022. if (ReceiverT && CanBeSubClassed)
  1023. if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl())
  1024. if (!canBeOverridenInSubclass(IDecl, Sel))
  1025. CanBeSubClassed = false;
  1026. }
  1027. // Handle special cases of '[self classMethod]' and
  1028. // '[[self class] classMethod]', which are treated by the compiler as
  1029. // instance (not class) messages. We will statically dispatch to those.
  1030. if (auto *PT = dyn_cast_or_null<ObjCObjectPointerType>(ReceiverT)) {
  1031. // For [self classMethod], return the compiler visible declaration.
  1032. if (PT->getObjectType()->isObjCClass() &&
  1033. Receiver == getSelfSVal().getAsRegion())
  1034. return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
  1035. // Similarly, handle [[self class] classMethod].
  1036. // TODO: We are currently doing a syntactic match for this pattern with is
  1037. // limiting as the test cases in Analysis/inlining/InlineObjCClassMethod.m
  1038. // shows. A better way would be to associate the meta type with the symbol
  1039. // using the dynamic type info tracking and use it here. We can add a new
  1040. // SVal for ObjC 'Class' values that know what interface declaration they
  1041. // come from. Then 'self' in a class method would be filled in with
  1042. // something meaningful in ObjCMethodCall::getReceiverSVal() and we could
  1043. // do proper dynamic dispatch for class methods just like we do for
  1044. // instance methods now.
  1045. if (E->getInstanceReceiver())
  1046. if (const auto *M = dyn_cast<ObjCMessageExpr>(E->getInstanceReceiver()))
  1047. if (isCallToSelfClass(M))
  1048. return RuntimeDefinition(findDefiningRedecl(E->getMethodDecl()));
  1049. }
  1050. // Lookup the instance method implementation.
  1051. if (ReceiverT)
  1052. if (ObjCInterfaceDecl *IDecl = ReceiverT->getInterfaceDecl()) {
  1053. // Repeatedly calling lookupPrivateMethod() is expensive, especially
  1054. // when in many cases it returns null. We cache the results so
  1055. // that repeated queries on the same ObjCIntefaceDecl and Selector
  1056. // don't incur the same cost. On some test cases, we can see the
  1057. // same query being issued thousands of times.
  1058. //
  1059. // NOTE: This cache is essentially a "global" variable, but it
  1060. // only gets lazily created when we get here. The value of the
  1061. // cache probably comes from it being global across ExprEngines,
  1062. // where the same queries may get issued. If we are worried about
  1063. // concurrency, or possibly loading/unloading ASTs, etc., we may
  1064. // need to revisit this someday. In terms of memory, this table
  1065. // stays around until clang quits, which also may be bad if we
  1066. // need to release memory.
  1067. using PrivateMethodKey = std::pair<const ObjCInterfaceDecl *, Selector>;
  1068. using PrivateMethodCache =
  1069. llvm::DenseMap<PrivateMethodKey, Optional<const ObjCMethodDecl *>>;
  1070. static PrivateMethodCache PMC;
  1071. Optional<const ObjCMethodDecl *> &Val = PMC[std::make_pair(IDecl, Sel)];
  1072. // Query lookupPrivateMethod() if the cache does not hit.
  1073. if (!Val.hasValue()) {
  1074. Val = IDecl->lookupPrivateMethod(Sel);
  1075. // If the method is a property accessor, we should try to "inline" it
  1076. // even if we don't actually have an implementation.
  1077. if (!*Val)
  1078. if (const ObjCMethodDecl *CompileTimeMD = E->getMethodDecl())
  1079. if (CompileTimeMD->isPropertyAccessor()) {
  1080. if (!CompileTimeMD->getSelfDecl() &&
  1081. isa<ObjCCategoryDecl>(CompileTimeMD->getDeclContext())) {
  1082. // If the method is an accessor in a category, and it doesn't
  1083. // have a self declaration, first
  1084. // try to find the method in a class extension. This
  1085. // works around a bug in Sema where multiple accessors
  1086. // are synthesized for properties in class
  1087. // extensions that are redeclared in a category and the
  1088. // the implicit parameters are not filled in for
  1089. // the method on the category.
  1090. // This ensures we find the accessor in the extension, which
  1091. // has the implicit parameters filled in.
  1092. auto *ID = CompileTimeMD->getClassInterface();
  1093. for (auto *CatDecl : ID->visible_extensions()) {
  1094. Val = CatDecl->getMethod(Sel,
  1095. CompileTimeMD->isInstanceMethod());
  1096. if (*Val)
  1097. break;
  1098. }
  1099. }
  1100. if (!*Val)
  1101. Val = IDecl->lookupInstanceMethod(Sel);
  1102. }
  1103. }
  1104. const ObjCMethodDecl *MD = Val.getValue();
  1105. if (CanBeSubClassed)
  1106. return RuntimeDefinition(MD, Receiver);
  1107. else
  1108. return RuntimeDefinition(MD, nullptr);
  1109. }
  1110. } else {
  1111. // This is a class method.
  1112. // If we have type info for the receiver class, we are calling via
  1113. // class name.
  1114. if (ObjCInterfaceDecl *IDecl = E->getReceiverInterface()) {
  1115. // Find/Return the method implementation.
  1116. return RuntimeDefinition(IDecl->lookupPrivateClassMethod(Sel));
  1117. }
  1118. }
  1119. return {};
  1120. }
  1121. bool ObjCMethodCall::argumentsMayEscape() const {
  1122. if (isInSystemHeader() && !isInstanceMessage()) {
  1123. Selector Sel = getSelector();
  1124. if (Sel.getNumArgs() == 1 &&
  1125. Sel.getIdentifierInfoForSlot(0)->isStr("valueWithPointer"))
  1126. return true;
  1127. }
  1128. return CallEvent::argumentsMayEscape();
  1129. }
  1130. void ObjCMethodCall::getInitialStackFrameContents(
  1131. const StackFrameContext *CalleeCtx,
  1132. BindingsTy &Bindings) const {
  1133. const auto *D = cast<ObjCMethodDecl>(CalleeCtx->getDecl());
  1134. SValBuilder &SVB = getState()->getStateManager().getSValBuilder();
  1135. addParameterValuesToBindings(CalleeCtx, Bindings, SVB, *this,
  1136. D->parameters());
  1137. SVal SelfVal = getReceiverSVal();
  1138. if (!SelfVal.isUnknown()) {
  1139. const VarDecl *SelfD = CalleeCtx->getAnalysisDeclContext()->getSelfDecl();
  1140. MemRegionManager &MRMgr = SVB.getRegionManager();
  1141. Loc SelfLoc = SVB.makeLoc(MRMgr.getVarRegion(SelfD, CalleeCtx));
  1142. Bindings.push_back(std::make_pair(SelfLoc, SelfVal));
  1143. }
  1144. }
  1145. CallEventRef<>
  1146. CallEventManager::getSimpleCall(const CallExpr *CE, ProgramStateRef State,
  1147. const LocationContext *LCtx) {
  1148. if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(CE))
  1149. return create<CXXMemberCall>(MCE, State, LCtx);
  1150. if (const auto *OpCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
  1151. const FunctionDecl *DirectCallee = OpCE->getDirectCallee();
  1152. if (const auto *MD = dyn_cast<CXXMethodDecl>(DirectCallee))
  1153. if (MD->isInstance())
  1154. return create<CXXMemberOperatorCall>(OpCE, State, LCtx);
  1155. } else if (CE->getCallee()->getType()->isBlockPointerType()) {
  1156. return create<BlockCall>(CE, State, LCtx);
  1157. }
  1158. // Otherwise, it's a normal function call, static member function call, or
  1159. // something we can't reason about.
  1160. return create<SimpleFunctionCall>(CE, State, LCtx);
  1161. }
  1162. CallEventRef<>
  1163. CallEventManager::getCaller(const StackFrameContext *CalleeCtx,
  1164. ProgramStateRef State) {
  1165. const LocationContext *ParentCtx = CalleeCtx->getParent();
  1166. const LocationContext *CallerCtx = ParentCtx->getStackFrame();
  1167. assert(CallerCtx && "This should not be used for top-level stack frames");
  1168. const Stmt *CallSite = CalleeCtx->getCallSite();
  1169. if (CallSite) {
  1170. if (CallEventRef<> Out = getCall(CallSite, State, CallerCtx))
  1171. return Out;
  1172. // All other cases are handled by getCall.
  1173. assert(isa<CXXConstructExpr>(CallSite) &&
  1174. "This is not an inlineable statement");
  1175. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  1176. const auto *Ctor = cast<CXXMethodDecl>(CalleeCtx->getDecl());
  1177. Loc ThisPtr = SVB.getCXXThis(Ctor, CalleeCtx);
  1178. SVal ThisVal = State->getSVal(ThisPtr);
  1179. return getCXXConstructorCall(cast<CXXConstructExpr>(CallSite),
  1180. ThisVal.getAsRegion(), State, CallerCtx);
  1181. }
  1182. // Fall back to the CFG. The only thing we haven't handled yet is
  1183. // destructors, though this could change in the future.
  1184. const CFGBlock *B = CalleeCtx->getCallSiteBlock();
  1185. CFGElement E = (*B)[CalleeCtx->getIndex()];
  1186. assert((E.getAs<CFGImplicitDtor>() || E.getAs<CFGTemporaryDtor>()) &&
  1187. "All other CFG elements should have exprs");
  1188. SValBuilder &SVB = State->getStateManager().getSValBuilder();
  1189. const auto *Dtor = cast<CXXDestructorDecl>(CalleeCtx->getDecl());
  1190. Loc ThisPtr = SVB.getCXXThis(Dtor, CalleeCtx);
  1191. SVal ThisVal = State->getSVal(ThisPtr);
  1192. const Stmt *Trigger;
  1193. if (Optional<CFGAutomaticObjDtor> AutoDtor = E.getAs<CFGAutomaticObjDtor>())
  1194. Trigger = AutoDtor->getTriggerStmt();
  1195. else if (Optional<CFGDeleteDtor> DeleteDtor = E.getAs<CFGDeleteDtor>())
  1196. Trigger = DeleteDtor->getDeleteExpr();
  1197. else
  1198. Trigger = Dtor->getBody();
  1199. return getCXXDestructorCall(Dtor, Trigger, ThisVal.getAsRegion(),
  1200. E.getAs<CFGBaseDtor>().hasValue(), State,
  1201. CallerCtx);
  1202. }
  1203. CallEventRef<> CallEventManager::getCall(const Stmt *S, ProgramStateRef State,
  1204. const LocationContext *LC) {
  1205. if (const auto *CE = dyn_cast<CallExpr>(S)) {
  1206. return getSimpleCall(CE, State, LC);
  1207. } else if (const auto *NE = dyn_cast<CXXNewExpr>(S)) {
  1208. return getCXXAllocatorCall(NE, State, LC);
  1209. } else if (const auto *ME = dyn_cast<ObjCMessageExpr>(S)) {
  1210. return getObjCMethodCall(ME, State, LC);
  1211. } else {
  1212. return nullptr;
  1213. }
  1214. }