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