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