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