16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallVector.h"
37 return std::string(RD->getName());
53 assert(!PrevV.
hasSameState(CurrV) &&
"The state should have changed.");
58 os <<
"Object released by directly sending the '-dealloc' message";
74 os <<
"Object autoreleased";
79 os <<
"Reference count decremented";
81 os <<
"Reference count incremented";
83 if (
unsigned Count = CurrV.
getCount())
84 os <<
"; the object now has a +" << Count <<
" retain count";
90 RefVal::IvarAccessHistory::ReleasedAfterDirectAccess &&
92 os <<
"Strong instance variable relinquished; object released";
94 os <<
"Object released";
103 os <<
"Object returned to caller as an owning reference (single "
104 "retain count transferred to caller)";
108 os <<
"Object returned to caller with a +0 retain count";
120static std::optional<unsigned>
126 for (
unsigned Idx = 0; Idx < (*CE)->getNumArgs(); Idx++)
127 if (
const MemRegion *MR = (*CE)->getArgSVal(Idx).getAsRegion())
128 if (
const auto *TR = dyn_cast<TypedValueRegion>(MR))
129 if (CurrSt->getSVal(MR, TR->getValueType()).getAsSymbol() == Sym)
136 if (
const auto *ME = dyn_cast<MemberExpr>(Callee)) {
137 if (ME->getMemberDecl()->getNameAsString() !=
"alloc")
139 const Expr *
This = ME->getBase()->IgnoreParenImpCasts();
140 if (
const auto *DRE = dyn_cast<DeclRefExpr>(
This)) {
145 if (
const auto *RD = dyn_cast<CXXRecordDecl>(VD->
getDeclContext()))
154 if (
const auto *CE = dyn_cast<CallExpr>(S))
164 llvm::raw_string_ostream &os) {
166 if (
const CallExpr *CE = dyn_cast<CallExpr>(S)) {
169 SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), SF);
174 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
176 if (
const auto *MD = dyn_cast<CXXMethodDecl>(CE->getCalleeDecl())) {
177 os <<
"Call to method '" << MD->getQualifiedNameAsString() <<
'\'';
181 os <<
"function call";
184 os <<
"Operator 'new'";
190 switch (
Call->getMessageKind()) {
203 std::optional<CallEventRef<>> CE = Mgr.
getCall(S, CurrSt, SF, {
nullptr, 0});
214 os <<
"a Core Foundation object of type '" << Sym->
getType() <<
"' with a ";
215 }
else if (CurrV.
getObjKind() == ObjKind::OS) {
218 }
else if (CurrV.
getObjKind() == ObjKind::Generalized) {
219 os <<
"an object of type '" << Sym->
getType() <<
"' with a ";
224 os <<
"an Objective-C object with a ";
232 os <<
"+1 retain count";
235 os <<
"+0 retain count";
239 os <<
" into an out parameter '";
240 const ParmVarDecl *PVD = (*CE)->parameters()[*Idx];
245 QualType RT = (*CE)->getResultType();
247 SVal RV = (*CE)->getReturnValue();
248 if (CurrSt->isNull(RV).isConstrainedTrue()) {
249 os <<
" (assuming the call returns zero)";
250 }
else if (CurrSt->isNonNull(RV).isConstrainedTrue()) {
251 os <<
" (assuming the call returns non-zero)";
271 void Profile(llvm::FoldingSetNodeID &ID)
const override {
290 LastBinding(LastBinding) {}
325static std::shared_ptr<PathDiagnosticEventPiece>
338 llvm::raw_string_ostream os(sbuf);
340 for (
unsigned I=0; I <
Call->getNumArgs() && I < Parameters.size(); ++I) {
343 if (!PVD->
hasAttr<OSConsumedAttr>())
350 if (!CountBeforeCall || !CountAtExit)
353 unsigned CountBefore = CountBeforeCall->
getCount();
354 unsigned CountAfter = CountAtExit->
getCount();
356 bool AsExpected = CountBefore > 0 && CountAfter == CountBefore - 1;
361 os <<
"' is marked as consuming, but the function did not consume "
362 <<
"the reference\n";
371 return std::make_shared<PathDiagnosticEventPiece>(L, sbuf);
375static std::shared_ptr<PathDiagnosticEventPiece>
394 llvm::raw_string_ostream os(s);
395 os <<
"Parameter '" << PVD->getDeclName() <<
"' starts at +";
397 os <<
"1, as it is marked as consuming";
402 return std::make_shared<PathDiagnosticEventPiece>(L, s);
432 const RefVal &CurrV = *CurrT;
438 llvm::raw_string_ostream os(sbuf);
441 os <<
"Object is now not exclusively owned";
443 return std::make_shared<PathDiagnosticEventPiece>(Pos, sbuf);
456 os <<
"NSArray literal is an object with a +0 retain count";
458 os <<
"NSDictionary literal is an object with a +0 retain count";
459 }
else if (
const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
461 os <<
"NSNumber literal is an object with a +0 retain count";
465 BoxClass =
Method->getClassInterface();
470 os << *BoxClass <<
" b";
475 os <<
"oxed expression produces an object with a +0 retain count";
478 os <<
"Object loaded from instance variable";
484 return std::make_shared<PathDiagnosticEventPiece>(Pos, sbuf);
489 bool DeallocSent =
false;
494 os <<
"Assuming dynamic cast returns null due to type mismatch";
502 if (
const CallExpr *CE = dyn_cast<CallExpr>(S)) {
505 for (
auto AI = CE->arg_begin(), AE = CE->arg_end(); AI != AE; ++AI) {
509 if (CurrSt->getSValAsScalarOrLoc(*AI, SF).getAsLocSymbol() !=
Sym)
516 if (
const Expr *R = ME->getInstanceReceiver()) {
517 if (CurrSt->getSValAsScalarOrLoc(R, SF).getAsLocSymbol() ==
Sym) {
533 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, sbuf);
538 if (
const Expr *Exp = dyn_cast_or_null<Expr>(Child))
539 if (CurrSt->getSValAsScalarOrLoc(Exp, SF).getAsLocSymbol() ==
Sym) {
540 P->addRange(Exp->getSourceRange());
548 if (
const auto *VR = dyn_cast_or_null<VarRegion>(MR))
549 return std::string(VR->getDecl()->getName());
564 : Sym(Sym),
Result(ToFill) {}
569 if (!SymV || SymV != Sym)
573 Result.emplace_back(R, Val);
584 VarBindingsCollector Collector{Sym,
Result};
585 while (
Result.empty() && Node) {
599struct AllocationInfo {
600 const ExplodedNode* N;
602 const StackFrame *InterestingMethodStackFrame;
603 AllocationInfo(
const ExplodedNode *InN,
const MemRegion *InR,
604 const StackFrame *InterestingMethodStackFrame)
606 InterestingMethodStackFrame(InterestingMethodStackFrame) {}
613 const ExplodedNode *AllocationNodeInCurrentOrParentContext = N;
619 const StackFrame *InitMethodStackFrame =
nullptr;
636 if (MR->getStackFrame() == LeakStackFrame)
650 if (NStackFrame == LeakStackFrame ||
652 AllocationNodeInCurrentOrParentContext = N;
656 if (!InitMethodStackFrame)
658 const Stmt *CE = CEP->getCallExpr();
659 if (
const auto *ME = dyn_cast_or_null<ObjCMessageExpr>(CE)) {
660 if (
const Expr *RecExpr = ME->getInstanceReceiver()) {
661 SVal RecV = St->getSVal(RecExpr, NStackFrame);
663 InitMethodStackFrame = CEP->getCalleeStackFrame();
673 const StackFrame *InterestingMethodStackFrame =
nullptr;
674 if (InitMethodStackFrame) {
679 InterestingMethodStackFrame = InitMethodStackFrame;
684 assert(N &&
"Could not find allocation node");
686 if (AllocationNodeInCurrentOrParentContext &&
687 AllocationNodeInCurrentOrParentContext->
getStackFrame() != LeakStackFrame)
688 FirstBinding =
nullptr;
690 return AllocationInfo(AllocationNodeInCurrentOrParentContext, FirstBinding,
691 InterestingMethodStackFrame);
714 llvm::raw_string_ostream os(sbuf);
716 os <<
"Object leaked: ";
718 std::optional<std::string> RegionDescription =
describeRegion(LastBinding);
719 if (RegionDescription) {
720 os <<
"object allocated and stored into '" << *RegionDescription <<
'\'';
733 os << (isa<ObjCMethodDecl>(D) ?
" is returned from a method "
734 :
" is returned from a function ");
736 if (D->
hasAttr<CFReturnsNotRetainedAttr>()) {
737 os <<
"that is annotated as CF_RETURNS_NOT_RETAINED";
738 }
else if (D->
hasAttr<NSReturnsNotRetainedAttr>()) {
739 os <<
"that is annotated as NS_RETURNS_NOT_RETAINED";
740 }
else if (D->
hasAttr<OSReturnsNotRetainedAttr>()) {
741 os <<
"that is annotated as OS_RETURNS_NOT_RETAINED";
745 os <<
"managed by Automatic Reference Counting";
747 os <<
"whose name ('" << MD->getSelector().getAsString()
748 <<
"') does not start with "
749 "'copy', 'mutableCopy', 'alloc' or 'new';"
750 " violating the naming convention rules"
751 " given in the Memory Management Guide for Cocoa";
757 os <<
"whose name ('" << *FD
758 <<
"') does not contain 'Copy' or 'Create'; violating the "
759 "naming convention rules given in the Memory Management Guide "
760 "for Core Foundation";
763 os <<
"whose name ('" << FuncName <<
"') starts with '"
764 << StringRef(FuncName).substr(0, 3) <<
"'";
769 os <<
" is not referenced later in this execution path and has a retain "
774 return std::make_shared<PathDiagnosticEventPiece>(L, sbuf);
779 bool IsReleaseUnowned)
802 const Decl *PDecl = Region->getDecl();
803 if (isa_and_nonnull<ParmVarDecl>(PDecl)) {
806 Location = ParamLocation;
826 AllocationInfo AllocI =
829 AllocNode = AllocI.N;
830 AllocFirstBinding = AllocI.R;
840 AllocFirstBinding =
nullptr;
846 Location = AllocLocation;
854void RefLeakReport::createDescription(CheckerContext &Ctx) {
858 os <<
"Potential leak of an object";
860 std::optional<std::string> RegionDescription =
862 if (RegionDescription) {
863 os <<
" stored into '" << *RegionDescription <<
'\'';
871void RefLeakReport::findBindingToReport(CheckerContext &Ctx,
872 ExplodedNode *Node) {
873 if (!AllocFirstBinding)
879 if (Node->
getState()->getSVal(AllocFirstBinding).getAsSymbol() ==
Sym) {
881 AllocBindingToReport = AllocFirstBinding;
904 if (!AllVarBindings.empty() &&
905 !llvm::is_contained(llvm::make_first_range(AllVarBindings),
906 AllocFirstBinding)) {
908 AllocBindingToReport = AllVarBindings[0].first;
920 AllocBindingToReport, *
this);
922 AllocBindingToReport = AllocFirstBinding;
931 deriveAllocLocation(Ctx);
932 findBindingToReport(Ctx, N);
934 if (!AllocFirstBinding)
935 deriveParamLocation(Ctx);
937 createDescription(Ctx);
Result
Implement __builtin_bit_cast and related operations.
static std::shared_ptr< PathDiagnosticEventPiece > annotateStartParameter(const ExplodedNode *N, SymbolRef Sym, const SourceManager &SM)
Annotate the parameter at the analysis entry point.
static std::string getPrettyTypeName(QualType QT)
If type represents a pointer to CXXRecordDecl, and is not a typedef, return the decl name.
static bool shouldGenerateNote(llvm::raw_string_ostream &os, const RefVal *PrevT, const RefVal &CurrV, bool DeallocSent)
Write information about the type state change to os, return whether the note should be generated.
static void generateDiagnosticsForCallLike(ProgramStateRef CurrSt, const StackFrame *SF, const RefVal &CurrV, SymbolRef &Sym, const Stmt *S, llvm::raw_string_ostream &os)
static std::optional< unsigned > findArgIdxOfSymbol(ProgramStateRef CurrSt, const StackFrame *SF, SymbolRef &Sym, std::optional< CallEventRef<> > CE)
Finds argument index of the out paramter in the call S corresponding to the symbol Sym.
static bool isNumericLiteralExpression(const Expr *E)
static std::shared_ptr< PathDiagnosticEventPiece > annotateConsumedSummaryMismatch(const ExplodedNode *N, CallExitBegin &CallExitLoc, const SourceManager &SM, CallEventManager &CEMgr)
Insert a diagnostic piece at function exit if a function parameter is annotated as "os_consumed",...
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
static std::string findAllocatedObjectName(const Stmt *S, QualType QT)
static AllocationInfo GetAllocationSite(ProgramStateManager &StateMgr, const ExplodedNode *N, SymbolRef Sym)
static std::optional< std::string > describeRegion(const MemRegion *MR)
static std::optional< std::string > findMetaClassAlloc(const Expr *Callee)
static const ExplodedNode * getCalleeNode(const ExplodedNode *Pred)
Find the first node with the parent stack frame.
static Bindings getAllVarBindingsForSymbol(ProgramStateManager &Manager, const ExplodedNode *Node, SymbolRef Sym)
a trap message and trap category.
const LangOptions & getLangOpts() const
const clang::PrintingPolicy & getPrintingPolicy() const
Represents a single basic block in a source-level CFG.
A boolean literal, per ([C++ lex.bool] Boolean literals).
Represents a point when we begin processing an inlined call.
Represents a point when we start the call exit sequence (for inlined call).
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
DeclContext * getDeclContext()
This represents one expression.
Represents a function declaration or definition.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::string getQualifiedNameAsString() const
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
ObjCBoxedExpr - used for generalized expression boxing.
Represents an ObjC class declaration.
An expression that sends a message to the given Objective-C object or class.
ObjCMethodDecl - Represents an instance or class method declaration.
Represents a pointer to an Objective C object.
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Represents a parameter to a function.
ProgramPoints can be "tagged" as representing points specific to a given analysis entity.
const ProgramPointTag * getTag() const
T castAs() const
Convert to the specified ProgramPoint type, asserting that this ProgramPoint is of the desired type.
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
This class handles loading and caching of source files into memory.
It represents a stack frame of the call stack.
bool isParentOf(const StackFrame *SF) const
const Expr * getCallSite() const
const Decl * getDecl() const
const StackFrame * getParent() const
It might return null.
Stmt - This represents one statement.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const T * getAs() const
Member-template getAs<specific type>'.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
ASTContext & getASTContext() const
ProgramStateManager & getStateManager() const
const SourceManager & getSourceManager() const
BugReporterVisitor()=default
static PathDiagnosticPieceRef getDefaultEndPath(const BugReporterContext &BRC, const ExplodedNode *N, const PathSensitiveBugReport &BR)
Generates the default final diagnostic piece.
Manages the lifetime of CallEvent objects.
CallEventRef getCaller(const StackFrame *CalleeSF, ProgramStateRef State)
Gets an outside caller given a callee context.
CallEventRef< ObjCMethodCall > getObjCMethodCall(const ObjCMessageExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
CallEventRef getCall(const Stmt *S, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Gets a call event for a function call, Objective-C method call, a 'new', or a 'delete' call.
const SourceManager & getSourceManager()
ProgramStateManager & getStateManager()
const StackFrame * getStackFrame() const
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
std::optional< T > getLocationAs() const &
ExplodedNode * getFirstPred()
const Decl & getCodeDecl() const
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind=bugreporter::TrackingKind::Thorough)
Marks a symbol as interesting.
PathSensitiveBugReport(const BugType &bt, const llvm::Twine &desc, const ExplodedNode *errorNode)
PathDiagnosticLocation UniqueingLocation
Reports with different uniqueing locations are considered to be different for the purposes of dedupli...
const ExplodedNode * getErrorNode() const
void addVisitor(std::unique_ptr< BugReporterVisitor > visitor)
Add custom or predefined bug report visitors to this report.
const Decl * UniqueingDecl
CallEventManager & getCallEventManager()
void iterBindings(ProgramStateRef state, StoreManager::BindingsHandler &F)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
SymbolRef getAsLocSymbol(bool IncludeBaseRegions=false) const
If this SVal is a location and wraps a symbol, return that SymbolRef.
const MemRegion * getRegion()
virtual const MemRegion * getOriginRegion() const
Find the region from which this symbol originates.
virtual QualType getType() const =0
void Profile(llvm::FoldingSetNodeID &ID) const override
PathDiagnosticPieceRef VisitNode(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Return a diagnostic piece which should be associated with the given node.
PathDiagnosticPieceRef getEndPath(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Provide custom definition for the final diagnostic piece on the path - the piece, which is displayed ...
RefCountReportVisitor(SymbolRef S, bool IRU)
RefCountReport(const RefCountBug &D, const LangOptions &LOpts, ExplodedNode *n, SymbolRef sym, bool isLeak=false, bool IsReleaseUnowned=false)
RefLeakReportVisitor(SymbolRef Sym, const MemRegion *LastBinding)
PathDiagnosticPieceRef getEndPath(const ExplodedNode *N, BugReporterContext &BRC, PathSensitiveBugReport &BR) override
Provide custom definition for the final diagnostic piece on the path - the piece, which is displayed ...
RefLeakReport(const RefCountBug &D, const LangOptions &LOpts, ExplodedNode *n, SymbolRef sym, CheckerContext &Ctx)
unsigned getCount() const
unsigned getCombinedCounts() const
IvarAccessHistory getIvarAccessHistory() const
Returns what the analyzer knows about direct accesses to a particular instance variable.
unsigned getAutoreleaseCount() const
bool hasSameState(const RefVal &X) const
ObjKind getObjKind() const
static const SimpleProgramPointTag & getCastFailTag()
static const SimpleProgramPointTag & getDeallocSentTag()
void trackStoredValue(SVal V, const MemRegion *R, PathSensitiveBugReport &Report, TrackingOptions Opts={}, const StackFrame *Origin=nullptr)
Track how the value got stored into the given region and where it came from.
bool isSynthesizedAccessor(const StackFrame *SF)
Returns true if this stack frame is for an Objective-C method that is a property getter or setter who...
const RefVal * getRefBinding(ProgramStateRef State, SymbolRef Sym)
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
ObjKind
Determines the object kind of a tracked object.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ CF
Indicates that the tracked object is a CF object.
@ ObjC
Indicates that the tracked object is an Objective-C object.
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
const void * Store
Store - This opaque type encapsulates an immutable mapping from locations to values.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
const FunctionProtoType * T
U cast(CodeGen::Address addr)