24class RawPtrRefLambdaCapturesChecker
25 :
public Checker<check::ASTDecl<TranslationUnitDecl>> {
28 mutable BugReporter *BR =
nullptr;
29 TrivialFunctionAnalysis TFA;
32 const std::unique_ptr<PtrRefSafetyModel> Model;
35 RawPtrRefLambdaCapturesChecker(
const char *description,
36 std::unique_ptr<PtrRefSafetyModel> Model)
37 : Bug(this, description,
"WebKit coding guidelines"),
38 Model(std::move(Model)) {}
40 std::optional<bool> isUnsafePtr(QualType QT)
const {
43 bool isPtrType(
const std::string &Name)
const {
44 return Model->isPtrType(Name);
47 void checkASTDecl(
const TranslationUnitDecl *TUD, AnalysisManager &MGR,
48 BugReporter &BRArg)
const {
55 const RawPtrRefLambdaCapturesChecker *Checker;
56 llvm::DenseSet<const DeclRefExpr *> DeclRefExprsToIgnore;
57 llvm::DenseSet<const LambdaExpr *> LambdasToIgnore;
58 llvm::DenseSet<const ValueDecl *> ProtectedThisDecls;
59 llvm::DenseSet<const CallExpr *> CallToIgnore;
60 llvm::DenseSet<const CXXConstructExpr *> ConstructToIgnore;
61 llvm::DenseMap<const VarDecl *, SmallVector<const LambdaExpr *>>
66 explicit LocalVisitor(
const RawPtrRefLambdaCapturesChecker *Checker)
69 ShouldVisitTemplateInstantiations =
true;
70 ShouldVisitImplicitCode =
false;
73 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctor)
override {
74 llvm::SaveAndRestore SavedDecl(ClsType);
76 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(Ctor);
79 bool TraverseCXXDestructorDecl(CXXDestructorDecl *Dtor)
override {
80 llvm::SaveAndRestore SavedDecl(ClsType);
81 ClsType =
Dtor->getThisType();
82 return DynamicRecursiveASTVisitor::TraverseCXXDestructorDecl(Dtor);
85 bool TraverseCXXMethodDecl(CXXMethodDecl *CXXMD)
override {
86 llvm::SaveAndRestore SavedDecl(ClsType);
89 return DynamicRecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD);
92 bool TraverseObjCMethodDecl(ObjCMethodDecl *OCMD)
override {
93 llvm::SaveAndRestore SavedDecl(ClsType);
96 ClsType = ImplParamDecl->getType();
98 return DynamicRecursiveASTVisitor::TraverseObjCMethodDecl(OCMD);
101 bool VisitTypedefDecl(TypedefDecl *TD)
override {
102 if (
auto *RTC = Checker->Model->retainTypeChecker())
103 RTC->visitTypedef(TD);
107 bool shouldCheckThis() {
109 !ClsType.
isNull() ? Checker->isUnsafePtr(ClsType) : std::nullopt;
110 return result && *result;
113 bool VisitLambdaExpr(
LambdaExpr *L)
override {
114 if (LambdasToIgnore.contains(L))
116 Checker->visitLambdaExpr(L, shouldCheckThis() && !hasProtectedThis(L),
121 bool VisitVarDecl(VarDecl *VD)
override {
125 if (
auto *L = dyn_cast_or_null<LambdaExpr>(
Init->IgnoreParenCasts())) {
126 LambdasToIgnore.insert(L);
131 if (
auto *E = dyn_cast<ExprWithCleanups>(
Init))
132 Init = E->getSubExpr();
133 if (
auto *E = dyn_cast<CXXBindTemporaryExpr>(
Init))
134 Init = E->getSubExpr();
135 if (
auto *CE = dyn_cast<CallExpr>(
Init)) {
136 if (
auto *Callee = CE->getDirectCallee()) {
138 unsigned ArgCnt = CE->getNumArgs();
139 if (FnName ==
"makeScopeExit" && ArgCnt == 1) {
140 auto *Arg = CE->getArg(0);
141 if (
auto *E = dyn_cast<MaterializeTemporaryExpr>(Arg))
142 Arg = E->getSubExpr();
143 if (
auto *L = dyn_cast<LambdaExpr>(Arg))
144 addLambdaOwner(VD, CE, L);
145 }
else if (FnName ==
"makeVisitor") {
146 for (
unsigned ArgIndex = 0; ArgIndex < ArgCnt; ++ArgIndex) {
147 auto *Arg = CE->getArg(ArgIndex);
148 if (
auto *E = dyn_cast<MaterializeTemporaryExpr>(Arg))
149 Arg = E->getSubExpr();
150 if (
auto *L = dyn_cast<LambdaExpr>(Arg))
151 addLambdaOwner(VD, CE, L);
155 }
else if (
auto *CE = dyn_cast<CXXConstructExpr>(
Init)) {
156 if (
auto *Ctor = CE->getConstructor()) {
159 unsigned ArgCnt = CE->getNumArgs();
160 if (FnName ==
"ScopeExit" && ArgCnt == 1) {
161 auto *Arg = CE->getArg(0);
162 if (
auto *E = dyn_cast<MaterializeTemporaryExpr>(Arg))
163 Arg = E->getSubExpr();
164 if (
auto *L = dyn_cast<LambdaExpr>(Arg))
165 addLambdaOwner(VD, CE, L);
173 void addLambdaOwner(VarDecl *VD, CallExpr *CE,
LambdaExpr *L) {
174 auto result = LambdaOwnerMap.insert(
175 std::make_pair(VD, SmallVector<const LambdaExpr *>{L}));
177 result.first->second.push_back(L);
178 CallToIgnore.insert(CE);
179 LambdasToIgnore.insert(L);
182 void addLambdaOwner(VarDecl *VD, CXXConstructExpr *CE,
LambdaExpr *L) {
183 auto result = LambdaOwnerMap.insert(
184 std::make_pair(VD, SmallVector<const LambdaExpr *>{L}));
186 result.first->second.push_back(L);
187 ConstructToIgnore.insert(CE);
188 LambdasToIgnore.insert(L);
191 bool VisitDeclRefExpr(DeclRefExpr *DRE)
override {
192 if (DeclRefExprsToIgnore.contains(DRE))
194 auto *VD = dyn_cast_or_null<VarDecl>(DRE->
getDecl());
197 if (
auto It = LambdaOwnerMap.find(VD); It != LambdaOwnerMap.end()) {
198 for (
auto *L : It->second) {
199 Checker->visitLambdaExpr(
200 L, shouldCheckThis() && !hasProtectedThis(L), ClsType);
207 auto *L = dyn_cast_or_null<LambdaExpr>(
Init->IgnoreParenCasts());
210 LambdasToIgnore.insert(L);
211 Checker->visitLambdaExpr(L, shouldCheckThis() && !hasProtectedThis(L),
216 bool shouldTreatAllArgAsNoEscape(FunctionDecl *FDecl) {
218 for (
auto *Decl = FDecl->
getParent(); Decl; Decl =
Decl->getParent()) {
225 if (Name ==
"WTF" && PreviousName ==
"switchOn")
228 if (Name ==
"std" && PreviousName ==
"ranges")
235 bool VisitCXXConstructExpr(CXXConstructExpr *CE)
override {
236 if (ConstructToIgnore.contains(CE))
239 unsigned ArgIndex = 0;
240 for (
auto *Param :
Callee->parameters()) {
244 if (
auto *L = findLambdaInArg(Arg)) {
245 LambdasToIgnore.insert(L);
246 if (!Param->hasAttr<NoEscapeAttr>())
247 Checker->visitLambdaExpr(
248 L, shouldCheckThis() && !hasProtectedThis(L), ClsType);
256 bool VisitCallExpr(CallExpr *CE)
override {
257 if (CallToIgnore.contains(CE))
259 checkCalleeLambda(CE);
261 if (isVisitFunction(CE, Callee))
263 checkParameters(CE, Callee);
264 }
else if (
auto *CalleeE = CE->
getCallee()) {
265 if (
auto *DRE = dyn_cast<DeclRefExpr>(CalleeE->IgnoreParenCasts())) {
266 if (
auto *Callee = dyn_cast_or_null<FunctionDecl>(DRE->
getDecl()))
267 checkParameters(CE, Callee);
273 bool isVisitFunction(CallExpr *CallExpr, FunctionDecl *FnDecl) {
284 if (NsName !=
"WTF" && NsName !=
"std")
286 auto *Arg = CallExpr->
getArg(0);
289 auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenCasts());
292 auto *VD = dyn_cast<VarDecl>(DRE->
getDecl());
295 if (!LambdaOwnerMap.contains(VD))
297 DeclRefExprsToIgnore.insert(DRE);
301 void checkParameters(CallExpr *CE, FunctionDecl *Callee) {
303 bool TreatAllArgsAsNoEscape = shouldTreatAllArgAsNoEscape(Callee);
304 for (
auto *Param :
Callee->parameters()) {
308 if (
auto *L = findLambdaInArg(Arg)) {
309 LambdasToIgnore.insert(L);
310 if (!Param->hasAttr<NoEscapeAttr>() && !TreatAllArgsAsNoEscape)
311 Checker->visitLambdaExpr(
312 L, shouldCheckThis() && !hasProtectedThis(L), ClsType);
319 if (
auto *Lambda = dyn_cast_or_null<LambdaExpr>(E))
321 auto *TempExpr = dyn_cast_or_null<CXXBindTemporaryExpr>(E);
327 if (
auto *Lambda = dyn_cast<LambdaExpr>(E))
329 auto *CE = dyn_cast_or_null<CXXConstructExpr>(E);
335 auto *InnerCE = dyn_cast_or_null<CXXConstructExpr>(CtorArg);
336 if (InnerCE && InnerCE->getNumArgs())
337 CtorArg = InnerCE->getArg(0)->IgnoreParenCasts();
338 auto updateIgnoreList = [&] {
339 ConstructToIgnore.insert(CE);
341 ConstructToIgnore.insert(InnerCE);
343 if (
auto *Lambda = dyn_cast<LambdaExpr>(CtorArg)) {
347 if (
auto *TempExpr = dyn_cast<CXXBindTemporaryExpr>(CtorArg)) {
349 if (
auto *Lambda = dyn_cast<LambdaExpr>(E)) {
354 auto *DRE = dyn_cast<DeclRefExpr>(CtorArg);
357 auto *VD = dyn_cast_or_null<VarDecl>(DRE->
getDecl());
363 if (
auto *Lambda = dyn_cast<LambdaExpr>(
Init)) {
364 DeclRefExprsToIgnore.insert(DRE);
371 void checkCalleeLambda(CallExpr *CE) {
376 if (
auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Callee)) {
377 Callee = MTE->getSubExpr();
382 if (
auto *L = dyn_cast<LambdaExpr>(Callee)) {
383 LambdasToIgnore.insert(L);
386 auto *DRE = dyn_cast<DeclRefExpr>(
Callee->IgnoreParenCasts());
389 auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->
getDecl());
393 if (
auto *L = dyn_cast_or_null<LambdaExpr>(Arg)) {
394 LambdasToIgnore.insert(L);
397 auto *ArgRef = dyn_cast<DeclRefExpr>(Arg);
400 auto *VD = dyn_cast_or_null<VarDecl>(ArgRef->getDecl());
406 auto *L = dyn_cast_or_null<LambdaExpr>(
Init->IgnoreParenCasts());
409 DeclRefExprsToIgnore.insert(ArgRef);
410 LambdasToIgnore.insert(L);
414 for (
const LambdaCapture &OtherCapture : L->
captures()) {
415 if (!OtherCapture.capturesVariable())
417 if (
auto *ValueDecl = OtherCapture.getCapturedVar()) {
418 if (declProtectsThis(ValueDecl)) {
419 ProtectedThisDecls.insert(ValueDecl);
427 bool declProtectsThis(
const ValueDecl *ValueDecl)
const {
428 auto *VD = dyn_cast<VarDecl>(ValueDecl);
436 if (
auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Arg))
438 if (
auto *CE = dyn_cast<CXXConstructExpr>(Arg)) {
439 auto *Ctor = CE->getConstructor();
443 if (Checker->isPtrType(clsName) && CE->
getNumArgs()) {
448 if (
auto *CXXR =
Type->getPointeeCXXRecordDecl()) {
458 if (
auto *CE = dyn_cast<CallExpr>(Arg)) {
467 if (
auto *OpCE = dyn_cast<CXXOperatorCallExpr>(Arg)) {
468 auto OpCode = OpCE->getOperator();
469 if (OpCode == OO_Star || OpCode == OO_Amp) {
470 auto *
Callee = OpCE->getDirectCallee();
474 if (!Checker->isPtrType(clsName) || !OpCE->getNumArgs())
480 if (
auto *UO = dyn_cast<UnaryOperator>(Arg)) {
481 auto OpCode = UO->getOpcode();
482 if (OpCode == UO_Deref || OpCode == UO_AddrOf) {
489 if (
auto *DRE = dyn_cast<DeclRefExpr>(Arg)) {
491 if (
auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(Decl)) {
492 auto kind = ImplicitParam->getParameterKind();
493 return kind == ImplicitParamKind::ObjCSelf ||
494 kind == ImplicitParamKind::CXXThis;
496 return ProtectedThisDecls.contains(Decl);
502 LocalVisitor visitor(
this);
503 if (
auto *RTC = Model->retainTypeChecker())
504 RTC->visitTranslationUnitDecl(TUD);
505 visitor.TraverseDecl(
const_cast<TranslationUnitDecl *
>(TUD));
508 void visitLambdaExpr(
const LambdaExpr *L,
bool shouldCheckThis,
510 bool ignoreParamVarDecl =
false)
const {
511 if (TFA.isTrivial(L->
getBody()))
513 for (
const LambdaCapture &
C : L->
captures()) {
514 if (
C.capturesVariable()) {
515 ValueDecl *CapturedVar =
C.getCapturedVar();
518 if (
auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(CapturedVar)) {
519 auto kind = ImplicitParam->getParameterKind();
520 if ((
kind == ImplicitParamKind::ObjCSelf ||
521 kind == ImplicitParamKind::CXXThis) &&
525 QualType CapturedVarQualType = CapturedVar->
getType();
526 auto IsUncountedPtr = isUnsafePtr(CapturedVar->
getType());
530 if (IsUncountedPtr && *IsUncountedPtr)
531 reportBug(
C, CapturedVar, CapturedVarQualType, L);
532 }
else if (
C.capturesThis() && shouldCheckThis) {
533 if (ignoreParamVarDecl)
535 reportBugOnThisPtr(
C,
T);
540 void reportBug(
const LambdaCapture &
Capture, ValueDecl *CapturedVar,
544 auto Location =
Capture.getLocation();
548 SmallString<100> Buf;
549 llvm::raw_svector_ostream Os(Buf);
554 Os <<
"Implicitly captured ";
558 bool IsUnsafePtr = CapturedVar->
getType() ==
T;
562 Os <<
" contains a ";
563 auto *CapturedType =
T.getTypePtrOrNull();
564 printPointer(Os, CapturedType);
566 PathDiagnosticLocation BSLoc(Location, BR->getSourceManager());
567 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
568 BR->emitReport(std::move(
Report));
571 void reportBugOnThisPtr(
const LambdaCapture &
Capture,
572 const QualType
T)
const {
573 SmallString<100> Buf;
574 llvm::raw_svector_ostream Os(Buf);
579 Os <<
"Implicitly captured ";
582 Os <<
"variable 'this' is a raw pointer to " << Model->typeName();
588 PathDiagnosticLocation BSLoc(
Capture.getLocation(), BR->getSourceManager());
589 auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
590 BR->emitReport(std::move(
Report));
593 void printPointer(llvm::raw_svector_ostream &Os,
const Type *
T)
const {
594 if (Model->retainTypeChecker()) {
597 if (
auto *ObjCPtr = dyn_cast<ObjCObjectPointerType>(
T)) {
598 for (ObjCProtocolDecl *P : ObjCPtr->quals()) {
599 if (
const auto *II = P->getIdentifier()) {
600 auto Name = II->getName();
601 if (Name.starts_with(
"OS_")) {
602 Os << Model->typeName() <<
" ";
614 Os << Model->typeName() <<
" ";
621 Os << (IsPtr ?
"raw pointer" :
"raw reference") <<
" to ";
622 Os << Model->typeName();
634class UncountedLambdaCapturesChecker :
public RawPtrRefLambdaCapturesChecker {
636 UncountedLambdaCapturesChecker()
637 : RawPtrRefLambdaCapturesChecker(
"Lambda capture of uncounted variable",
641class UncheckedLambdaCapturesChecker :
public RawPtrRefLambdaCapturesChecker {
643 UncheckedLambdaCapturesChecker()
644 : RawPtrRefLambdaCapturesChecker(
"Lambda capture of unchecked variable",
648class UnretainedLambdaCapturesChecker :
public RawPtrRefLambdaCapturesChecker {
650 UnretainedLambdaCapturesChecker()
651 : RawPtrRefLambdaCapturesChecker(
"Lambda capture of unretained "
658void ento::registerUncountedLambdaCapturesChecker(
CheckerManager &Mgr) {
662bool ento::shouldRegisterUncountedLambdaCapturesChecker(
667void ento::registerUncheckedLambdaCapturesChecker(
CheckerManager &Mgr) {
671bool ento::shouldRegisterUncheckedLambdaCapturesChecker(
676void ento::registerUnretainedLambdaCapturesChecker(
CheckerManager &Mgr) {
680bool ento::shouldRegisterUnretainedLambdaCapturesChecker(
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
Expr * getArg(unsigned Arg)
Return the specified argument.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
bool isMoveConstructor(unsigned &TypeQuals) const
Determine whether this constructor is a move constructor (C++11 [class.copy]p3), which can be used to...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
QualType getThisType() const
Return the type of the this pointer.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Stmt * getBody() const
Retrieve the body of the lambda.
SourceLocation getBeginLoc() const LLVM_READONLY
capture_range captures() const
Retrieve this lambda's captures.
ImplicitParamDecl * getSelfDecl() const
bool isInstanceMethod() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtrOrNull() const
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isReferenceType() const
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
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>'.
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
const Expr * getInit() const
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
constexpr bool isPtrType(PrimType T)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
bool isCtorOfSafePtr(const clang::FunctionDecl *F)
bool isa(CodeGen::Address addr)
std::unique_ptr< PtrRefSafetyModel > makeCheckedPtrSafetyModel()
@ LCK_ByCopy
Capturing by copy (a.k.a., by value)
void printQuotedQualifiedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
std::optional< bool > isUnsafePtrForStorage(const PtrRefSafetyModel &Model, QualType T, bool IgnoreARC=false)
Applies the memory-management exemptions that hold for a variable, member, or lambda capture (but not...
const FunctionProtoType * T
@ Type
The name was classified as a type.
std::string safeGetName(const T *ASTNode)
ObjCInterfaceDecl * getObjCDeclFromObjCPtr(const Type *TypePtr)
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
bool isStdOrWTFMove(const clang::FunctionDecl *F)
std::unique_ptr< PtrRefSafetyModel > makeRefPtrSafetyModel()
std::unique_ptr< PtrRefSafetyModel > makeRetainPtrSafetyModel()