CallEvent.cpp 49 KB

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