Skip to content

Commit 474490d

Browse files
committed
[webkit.UncountedLambdaCapturesChecker] Ignore trivial functions and [[clang::noescape]].
This PR makes webkit.UncountedLambdaCapturesChecker ignore trivial functions as well as the one being passed to an argument with [[clang::noescape]] attribute. This dramatically reduces the false positive rate for this checker. To do this, this PR replaces VisitLambdaExpr in favor of checking lambdas via VisitDeclRefExpr and VisitCallExpr. The idea is that if a lambda is defined but never called or stored somewhere, then capturing whatever variable in such a lambda is harmless. VisitCallExpr explicitly looks for direct invocation of lambdas and registers its DeclRefExpr to be ignored in VisitDeclRefExpr. If a lambda is being passed to a function, it checks whether its argument is annotated with [[clang::noescape]]. If it's not annotated such, it checks captures for their safety. Because WTF::switchOn could not be annotated with [[clang::noescape]] as function type parameters are variadic template function so we hard-code this function into the checker. In order to check whether "this" pointer is ref-counted type or not, we override TraverseDecl and record the most recent method's declaration. In addition, this PR fixes a bug in isUnsafePtr that it was erroneously checking whether std::nullopt was returned by isUncounted and isUnchecked as opposed to the actual boolean value. Finally, this PR also converts the accompanying test to use -verify and adds a bunch of tests.
1 parent 1897bf6 commit 474490d

File tree

5 files changed

+286
-35
lines changed

5 files changed

+286
-35
lines changed

clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,13 @@ std::optional<bool> isUncountedPtr(const QualType T) {
203203
std::optional<bool> isUnsafePtr(const QualType T) {
204204
if (T->isPointerType() || T->isReferenceType()) {
205205
if (auto *CXXRD = T->getPointeeCXXRecordDecl()) {
206-
return isUncounted(CXXRD) || isUnchecked(CXXRD);
206+
auto isUncountedPtr = isUncounted(CXXRD);
207+
auto isUncheckedPtr = isUnchecked(CXXRD);
208+
if (isUncountedPtr && isUncheckedPtr)
209+
return *isUncountedPtr || *isUncheckedPtr;
210+
if (isUncountedPtr)
211+
return *isUncountedPtr;
212+
return isUncheckedPtr;
207213
}
208214
}
209215
return false;

clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,10 @@ std::optional<bool> isUncounted(const clang::CXXRecordDecl* Class);
6363
/// class, false if not, std::nullopt if inconclusive.
6464
std::optional<bool> isUncountedPtr(const clang::QualType T);
6565

66+
/// \returns true if \p T is either a raw pointer or reference to an uncounted
67+
/// or unchecked class, false if not, std::nullopt if inconclusive.
68+
std::optional<bool> isUnsafePtr(const QualType T);
69+
6670
/// \returns true if \p T is a RefPtr, Ref, CheckedPtr, CheckedRef, or its
6771
/// variant, false if not.
6872
bool isSafePtrType(const clang::QualType T);

clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedLambdaCapturesChecker.cpp

Lines changed: 120 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
//
77
//===----------------------------------------------------------------------===//
88

9+
#include "ASTUtils.h"
910
#include "DiagOutputUtils.h"
1011
#include "PtrTypesSemantics.h"
1112
#include "clang/AST/CXXInheritance.h"
@@ -26,6 +27,7 @@ class UncountedLambdaCapturesChecker
2627
BugType Bug{this, "Lambda capture of uncounted variable",
2728
"WebKit coding guidelines"};
2829
mutable BugReporter *BR = nullptr;
30+
TrivialFunctionAnalysis TFA;
2931

3032
public:
3133
void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
@@ -37,6 +39,11 @@ class UncountedLambdaCapturesChecker
3739
// want to visit those, so we make our own RecursiveASTVisitor.
3840
struct LocalVisitor : public RecursiveASTVisitor<LocalVisitor> {
3941
const UncountedLambdaCapturesChecker *Checker;
42+
llvm::DenseSet<const DeclRefExpr *> DeclRefExprsToIgnore;
43+
QualType ClsType;
44+
45+
using Base = RecursiveASTVisitor<LocalVisitor>;
46+
4047
explicit LocalVisitor(const UncountedLambdaCapturesChecker *Checker)
4148
: Checker(Checker) {
4249
assert(Checker);
@@ -45,32 +52,117 @@ class UncountedLambdaCapturesChecker
4552
bool shouldVisitTemplateInstantiations() const { return true; }
4653
bool shouldVisitImplicitCode() const { return false; }
4754

48-
bool VisitLambdaExpr(LambdaExpr *L) {
49-
Checker->visitLambdaExpr(L);
55+
bool TraverseDecl(Decl *D) {
56+
if (auto *CXXMD = dyn_cast<CXXMethodDecl>(D)) {
57+
llvm::SaveAndRestore SavedDecl(ClsType);
58+
ClsType = CXXMD->getThisType();
59+
return Base::TraverseDecl(D);
60+
}
61+
return Base::TraverseDecl(D);
62+
}
63+
64+
bool shouldCheckThis() {
65+
auto result = !ClsType.isNull() ? isUnsafePtr(ClsType) : std::nullopt;
66+
return result && *result;
67+
}
68+
69+
bool VisitDeclRefExpr(DeclRefExpr *DRE) {
70+
if (DeclRefExprsToIgnore.contains(DRE))
71+
return true;
72+
auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl());
73+
if (!VD)
74+
return true;
75+
auto *Init = VD->getInit()->IgnoreParenCasts();
76+
auto *L = dyn_cast_or_null<LambdaExpr>(Init);
77+
if (!L)
78+
return true;
79+
Checker->visitLambdaExpr(L, shouldCheckThis());
80+
return true;
81+
}
82+
83+
// WTF::switchOn(T, F... f) is a variadic template function and couldn't
84+
// be annotated with NOESCAPE. We hard code it here to workaround that.
85+
bool shouldTreatAllArgAsNoEscape(FunctionDecl *Decl) {
86+
auto *NsDecl = Decl->getParent();
87+
if (!NsDecl || !isa<NamespaceDecl>(NsDecl))
88+
return false;
89+
return safeGetName(NsDecl) == "WTF" && safeGetName(Decl) == "switchOn";
90+
}
91+
92+
bool VisitCallExpr(CallExpr *CE) {
93+
checkCalleeLambda(CE);
94+
if (auto *Callee = CE->getDirectCallee()) {
95+
bool TreatAllArgsAsNoEscape = shouldTreatAllArgAsNoEscape(Callee);
96+
unsigned ArgIndex = 0;
97+
for (auto *Param : Callee->parameters()) {
98+
if (ArgIndex >= CE->getNumArgs())
99+
break;
100+
auto *Arg = CE->getArg(ArgIndex)->IgnoreParenCasts();
101+
if (!Param->hasAttr<NoEscapeAttr>() && !TreatAllArgsAsNoEscape) {
102+
if (auto *L = dyn_cast_or_null<LambdaExpr>(Arg)) {
103+
Checker->visitLambdaExpr(L, shouldCheckThis());
104+
}
105+
}
106+
++ArgIndex;
107+
}
108+
}
50109
return true;
51110
}
111+
112+
void checkCalleeLambda(CallExpr *CE) {
113+
auto *Callee = CE->getCallee();
114+
if (!Callee)
115+
return;
116+
auto *DRE = dyn_cast<DeclRefExpr>(Callee->IgnoreParenCasts());
117+
if (!DRE)
118+
return;
119+
auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl());
120+
if (!MD || CE->getNumArgs() != 1)
121+
return;
122+
auto *Arg = CE->getArg(0)->IgnoreParenCasts();
123+
auto *ArgRef = dyn_cast<DeclRefExpr>(Arg);
124+
if (!ArgRef)
125+
return;
126+
auto *VD = dyn_cast_or_null<VarDecl>(ArgRef->getDecl());
127+
if (!VD)
128+
return;
129+
auto *Init = VD->getInit()->IgnoreParenCasts();
130+
auto *L = dyn_cast_or_null<LambdaExpr>(Init);
131+
if (!L)
132+
return;
133+
DeclRefExprsToIgnore.insert(ArgRef);
134+
Checker->visitLambdaExpr(L, shouldCheckThis(),
135+
/* ignoreParamVarDecl */ true);
136+
}
52137
};
53138

54139
LocalVisitor visitor(this);
55140
visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
56141
}
57142

58-
void visitLambdaExpr(LambdaExpr *L) const {
143+
void visitLambdaExpr(LambdaExpr *L, bool shouldCheckThis,
144+
bool ignoreParamVarDecl = false) const {
145+
if (TFA.isTrivial(L->getBody()))
146+
return;
59147
for (const LambdaCapture &C : L->captures()) {
60148
if (C.capturesVariable()) {
61149
ValueDecl *CapturedVar = C.getCapturedVar();
150+
if (ignoreParamVarDecl && isa<ParmVarDecl>(CapturedVar))
151+
continue;
62152
QualType CapturedVarQualType = CapturedVar->getType();
63-
if (auto *CapturedVarType = CapturedVarQualType.getTypePtrOrNull()) {
64-
auto IsUncountedPtr = isUncountedPtr(CapturedVarQualType);
65-
if (IsUncountedPtr && *IsUncountedPtr)
66-
reportBug(C, CapturedVar, CapturedVarType);
67-
}
153+
auto IsUncountedPtr = isUnsafePtr(CapturedVar->getType());
154+
if (IsUncountedPtr && *IsUncountedPtr)
155+
reportBug(C, CapturedVar, CapturedVarQualType);
156+
} else if (C.capturesThis() && shouldCheckThis) {
157+
if (ignoreParamVarDecl) // this is always a parameter to this function.
158+
continue;
159+
reportBugOnThisPtr(C);
68160
}
69161
}
70162
}
71163

72164
void reportBug(const LambdaCapture &Capture, ValueDecl *CapturedVar,
73-
const Type *T) const {
165+
const QualType T) const {
74166
assert(CapturedVar);
75167

76168
SmallString<100> Buf;
@@ -89,7 +181,25 @@ class UncountedLambdaCapturesChecker
89181
}
90182

91183
printQuotedQualifiedName(Os, Capture.getCapturedVar());
92-
Os << " to uncounted type is unsafe.";
184+
Os << " to ref-counted / CheckedPtr capable type is unsafe.";
185+
186+
PathDiagnosticLocation BSLoc(Capture.getLocation(), BR->getSourceManager());
187+
auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
188+
BR->emitReport(std::move(Report));
189+
}
190+
191+
void reportBugOnThisPtr(const LambdaCapture &Capture) const {
192+
SmallString<100> Buf;
193+
llvm::raw_svector_ostream Os(Buf);
194+
195+
if (Capture.isExplicit()) {
196+
Os << "Captured ";
197+
} else {
198+
Os << "Implicitly captured ";
199+
}
200+
201+
Os << "raw-pointer 'this' to ref-counted / CheckedPtr capable type is "
202+
"unsafe.";
93203

94204
PathDiagnosticLocation BSLoc(Capture.getLocation(), BR->getSourceManager());
95205
auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);

clang/test/Analysis/Checkers/WebKit/mock-types.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ struct RefCountable {
135135
void ref() {}
136136
void deref() {}
137137
void method();
138+
void constMethod() const;
138139
int trivial() { return 123; }
140+
RefCountable* next();
139141
};
140142

141143
template <typename T> T *downcast(T *t) { return t; }

0 commit comments

Comments
 (0)