CallEvent.cpp 50 KB

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