1//=======- RawPtrRefLambdaCapturesChecker.cpp --------------------*- C++ -*-==//
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#include "ASTUtils.h"
10#include "DiagOutputUtils.h"
11#include "PtrTypesSemantics.h"
12#include "RawPtrRefSafetyModel.h"
13#include "clang/AST/DynamicRecursiveASTVisitor.h"
14#include "clang/Basic/SourceManager.h"
15#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
16#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18#include "clang/StaticAnalyzer/Core/Checker.h"
19#include <optional>
20
21using namespace clang;
22using namespace ento;
23
24namespace {
25class RawPtrRefLambdaCapturesChecker
26 : public Checker<check::ASTDecl<TranslationUnitDecl>> {
27private:
28 BugType Bug;
29 mutable BugReporter *BR = nullptr;
30 TrivialFunctionAnalysis TFA;
31
32protected:
33 const std::unique_ptr<PtrRefSafetyModel> Model;
34
35public:
36 RawPtrRefLambdaCapturesChecker(const char *description,
37 std::unique_ptr<PtrRefSafetyModel> Model)
38 : Bug(this, description, "WebKit coding guidelines"),
39 Model(std::move(Model)) {}
40
41 std::optional<bool> isUnsafePtr(QualType QT) const {
42 return isUnsafePtrForStorage(Model: *Model, T: QT);
43 }
44 bool isPtrType(const std::string &Name) const {
45 return Model->isPtrType(Name);
46 }
47
48 void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
49 BugReporter &BRArg) const {
50 BR = &BRArg;
51
52 // The calls to checkAST* from AnalysisConsumer don't
53 // visit template instantiations or lambda classes. We
54 // want to visit those, so we make our own RecursiveASTVisitor.
55 struct LocalVisitor : DynamicRecursiveASTVisitor {
56 const RawPtrRefLambdaCapturesChecker *Checker;
57 llvm::DenseSet<const DeclRefExpr *> DeclRefExprsToIgnore;
58 llvm::DenseSet<const LambdaExpr *> LambdasToIgnore;
59 llvm::DenseSet<const ValueDecl *> ProtectedThisDecls;
60 llvm::DenseSet<const CallExpr *> CallToIgnore;
61 llvm::DenseSet<const CXXConstructExpr *> ConstructToIgnore;
62 llvm::DenseMap<const VarDecl *, SmallVector<const LambdaExpr *>>
63 LambdaOwnerMap;
64
65 QualType ClsType;
66
67 explicit LocalVisitor(const RawPtrRefLambdaCapturesChecker *Checker)
68 : Checker(Checker) {
69 assert(Checker);
70 ShouldVisitTemplateInstantiations = true;
71 ShouldVisitImplicitCode = false;
72 }
73
74 bool TraverseDecl(Decl *D) override {
75 // A template pattern is checked through its instantiations, which are
76 // traversed from the TemplateDecl itself. In the pattern the callee of
77 // a call may still be an unresolved overload set, so whether a lambda
78 // argument can escape isn't known, and a lambda in a pattern which is
79 // never instantiated is never used. Don't enter it at all.
80 if (D && !isa<TemplateDecl>(Val: D) && D->isTemplated())
81 return true;
82 return DynamicRecursiveASTVisitor::TraverseDecl(D);
83 }
84
85 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctor) override {
86 llvm::SaveAndRestore SavedDecl(ClsType);
87 ClsType = Ctor->getThisType();
88 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctor);
89 }
90
91 bool TraverseCXXDestructorDecl(CXXDestructorDecl *Dtor) override {
92 llvm::SaveAndRestore SavedDecl(ClsType);
93 ClsType = Dtor->getThisType();
94 return DynamicRecursiveASTVisitor::TraverseCXXDestructorDecl(D: Dtor);
95 }
96
97 bool TraverseCXXMethodDecl(CXXMethodDecl *CXXMD) override {
98 llvm::SaveAndRestore SavedDecl(ClsType);
99 // 'this' in the body of a lambda's call operator refers to the object
100 // of the enclosing method, so keep the class of that method. This
101 // matters for the instantiations of a generic lambda, which are
102 // traversed as declarations rather than as a body.
103 if (CXXMD->isInstance() && !CXXMD->getParent()->isLambda())
104 ClsType = CXXMD->getThisType();
105 return DynamicRecursiveASTVisitor::TraverseCXXMethodDecl(D: CXXMD);
106 }
107
108 bool TraverseObjCMethodDecl(ObjCMethodDecl *OCMD) override {
109 llvm::SaveAndRestore SavedDecl(ClsType);
110 if (OCMD && OCMD->isInstanceMethod()) {
111 if (auto *ImplParamDecl = OCMD->getSelfDecl())
112 ClsType = ImplParamDecl->getType();
113 }
114 return DynamicRecursiveASTVisitor::TraverseObjCMethodDecl(D: OCMD);
115 }
116
117 bool VisitTypedefDecl(TypedefDecl *TD) override {
118 if (auto *RTC = Checker->Model->retainTypeChecker())
119 RTC->visitTypedef(TD);
120 return true;
121 }
122
123 bool shouldCheckThis() {
124 // A pointer to the object itself is not a loan on its interior.
125 if (Checker->Model->checksForInteriorDestruction())
126 return false;
127 auto result =
128 !ClsType.isNull() ? Checker->isUnsafePtr(QT: ClsType) : std::nullopt;
129 return result && *result;
130 }
131
132 bool VisitLambdaExpr(LambdaExpr *L) override {
133 if (LambdasToIgnore.contains(V: L))
134 return true;
135 Checker->visitLambdaExpr(L, shouldCheckThis: shouldCheckThis() && !hasProtectedThis(L),
136 T: ClsType);
137 return true;
138 }
139
140 bool TraverseLambdaExpr(LambdaExpr *L) override {
141 auto *FTD = L->getLambdaClass()->getDependentLambdaCallOperator();
142 if (!FTD)
143 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(S: L);
144 // The body of a generic lambda is the pattern of its call operator,
145 // but it is reached from the LambdaExpr as a statement, so TraverseDecl
146 // never gets to skip it. Visit the lambda itself, traverse the capture
147 // initializers, which are evaluated in the enclosing scope, and then
148 // the call operator, of which the pattern is skipped like any other and
149 // the instantiations are traversed. The initializers are traversed as
150 // expressions because the variable of an init capture is declared in
151 // the pattern.
152 if (!VisitLambdaExpr(L))
153 return false;
154 for (unsigned I = 0, N = L->capture_size(); I != N; ++I) {
155 if (!(L->capture_begin() + I)->isExplicit())
156 continue;
157 if (auto *Init = L->capture_init_begin()[I];
158 Init && !TraverseStmt(S: Init))
159 return false;
160 }
161 return TraverseDecl(D: FTD);
162 }
163
164 bool VisitVarDecl(VarDecl *VD) override {
165 auto *Init = VD->getInit();
166 if (!Init)
167 return true;
168 if (auto *L = dyn_cast_or_null<LambdaExpr>(Val: Init->IgnoreParenCasts())) {
169 LambdasToIgnore.insert(V: L); // Evaluate lambdas in VisitDeclRefExpr.
170 return true;
171 }
172 if (!VD->hasLocalStorage())
173 return true;
174 if (auto *E = dyn_cast<ExprWithCleanups>(Val: Init))
175 Init = E->getSubExpr();
176 if (auto *E = dyn_cast<CXXBindTemporaryExpr>(Val: Init))
177 Init = E->getSubExpr();
178 if (auto *CE = dyn_cast<CallExpr>(Val: Init)) {
179 if (auto *Callee = CE->getDirectCallee()) {
180 auto FnName = safeGetName(ASTNode: Callee);
181 unsigned ArgCnt = CE->getNumArgs();
182 if (FnName == "makeScopeExit" && ArgCnt == 1) {
183 auto *Arg = CE->getArg(Arg: 0);
184 if (auto *E = dyn_cast<MaterializeTemporaryExpr>(Val: Arg))
185 Arg = E->getSubExpr();
186 if (auto *L = dyn_cast<LambdaExpr>(Val: Arg))
187 addLambdaOwner(VD, CE, L);
188 } else if (FnName == "makeVisitor") {
189 for (unsigned ArgIndex = 0; ArgIndex < ArgCnt; ++ArgIndex) {
190 auto *Arg = CE->getArg(Arg: ArgIndex);
191 if (auto *E = dyn_cast<MaterializeTemporaryExpr>(Val: Arg))
192 Arg = E->getSubExpr();
193 if (auto *L = dyn_cast<LambdaExpr>(Val: Arg))
194 addLambdaOwner(VD, CE, L);
195 }
196 }
197 }
198 } else if (auto *CE = dyn_cast<CXXConstructExpr>(Val: Init)) {
199 if (auto *Ctor = CE->getConstructor()) {
200 if (auto *Cls = Ctor->getParent()) {
201 auto FnName = safeGetName(ASTNode: Cls);
202 unsigned ArgCnt = CE->getNumArgs();
203 if (FnName == "ScopeExit" && ArgCnt == 1) {
204 auto *Arg = CE->getArg(Arg: 0);
205 if (auto *E = dyn_cast<MaterializeTemporaryExpr>(Val: Arg))
206 Arg = E->getSubExpr();
207 if (auto *L = dyn_cast<LambdaExpr>(Val: Arg))
208 addLambdaOwner(VD, CE, L);
209 }
210 }
211 }
212 }
213 return true;
214 }
215
216 void addLambdaOwner(VarDecl *VD, CallExpr *CE, LambdaExpr *L) {
217 auto result = LambdaOwnerMap.insert(
218 KV: std::make_pair(x&: VD, y: SmallVector<const LambdaExpr *>{L}));
219 if (!result.second)
220 result.first->second.push_back(Elt: L);
221 CallToIgnore.insert(V: CE);
222 LambdasToIgnore.insert(V: L);
223 }
224
225 void addLambdaOwner(VarDecl *VD, CXXConstructExpr *CE, LambdaExpr *L) {
226 auto result = LambdaOwnerMap.insert(
227 KV: std::make_pair(x&: VD, y: SmallVector<const LambdaExpr *>{L}));
228 if (!result.second)
229 result.first->second.push_back(Elt: L);
230 ConstructToIgnore.insert(V: CE);
231 LambdasToIgnore.insert(V: L);
232 }
233
234 bool VisitExplicitCastExpr(ExplicitCastExpr *CE) override {
235 // Discarding a variable with (void) doesn't let a lambda escape.
236 if (CE->getCastKind() != CK_ToVoid)
237 return true;
238 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CE->getSubExpr()->IgnoreParens()))
239 DeclRefExprsToIgnore.insert(V: DRE);
240 return true;
241 }
242
243 bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
244 if (DeclRefExprsToIgnore.contains(V: DRE))
245 return true;
246 auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getDecl());
247 if (!VD)
248 return true;
249 if (auto It = LambdaOwnerMap.find(Val: VD); It != LambdaOwnerMap.end()) {
250 for (auto *L : It->second) {
251 Checker->visitLambdaExpr(
252 L, shouldCheckThis: shouldCheckThis() && !hasProtectedThis(L), T: ClsType);
253 }
254 return true;
255 }
256 auto *Init = VD->getInit();
257 if (!Init)
258 return true;
259 auto *L = dyn_cast_or_null<LambdaExpr>(Val: Init->IgnoreParenCasts());
260 if (!L)
261 return true;
262 LambdasToIgnore.insert(V: L);
263 Checker->visitLambdaExpr(L, shouldCheckThis: shouldCheckThis() && !hasProtectedThis(L),
264 T: ClsType);
265 return true;
266 }
267
268 bool shouldTreatAllArgAsNoEscape(FunctionDecl *FDecl) {
269 std::string PreviousName = safeGetName(ASTNode: FDecl);
270 for (auto *Decl = FDecl->getParent(); Decl; Decl = Decl->getParent()) {
271 if (!isa<NamespaceDecl>(Val: Decl) && !isa<CXXRecordDecl>(Val: Decl))
272 return false;
273 if (auto *NS = dyn_cast<NamespaceDecl>(Val: Decl); NS && NS->isInline())
274 continue;
275 auto Name = safeGetName(ASTNode: Decl);
276 // WTF::switchOn(T, F... f) is a variadic template function and
277 // couldn't be annotated with NOESCAPE. We hard code it here to
278 // workaround that.
279 if (Name == "WTF" && PreviousName == "switchOn")
280 return true;
281 if (Name == "std") {
282 // Treat every argument of functions in std::ranges as noescape.
283 if (PreviousName == "ranges")
284 return true;
285 // Treat every argument of call_once as noescape even though only
286 // the second argument is lambda since we can't add annotation to
287 // a std function.
288 if (PreviousName == "call_once")
289 return true;
290 }
291 PreviousName = Name;
292 }
293 return false;
294 }
295
296 bool VisitCXXConstructExpr(CXXConstructExpr *CE) override {
297 if (ConstructToIgnore.contains(V: CE))
298 return true;
299 if (auto *Callee = CE->getConstructor()) {
300 unsigned ArgIndex = 0;
301 for (auto *Param : Callee->parameters()) {
302 if (ArgIndex >= CE->getNumArgs())
303 return true;
304 auto *Arg = CE->getArg(Arg: ArgIndex)->IgnoreParenCasts();
305 if (auto *L = findLambdaInArg(E: Arg)) {
306 LambdasToIgnore.insert(V: L);
307 if (!Param->hasAttr<NoEscapeAttr>())
308 Checker->visitLambdaExpr(
309 L, shouldCheckThis: shouldCheckThis() && !hasProtectedThis(L), T: ClsType);
310 }
311 ++ArgIndex;
312 }
313 }
314 return true;
315 }
316
317 bool VisitCallExpr(CallExpr *CE) override {
318 if (CallToIgnore.contains(V: CE))
319 return true;
320 checkCalleeLambda(CE);
321 if (auto *Callee = CE->getDirectCallee()) {
322 if (isVisitFunction(CallExpr: CE, FnDecl: Callee))
323 return true;
324 checkParameters(CE, Callee);
325 } else if (auto *CalleeE = CE->getCallee()) {
326 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CalleeE->IgnoreParenCasts())) {
327 if (auto *Callee = dyn_cast_or_null<FunctionDecl>(Val: DRE->getDecl()))
328 checkParameters(CE, Callee);
329 }
330 }
331 return true;
332 }
333
334 bool isVisitFunction(CallExpr *CallExpr, FunctionDecl *FnDecl) {
335 bool IsVisitFn = safeGetName(ASTNode: FnDecl) == "visit";
336 if (!IsVisitFn)
337 return false;
338 bool ArgCnt = CallExpr->getNumArgs();
339 if (!ArgCnt)
340 return false;
341 auto *Ns = FnDecl->getParent();
342 if (!Ns)
343 return false;
344 auto NsName = safeGetName(ASTNode: Ns);
345 if (NsName != "WTF" && NsName != "std")
346 return false;
347 auto *Arg = CallExpr->getArg(Arg: 0);
348 if (!Arg)
349 return false;
350 auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenCasts());
351 if (!DRE)
352 return false;
353 auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl());
354 if (!VD)
355 return false;
356 if (!LambdaOwnerMap.contains(Val: VD))
357 return false;
358 DeclRefExprsToIgnore.insert(V: DRE);
359 return true;
360 }
361
362 void checkParameters(CallExpr *CE, FunctionDecl *Callee) {
363 unsigned ArgIndex = isa<CXXOperatorCallExpr>(Val: CE);
364 bool TreatAllArgsAsNoEscape = shouldTreatAllArgAsNoEscape(FDecl: Callee);
365 for (auto *Param : Callee->parameters()) {
366 if (ArgIndex >= CE->getNumArgs())
367 return;
368 auto *Arg = CE->getArg(Arg: ArgIndex)->IgnoreParenCasts();
369 if (auto *L = findLambdaInArg(E: Arg)) {
370 LambdasToIgnore.insert(V: L);
371 if (!Param->hasAttr<NoEscapeAttr>() && !TreatAllArgsAsNoEscape)
372 Checker->visitLambdaExpr(
373 L, shouldCheckThis: shouldCheckThis() && !hasProtectedThis(L), T: ClsType);
374 }
375 ++ArgIndex;
376 }
377 }
378
379 LambdaExpr *findLambdaInArg(Expr *E) {
380 if (auto *Lambda = dyn_cast_or_null<LambdaExpr>(Val: E))
381 return Lambda;
382 // A temporary of a type with a trivial destructor, such as
383 // WTF::ScopedLambda, isn't wrapped in a CXXBindTemporaryExpr.
384 if (auto *TempExpr = dyn_cast_or_null<CXXBindTemporaryExpr>(Val: E)) {
385 E = TempExpr->getSubExpr()->IgnoreParenCasts();
386 if (!E)
387 return nullptr;
388 if (auto *Lambda = dyn_cast<LambdaExpr>(Val: E))
389 return Lambda;
390 }
391 auto *CE = dyn_cast_or_null<CXXConstructExpr>(Val: E);
392 if (!CE || !CE->getNumArgs())
393 return nullptr;
394 auto *CtorArg = CE->getArg(Arg: 0)->IgnoreParenCasts();
395 if (!CtorArg)
396 return nullptr;
397 auto *InnerCE = dyn_cast_or_null<CXXConstructExpr>(Val: CtorArg);
398 if (InnerCE && InnerCE->getNumArgs())
399 CtorArg = InnerCE->getArg(Arg: 0)->IgnoreParenCasts();
400 auto updateIgnoreList = [&] {
401 ConstructToIgnore.insert(V: CE);
402 if (InnerCE)
403 ConstructToIgnore.insert(V: InnerCE);
404 };
405 if (auto *Lambda = dyn_cast<LambdaExpr>(Val: CtorArg)) {
406 updateIgnoreList();
407 return Lambda;
408 }
409 if (auto *TempExpr = dyn_cast<CXXBindTemporaryExpr>(Val: CtorArg)) {
410 E = TempExpr->getSubExpr()->IgnoreParenCasts();
411 if (auto *Lambda = dyn_cast<LambdaExpr>(Val: E)) {
412 updateIgnoreList();
413 return Lambda;
414 }
415 }
416 auto *DRE = dyn_cast<DeclRefExpr>(Val: CtorArg);
417 if (!DRE)
418 return nullptr;
419 auto *VD = dyn_cast_or_null<VarDecl>(Val: DRE->getDecl());
420 if (!VD)
421 return nullptr;
422 auto *Init = VD->getInit();
423 if (!Init)
424 return nullptr;
425 if (auto *Lambda = dyn_cast<LambdaExpr>(Val: Init)) {
426 DeclRefExprsToIgnore.insert(V: DRE);
427 updateIgnoreList();
428 return Lambda;
429 }
430 return nullptr;
431 }
432
433 void checkCalleeLambda(CallExpr *CE) {
434 auto *Callee = CE->getCallee();
435 if (!Callee)
436 return;
437 Callee = Callee->IgnoreParenCasts();
438 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Callee)) {
439 Callee = MTE->getSubExpr();
440 if (!Callee)
441 return;
442 Callee = Callee->IgnoreParenCasts();
443 }
444 if (auto *L = dyn_cast<LambdaExpr>(Val: Callee)) {
445 LambdasToIgnore.insert(V: L); // Calling a lambda upon creation is safe.
446 return;
447 }
448 auto *DRE = dyn_cast<DeclRefExpr>(Val: Callee->IgnoreParenCasts());
449 if (!DRE)
450 return;
451 auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl());
452 if (!MD || CE->getNumArgs() < 1)
453 return;
454 auto *Arg = CE->getArg(Arg: 0)->IgnoreParenCasts();
455 if (auto *L = dyn_cast_or_null<LambdaExpr>(Val: Arg)) {
456 LambdasToIgnore.insert(V: L); // Calling a lambda upon creation is safe.
457 return;
458 }
459 auto *ArgRef = dyn_cast<DeclRefExpr>(Val: Arg);
460 if (!ArgRef)
461 return;
462 auto *VD = dyn_cast_or_null<VarDecl>(Val: ArgRef->getDecl());
463 if (!VD)
464 return;
465 auto *Init = VD->getInit();
466 if (!Init)
467 return;
468 auto *L = dyn_cast_or_null<LambdaExpr>(Val: Init->IgnoreParenCasts());
469 if (!L)
470 return;
471 DeclRefExprsToIgnore.insert(V: ArgRef);
472 LambdasToIgnore.insert(V: L);
473 }
474
475 bool hasProtectedThis(const LambdaExpr *L) {
476 for (const LambdaCapture &OtherCapture : L->captures()) {
477 if (!OtherCapture.capturesVariable())
478 continue;
479 if (auto *ValueDecl = OtherCapture.getCapturedVar()) {
480 if (declProtectsThis(ValueDecl)) {
481 ProtectedThisDecls.insert(V: ValueDecl);
482 return true;
483 }
484 }
485 }
486 return false;
487 }
488
489 bool declProtectsThis(const ValueDecl *ValueDecl) const {
490 auto *VD = dyn_cast<VarDecl>(Val: ValueDecl);
491 if (!VD)
492 return false;
493 auto *Init = VD->getInit();
494 if (!Init)
495 return false;
496 const Expr *Arg = Init->IgnoreParenCasts();
497 do {
498 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Arg))
499 Arg = BTE->getSubExpr()->IgnoreParenCasts();
500 if (auto *CE = dyn_cast<CXXConstructExpr>(Val: Arg)) {
501 auto *Ctor = CE->getConstructor();
502 if (!Ctor)
503 return false;
504 auto ArgClsTy = dyn_cast_or_null<CXXRecordDecl>(Val: Ctor->getParent());
505 if (Checker->Model->isSafePtr(Record: ArgClsTy) && CE->getNumArgs()) {
506 Arg = CE->getArg(Arg: 0)->IgnoreParenCasts();
507 continue;
508 }
509 if (auto *Type = ClsType.getTypePtrOrNull()) {
510 if (auto *CXXR = Type->getPointeeCXXRecordDecl()) {
511 if (CXXR == Ctor->getParent() && Ctor->isMoveConstructor() &&
512 CE->getNumArgs() == 1) {
513 Arg = CE->getArg(Arg: 0)->IgnoreParenCasts();
514 continue;
515 }
516 }
517 }
518 return false;
519 }
520 if (auto *CE = dyn_cast<CallExpr>(Val: Arg)) {
521 if (auto *Callee = CE->getDirectCallee()) {
522 if ((isStdOrWTFMove(F: Callee) || isCtorOfSafePtr(F: Callee)) &&
523 CE->getNumArgs() == 1) {
524 Arg = CE->getArg(Arg: 0)->IgnoreParenCasts();
525 continue;
526 }
527 }
528 }
529 if (auto *OpCE = dyn_cast<CXXOperatorCallExpr>(Val: Arg)) {
530 auto OpCode = OpCE->getOperator();
531 if (OpCode == OO_Star || OpCode == OO_Amp) {
532 auto *Callee = OpCE->getDirectCallee();
533 if (!Callee)
534 return false;
535 auto clsName = safeGetName(ASTNode: Callee->getParent());
536 if (!Checker->isPtrType(Name: clsName) || !OpCE->getNumArgs())
537 return false;
538 Arg = OpCE->getArg(Arg: 0)->IgnoreParenCasts();
539 continue;
540 }
541 }
542 if (auto *UO = dyn_cast<UnaryOperator>(Val: Arg)) {
543 auto OpCode = UO->getOpcode();
544 if (OpCode == UO_Deref || OpCode == UO_AddrOf) {
545 Arg = UO->getSubExpr()->IgnoreParenCasts();
546 continue;
547 }
548 }
549 break;
550 } while (Arg);
551 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: Arg)) {
552 auto *Decl = DRE->getDecl();
553 if (auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(Val: Decl)) {
554 auto kind = ImplicitParam->getParameterKind();
555 return kind == ImplicitParamKind::ObjCSelf ||
556 kind == ImplicitParamKind::CXXThis;
557 }
558 return ProtectedThisDecls.contains(V: Decl);
559 }
560 return isa<CXXThisExpr>(Val: Arg);
561 }
562 };
563
564 LocalVisitor visitor(this);
565 if (auto *RTC = Model->retainTypeChecker())
566 RTC->visitTranslationUnitDecl(TUD);
567 visitor.TraverseDecl(D: const_cast<TranslationUnitDecl *>(TUD));
568 }
569
570 void visitLambdaExpr(const LambdaExpr *L, bool shouldCheckThis,
571 const QualType T,
572 bool ignoreParamVarDecl = false) const {
573 if (BR->getSourceManager().isInSystemHeader(Loc: L->getBeginLoc()))
574 return;
575 // FIXME: This check is unsound. Destruction can happen in three places,
576 // and a capture is only safe when all three are trivial: the lambda's
577 // body, the callee that receives it, and the scope that creates it.
578 if (TFA.isTrivial(S: L->getBody()))
579 return;
580 for (auto [C, CaptureInit] :
581 llvm::zip_equal(t: L->captures(), u: L->capture_inits())) {
582 if (C.capturesVariable()) {
583 ValueDecl *CapturedVar = C.getCapturedVar();
584 if (ignoreParamVarDecl && isa<ParmVarDecl>(Val: CapturedVar))
585 continue;
586 if (auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(Val: CapturedVar)) {
587 auto kind = ImplicitParam->getParameterKind();
588 if ((kind == ImplicitParamKind::ObjCSelf ||
589 kind == ImplicitParamKind::CXXThis) &&
590 !shouldCheckThis)
591 continue;
592 }
593 QualType CapturedVarQualType = CapturedVar->getType();
594 auto IsUncountedPtr = isUnsafePtr(QT: CapturedVarQualType);
595 if (C.getCaptureKind() == LCK_ByCopy &&
596 CapturedVarQualType->isReferenceType())
597 continue;
598 if (!IsUncountedPtr || !*IsUncountedPtr)
599 continue;
600 const Expr *Origin = nullptr;
601 if (Model->checksForInteriorDestruction()) {
602 if (!CaptureInit)
603 continue;
604 if (isCaptureOriginSafeToEscape(CaptureInit, Origin,
605 SinkType: CapturedVarQualType))
606 continue;
607 }
608 reportBug(Capture: C, CapturedVar, T: CapturedVarQualType, L, Origin);
609 } else if (C.capturesThis() && shouldCheckThis) {
610 if (ignoreParamVarDecl)
611 continue;
612 reportBugOnThisPtr(Capture: C, T);
613 }
614 }
615 }
616
617 bool isCaptureOriginSafeToEscape(const Expr *CaptureInit, const Expr *&Origin,
618 QualType SinkType) const {
619 return tryToFindPtrOrigin(
620 E: CaptureInit, /*StopAtFirstRefCountedObj=*/false,
621 FollowLifetimeBound: Model->checksForInteriorDestruction(),
622
623 // A smart pointer, even if safe, has shorter lifetime than an
624 // escaping lambda, so we do not treat it as a guarantee of safety.
625 /*isSafePtr=*/[](const clang::CXXRecordDecl *) { return false; },
626 /*isSafePtrType=*/[](const clang::QualType) { return false; },
627
628 // A global has longer lifetime, and can be safe.
629 /*isSafeGlobalDecl=*/
630 [&](const clang::Decl *D) {
631 return Model->isSafeDecl(D, BR->getSourceManager());
632 },
633
634 callback: [&](const clang::Expr *CaptureOrigin, bool IsSafe,
635 bool /*OriginDependsOnFullExpressionTemporary*/,
636 bool PtrIsLifetimeBoundToOrigin) {
637 if (!CaptureOrigin)
638 return true;
639 if (isa<CXXThisExpr>(Val: CaptureOrigin))
640 return true;
641 if (IsSafe)
642 return true;
643 if (Model->isSafeExpr(Origin: CaptureOrigin, PtrIsLifetimeBoundToOrigin,
644 SinkType, /*SinkMayEscape=*/true))
645 return true;
646 if (!Origin)
647 Origin = CaptureOrigin;
648 return false;
649 });
650 }
651
652 void reportBug(const LambdaCapture &Capture, ValueDecl *CapturedVar,
653 const QualType T, const LambdaExpr *L,
654 const Expr *Origin) const {
655 assert(CapturedVar);
656
657 auto Location = Capture.getLocation();
658 if (isa<ImplicitParamDecl>(Val: CapturedVar) && !Location.isValid())
659 Location = L->getBeginLoc();
660
661 SmallString<100> Buf;
662 llvm::raw_svector_ostream Os(Buf);
663
664 if (Capture.isExplicit())
665 Os << "Captured ";
666 else
667 Os << "Implicitly captured ";
668 Os << "variable ";
669 printQuotedQualifiedName(Os, D: CapturedVar);
670
671 bool IsUnsafePtr = CapturedVar->getType() == T;
672 if (IsUnsafePtr)
673 Os << " is a ";
674 else
675 Os << " contains a ";
676 if (Model->checksForInteriorDestruction())
677 Model->describeHazard(Os, Origin, SinkType: T);
678 else
679 printPointer(Os, T: T.getTypePtrOrNull());
680
681 PathDiagnosticLocation BSLoc(Location, BR->getSourceManager());
682 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
683 BR->emitReport(R: std::move(Report));
684 }
685
686 void reportBugOnThisPtr(const LambdaCapture &Capture,
687 const QualType T) const {
688 SmallString<100> Buf;
689 llvm::raw_svector_ostream Os(Buf);
690
691 if (Capture.isExplicit()) {
692 Os << "Captured ";
693 } else {
694 Os << "Implicitly captured ";
695 }
696
697 Os << "variable 'this' is a raw pointer to " << Model->typeName();
698 if (auto *RD = T->getPointeeCXXRecordDecl()) {
699 Os << " ";
700 printQuotedQualifiedName(Os, D: RD);
701 }
702
703 PathDiagnosticLocation BSLoc(Capture.getLocation(), BR->getSourceManager());
704 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
705 BR->emitReport(R: std::move(Report));
706 }
707
708 void printPointer(llvm::raw_svector_ostream &Os, const Type *T) const {
709 if (Model->retainTypeChecker()) {
710 // An OS object may be spelled as an id qualified by an OS_-prefixed
711 // protocol; print that protocol name.
712 if (auto *ObjCPtr = dyn_cast<ObjCObjectPointerType>(Val: T)) {
713 for (ObjCProtocolDecl *P : ObjCPtr->quals()) {
714 if (const auto *II = P->getIdentifier()) {
715 auto Name = II->getName();
716 if (Name.starts_with(Prefix: "OS_")) {
717 Os << Model->typeName() << " ";
718 printQuotedQualifiedName(Os, D: P);
719 return;
720 }
721 }
722 }
723 }
724 // Retain/OS types are frequently spelled through a typedef (e.g.
725 // CFXXXRef); print the typedef name rather than desugaring.
726 if (!isa<ObjCObjectPointerType>(Val: T) && T->getAs<TypedefType>()) {
727 auto Typedef = T->getAs<TypedefType>();
728 assert(Typedef);
729 Os << Model->typeName() << " ";
730 printQuotedQualifiedName(Os, D: Typedef->getDecl());
731 return;
732 }
733 }
734 T = T->getUnqualifiedDesugaredType();
735 bool IsPtr = isa<PointerType>(Val: T) || isa<ObjCObjectPointerType>(Val: T);
736 Os << (IsPtr ? "raw pointer" : "raw reference") << " to ";
737 Os << Model->typeName();
738
739 if (auto *RD = T->getPointeeType()->getAsRecordDecl()) {
740 Os << " ";
741 printQuotedQualifiedName(Os, D: RD);
742 } else if (auto *ObjCDecl = getObjCDeclFromObjCPtr(TypePtr: T)) {
743 Os << " ";
744 printQuotedQualifiedName(Os, D: ObjCDecl);
745 }
746 }
747};
748
749class UncountedLambdaCapturesChecker : public RawPtrRefLambdaCapturesChecker {
750public:
751 UncountedLambdaCapturesChecker()
752 : RawPtrRefLambdaCapturesChecker("Lambda capture of uncounted variable",
753 makeRefPtrSafetyModel()) {}
754};
755
756class UncheckedLambdaCapturesChecker : public RawPtrRefLambdaCapturesChecker {
757public:
758 UncheckedLambdaCapturesChecker()
759 : RawPtrRefLambdaCapturesChecker("Lambda capture of unchecked variable",
760 makeCheckedPtrSafetyModel()) {}
761};
762
763class UnretainedLambdaCapturesChecker : public RawPtrRefLambdaCapturesChecker {
764public:
765 UnretainedLambdaCapturesChecker()
766 : RawPtrRefLambdaCapturesChecker("Lambda capture of unretained "
767 "variables",
768 makeRetainPtrSafetyModel()) {}
769};
770
771class UnborrowedLambdaCapturesChecker : public RawPtrRefLambdaCapturesChecker {
772public:
773 UnborrowedLambdaCapturesChecker()
774 : RawPtrRefLambdaCapturesChecker("Lambda capture of a loan on a "
775 "CanBorrow object",
776 makeBorrowSafetyModel()) {}
777};
778
779} // namespace
780
781void ento::registerUncountedLambdaCapturesChecker(CheckerManager &Mgr) {
782 Mgr.registerChecker<UncountedLambdaCapturesChecker>();
783}
784
785bool ento::shouldRegisterUncountedLambdaCapturesChecker(
786 const CheckerManager &mgr) {
787 return true;
788}
789
790void ento::registerUncheckedLambdaCapturesChecker(CheckerManager &Mgr) {
791 Mgr.registerChecker<UncheckedLambdaCapturesChecker>();
792}
793
794bool ento::shouldRegisterUncheckedLambdaCapturesChecker(
795 const CheckerManager &mgr) {
796 return true;
797}
798
799void ento::registerUnretainedLambdaCapturesChecker(CheckerManager &Mgr) {
800 Mgr.registerChecker<UnretainedLambdaCapturesChecker>();
801}
802
803bool ento::shouldRegisterUnretainedLambdaCapturesChecker(
804 const CheckerManager &mgr) {
805 return true;
806}
807
808void ento::registerUnborrowedLambdaCapturesChecker(CheckerManager &Mgr) {
809 Mgr.registerChecker<UnborrowedLambdaCapturesChecker>();
810}
811
812bool ento::shouldRegisterUnborrowedLambdaCapturesChecker(
813 const CheckerManager &mgr) {
814 return true;
815}
816