1//=======- UncountedLocalVarsChecker.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/CXXInheritance.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DynamicRecursiveASTVisitor.h"
17#include "clang/AST/ParentMapContext.h"
18#include "clang/AST/StmtObjC.h"
19#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/Basic/SourceLocation.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
23#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/Checker.h"
26#include <optional>
27
28using namespace clang;
29using namespace ento;
30
31namespace {
32
33// FIXME: should be defined by anotations in the future
34bool isRefcountedStringsHack(const VarDecl *V) {
35 assert(V);
36 auto safeClass = [](const std::string &className) {
37 return className == "String" || className == "AtomString" ||
38 className == "UniquedString" || className == "Identifier";
39 };
40 QualType QT = V->getType();
41 auto *T = QT.getTypePtr();
42 if (auto *CXXRD = T->getAsCXXRecordDecl()) {
43 if (safeClass(safeGetName(ASTNode: CXXRD)))
44 return true;
45 }
46 if (T->isPointerType() || T->isReferenceType()) {
47 if (auto *CXXRD = T->getPointeeCXXRecordDecl()) {
48 if (safeClass(safeGetName(ASTNode: CXXRD)))
49 return true;
50 }
51 }
52 return false;
53}
54
55struct GuardianVisitor : DynamicRecursiveASTVisitor {
56 const VarDecl *Guardian{nullptr};
57 bool GuardianIsRawPtrOrRef{false};
58
59 explicit GuardianVisitor(const VarDecl *Guardian,
60 bool GuardianIsRawPtrOrRef = false)
61 : Guardian(Guardian), GuardianIsRawPtrOrRef(GuardianIsRawPtrOrRef) {
62 assert(Guardian);
63 }
64
65 bool VisitBinaryOperator(BinaryOperator *BO) override {
66 if (BO->isAssignmentOp()) {
67 if (auto *VarRef = dyn_cast<DeclRefExpr>(Val: BO->getLHS())) {
68 if (VarRef->getDecl() == Guardian)
69 return false;
70 }
71 }
72 return true;
73 }
74
75 bool VisitCXXConstructExpr(CXXConstructExpr *CE) override {
76 auto *Ctor = CE->getConstructor();
77 if (!Ctor)
78 return false;
79 unsigned ArgIndex = 0;
80 for (auto *Arg : CE->arguments()) {
81 QualType ParamType;
82 if (ArgIndex < Ctor->getNumParams())
83 ParamType = Ctor->getParamDecl(i: ArgIndex)->getType();
84 if (mutatesGuardian(Arg, ParamType))
85 return false;
86 ArgIndex++;
87 }
88 return true;
89 }
90
91 bool VisitCallExpr(CallExpr *CE) override {
92 auto *Callee = CE->getDirectCallee();
93 if (!Callee)
94 return !indirectCallMutatesGuardian(CE);
95 if (isPtrConversion(F: Callee))
96 return true;
97 if (auto *Method = dyn_cast<CXXMethodDecl>(Val: Callee)) {
98 if (isGetterOfSafePtr(Method).value_or(u: false))
99 return true;
100 }
101 // For a member operator call, the first argument is the implicit object.
102 auto *OperatorMethod = dyn_cast<CXXMethodDecl>(Val: Callee);
103 if (!isa<CXXOperatorCallExpr>(Val: CE) || !OperatorMethod ||
104 !OperatorMethod->isImplicitObjectMemberFunction())
105 OperatorMethod = nullptr;
106 unsigned ArgIndex = 0;
107 unsigned ArgOffset = OperatorMethod ? 1 : 0;
108 for (auto *Arg : CE->arguments()) {
109 QualType ParamType;
110 if (ArgIndex >= ArgOffset) {
111 unsigned ParmIndex = ArgIndex - ArgOffset;
112 if (ParmIndex < Callee->getNumParams())
113 ParamType = Callee->getParamDecl(i: ParmIndex)->getType();
114 } else if (OperatorMethod->isConst()) {
115 ArgIndex++;
116 continue;
117 }
118 if (mutatesGuardian(Arg, ParamType))
119 return false;
120 ArgIndex++;
121 }
122 return true;
123 }
124
125 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *MCE) override {
126 if (GuardianIsRawPtrOrRef)
127 return true;
128 auto *Method = MCE->getMethodDecl();
129 auto ObjType = MCE->getObjectType();
130 if (ObjType.isConstQualified())
131 return true;
132 // A call through a pointer to member function has no method declaration.
133 if (!Method) {
134 if (auto *Prototype = getCalleePrototype(CE: MCE);
135 Prototype && Prototype->getMethodQuals().hasConst())
136 return true;
137 }
138 auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
139 if (auto *UO = dyn_cast<UnaryOperator>(Val: ThisArg);
140 UO && UO->getOpcode() == UO_AddrOf)
141 ThisArg = UO->getSubExpr()->IgnoreParenCasts();
142 if (auto *VarRef = dyn_cast<DeclRefExpr>(Val: ThisArg)) {
143 if (!isa_and_nonnull<CXXConversionDecl>(Val: Method) &&
144 VarRef->getDecl() == Guardian)
145 return false;
146 }
147 return true;
148 }
149
150private:
151 // Returns the prototype of the callee of a call through a function pointer,
152 // a block, or a pointer to member function.
153 static const FunctionProtoType *getCalleePrototype(const CallExpr *CE) {
154 auto *CalleeExpr = CE->getCallee();
155 if (!CalleeExpr)
156 return nullptr;
157 CalleeExpr = CalleeExpr->IgnoreParens();
158 QualType CalleeType = CalleeExpr->getType();
159 if (auto *BO = dyn_cast<BinaryOperator>(Val: CalleeExpr); BO && BO->isPtrMemOp())
160 CalleeType = BO->getRHS()->getType();
161 if (QualType PointeeType = CalleeType->getPointeeType();
162 !PointeeType.isNull())
163 CalleeType = PointeeType;
164 return CalleeType->getAs<FunctionProtoType>();
165 }
166
167 // A call through a function pointer, a block, or a pointer to member function
168 // can only mutate the guardian if the guardian is passed to it, or if the
169 // guardian is a __block variable that a block could have captured by
170 // reference.
171 bool indirectCallMutatesGuardian(const CallExpr *CE) {
172 if (Guardian->hasAttr<BlocksAttr>())
173 return true;
174 auto *Prototype = getCalleePrototype(CE);
175 unsigned ArgIndex = 0;
176 for (auto *Arg : CE->arguments()) {
177 QualType ParamType;
178 if (Prototype && ArgIndex < Prototype->getNumParams())
179 ParamType = Prototype->getParamType(i: ArgIndex);
180 if (mutatesGuardian(Arg, ParamType))
181 return true;
182 ArgIndex++;
183 }
184 return false;
185 }
186
187 bool mutatesGuardian(const Expr *Arg, QualType ParamType) {
188 Arg = Arg->IgnoreParenCasts();
189 auto ArgType = !ParamType.isNull() ? ParamType : Arg->getType();
190 bool IsAddressOf = false;
191 if (auto *UO = dyn_cast<UnaryOperator>(Val: Arg);
192 UO && UO->getOpcode() == UO_AddrOf) {
193 Arg = UO->getSubExpr()->IgnoreParenCasts();
194 IsAddressOf = true;
195 }
196 auto *VarRef = dyn_cast<DeclRefExpr>(Val: Arg);
197 if (!VarRef || VarRef->getDecl() != Guardian)
198 return false;
199 if (GuardianIsRawPtrOrRef && !Guardian->getType()->isAnyPointerType())
200 return false;
201 if (IsAddressOf) {
202 if (!ArgType->isPointerType())
203 return false;
204 return !ArgType->getPointeeType().isConstQualified();
205 }
206 if (GuardianIsRawPtrOrRef) {
207 if (!ArgType->isReferenceType())
208 return false;
209 return !ArgType.getNonReferenceType().isConstQualified();
210 }
211 return !ArgType.getNonReferenceType().isConstQualified();
212 }
213};
214
215bool isGuardedScopeEmbeddedInGuardianScope(const VarDecl *Guarded,
216 const VarDecl *MaybeGuardian) {
217 assert(Guarded);
218 assert(MaybeGuardian);
219
220 if (!MaybeGuardian->isLocalVarDecl())
221 return false;
222
223 const CompoundStmt *guardiansClosestCompStmtAncestor = nullptr;
224
225 ASTContext &ctx = MaybeGuardian->getASTContext();
226
227 for (DynTypedNodeList guardianAncestors = ctx.getParents(Node: *MaybeGuardian);
228 !guardianAncestors.empty();
229 guardianAncestors = ctx.getParents(
230 Node: *guardianAncestors
231 .begin()) // FIXME - should we handle all of the parents?
232 ) {
233 for (auto &guardianAncestor : guardianAncestors) {
234 if (auto *CStmtParentAncestor = guardianAncestor.get<CompoundStmt>()) {
235 guardiansClosestCompStmtAncestor = CStmtParentAncestor;
236 break;
237 }
238 }
239 if (guardiansClosestCompStmtAncestor)
240 break;
241 }
242
243 if (!guardiansClosestCompStmtAncestor)
244 return false;
245
246 // We need to skip the first CompoundStmt to avoid situation when guardian is
247 // defined in the same scope as guarded variable.
248 const CompoundStmt *FirstCompondStmt = nullptr;
249 for (DynTypedNodeList guardedVarAncestors = ctx.getParents(Node: *Guarded);
250 !guardedVarAncestors.empty();
251 guardedVarAncestors = ctx.getParents(
252 Node: *guardedVarAncestors
253 .begin()) // FIXME - should we handle all of the parents?
254 ) {
255 for (auto &guardedVarAncestor : guardedVarAncestors) {
256 if (auto *CStmtAncestor = guardedVarAncestor.get<CompoundStmt>()) {
257 if (!FirstCompondStmt) {
258 FirstCompondStmt = CStmtAncestor;
259 continue;
260 }
261 if (CStmtAncestor == guardiansClosestCompStmtAncestor) {
262 GuardianVisitor guardianVisitor(MaybeGuardian);
263 auto *GuardedScope = const_cast<CompoundStmt *>(FirstCompondStmt);
264 return guardianVisitor.TraverseCompoundStmt(S: GuardedScope);
265 }
266 }
267 }
268 }
269
270 return false;
271}
272
273// Returns the fast enumeration statement whose element is declared as V as in
274// "for (T *V in Collection)".
275static const ObjCForCollectionStmt *
276findObjCForCollectionStmtOfElement(const VarDecl *V) {
277 ASTContext &Ctx = V->getASTContext();
278 for (auto &VarParent : Ctx.getParents(Node: *V)) {
279 auto *DS = VarParent.get<DeclStmt>();
280 if (!DS || !DS->isSingleDecl())
281 continue;
282 for (auto &DeclStmtParent : Ctx.getParents(Node: *DS)) {
283 auto *FCS = DeclStmtParent.get<ObjCForCollectionStmt>();
284 if (FCS && FCS->getElement() == DS)
285 return FCS;
286 }
287 }
288 return nullptr;
289}
290
291static const VarDecl *findAssignedVar(const Expr *DestExpr) {
292 while (DestExpr) {
293 DestExpr = DestExpr->IgnoreParenCasts();
294 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: DestExpr))
295 return dyn_cast_or_null<VarDecl>(Val: DRE->getDecl());
296 if (auto *UO = dyn_cast<UnaryOperator>(Val: DestExpr);
297 UO && UO->getOpcode() == UO_Deref) {
298 DestExpr = UO->getSubExpr();
299 continue;
300 }
301 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Val: DestExpr)) {
302 DestExpr = ASE->getBase();
303 continue;
304 }
305 return nullptr;
306 }
307 return nullptr;
308}
309
310class RawPtrRefLocalVarsChecker
311 : public Checker<check::ASTDecl<TranslationUnitDecl>> {
312 BugType Bug;
313 EnsureFunctionAnalysis EFA;
314
315protected:
316 mutable BugReporter *BR;
317 const std::unique_ptr<PtrRefSafetyModel> Model;
318
319public:
320 RawPtrRefLocalVarsChecker(const char *description,
321 std::unique_ptr<PtrRefSafetyModel> Model)
322 : Bug(this, description, "WebKit coding guidelines"),
323 Model(std::move(Model)) {}
324
325 std::optional<bool> isUnsafePtr(QualType T) const {
326 return isUnsafePtrForStorage(Model: *Model, T);
327 }
328
329 void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
330 BugReporter &BRArg) const {
331 BR = &BRArg;
332
333 // The calls to checkAST* from AnalysisConsumer don't
334 // visit template instantiations or lambda classes. We
335 // want to visit those, so we make our own RecursiveASTVisitor.
336 struct LocalVisitor : DynamicRecursiveASTVisitor {
337 const RawPtrRefLocalVarsChecker *Checker;
338 Decl *DeclWithIssue{nullptr};
339
340 TrivialFunctionAnalysis TFA;
341
342 explicit LocalVisitor(const RawPtrRefLocalVarsChecker *Checker)
343 : Checker(Checker) {
344 assert(Checker);
345 ShouldVisitTemplateInstantiations = true;
346 ShouldVisitImplicitCode = false;
347 }
348
349 bool TraverseDecl(Decl *D) override {
350 // A template pattern is checked through its instantiations, which are
351 // traversed from the TemplateDecl itself. In the pattern the callee of
352 // a call may still be an unresolved overload set and the type of an
353 // expression may still be dependent, neither of which can be reasoned
354 // about, so don't enter it at all.
355 if (D && !isa<TemplateDecl>(Val: D) && D->isTemplated())
356 return true;
357 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
358 if (D && (isa<FunctionDecl>(Val: D) || isa<ObjCMethodDecl>(Val: D)))
359 DeclWithIssue = D;
360 return DynamicRecursiveASTVisitor::TraverseDecl(D);
361 }
362
363 bool TraverseLambdaExpr(LambdaExpr *L) override {
364 auto *FTD = L->getLambdaClass()->getDependentLambdaCallOperator();
365 if (!FTD)
366 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(S: L);
367 // The body of a generic lambda is the pattern of its call operator,
368 // but it is reached from the LambdaExpr as a statement, so TraverseDecl
369 // never gets to skip it. Traverse the capture initializers, which are
370 // evaluated in the enclosing scope, and then the call operator itself,
371 // of which the pattern is skipped like any other and the instantiations
372 // are traversed. Going through TraverseDecl also makes an instantiation
373 // the decl with the issue, so that a guardian is looked up in it rather
374 // than in the pattern. The initializers are traversed as expressions
375 // because the variable of an init capture is declared in the pattern.
376 for (unsigned I = 0, N = L->capture_size(); I != N; ++I) {
377 if (!(L->capture_begin() + I)->isExplicit())
378 continue;
379 if (auto *Init = L->capture_init_begin()[I];
380 Init && !TraverseStmt(S: Init))
381 return false;
382 }
383 return TraverseDecl(D: FTD);
384 }
385
386 bool VisitTypedefDecl(TypedefDecl *TD) override {
387 if (auto *RTC = Checker->Model->retainTypeChecker())
388 RTC->visitTypedef(TD);
389 return true;
390 }
391
392 bool VisitVarDecl(VarDecl *V) override {
393 auto *Init = V->getInit();
394 if (V->isLocalVarDecl())
395 Checker->visitVarDecl(V, SinkType: V->getType(), Value: Init, DeclWithIssue);
396 return true;
397 }
398
399 bool VisitBinaryOperator(BinaryOperator *BO) override {
400 if (BO->isAssignmentOp()) {
401 if (Checker->Model->recognizesIndirectStores()) {
402 if (auto *V = findAssignedVar(DestExpr: BO->getLHS()))
403 Checker->visitVarDecl(V, SinkType: BO->getLHS()->getType(), Value: BO->getRHS(),
404 DeclWithIssue);
405 } else if (auto *VarRef = dyn_cast<DeclRefExpr>(Val: BO->getLHS())) {
406 if (auto *V = dyn_cast<VarDecl>(Val: VarRef->getDecl()))
407 Checker->visitVarDecl(V, SinkType: V->getType(), Value: BO->getRHS(),
408 DeclWithIssue);
409 }
410 }
411 return true;
412 }
413
414 bool TraverseIfStmt(IfStmt *IS) override {
415 if (IS->getConditionVariable()) {
416 // This code does not check the condition variable in the "else"
417 // statement since getConditionVariable returns nullptr when there
418 // is a condition defined after ";" as in "if (auto foo = ~; !foo)".
419 // If this semantics change, we should check it in "else" as well.
420 if (auto *Then = IS->getThen(); !Then || TFA.isTrivial(S: Then)) {
421 if (auto *Else = IS->getElse(); Else && !TFA.isTrivial(S: Else))
422 return TraverseStmt(S: Else);
423 return true;
424 }
425 }
426 if (!TFA.isTrivial(S: IS))
427 return DynamicRecursiveASTVisitor::TraverseIfStmt(S: IS);
428 return true;
429 }
430
431 bool TraverseForStmt(ForStmt *FS) override {
432 if (!TFA.isTrivial(S: FS))
433 return DynamicRecursiveASTVisitor::TraverseForStmt(S: FS);
434 return true;
435 }
436
437 bool TraverseCXXForRangeStmt(CXXForRangeStmt *FRS) override {
438 if (!TFA.isTrivial(S: FRS))
439 return DynamicRecursiveASTVisitor::TraverseCXXForRangeStmt(S: FRS);
440 return true;
441 }
442
443 bool TraverseWhileStmt(WhileStmt *WS) override {
444 if (!TFA.isTrivial(S: WS))
445 return DynamicRecursiveASTVisitor::TraverseWhileStmt(S: WS);
446 return true;
447 }
448
449 bool TraverseCompoundStmt(CompoundStmt *CS) override {
450 if (!TFA.isTrivial(S: CS))
451 return DynamicRecursiveASTVisitor::TraverseCompoundStmt(S: CS);
452 return true;
453 }
454
455 bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl) override {
456 if (isSmartPtrClass(Name: safeGetName(ASTNode: Decl)))
457 return true;
458 return DynamicRecursiveASTVisitor::TraverseClassTemplateDecl(D: Decl);
459 }
460 };
461
462 LocalVisitor visitor(this);
463 if (auto *RTC = Model->retainTypeChecker())
464 RTC->visitTranslationUnitDecl(TUD);
465 visitor.TraverseDecl(D: const_cast<TranslationUnitDecl *>(TUD));
466 }
467
468 void visitVarDecl(const VarDecl *V, QualType SinkType, const Expr *Value,
469 const Decl *DeclWithIssue) const {
470 if (shouldSkipVarDecl(V))
471 return;
472
473 if (auto *DD = dyn_cast<DecompositionDecl>(Val: V)) {
474 const auto *InitList =
475 Value ? dyn_cast<InitListExpr>(Val: Value->IgnoreParenCasts()) : nullptr;
476 if (InitList && InitList->getNumInits() != DD->bindings().size())
477 InitList = nullptr;
478
479 unsigned BindingIndex = 0;
480 for (auto *BD : DD->bindings()) {
481 const unsigned Index = BindingIndex++;
482 auto *Binding = BD->getBinding();
483 if (!Binding)
484 continue;
485 std::optional<bool> IsUncountedPtr = isUnsafePtr(T: Binding->getType());
486 if (!IsUncountedPtr || !*IsUncountedPtr)
487 continue;
488
489 const Expr *Origin = nullptr;
490 if (Model->checksForInteriorDestruction()) {
491 const Expr *Source = InitList ? InitList->getInit(Init: Index) : Value;
492 if (isPtrOriginSafe(V, Value: Source, DeclWithIssue, Origin,
493 SinkType: Binding->getType()))
494 continue;
495 }
496 reportBug(V, SinkType: V->getType(), Value: nullptr, BindingDecl: BD, DeclWithIssue, Origin);
497 }
498 }
499
500 std::optional<bool> IsUncountedPtr = isUnsafePtr(T: SinkType);
501 if (IsUncountedPtr && *IsUncountedPtr) {
502 const Expr *Origin = nullptr;
503 // The element of a fast enumeration is kept alive by the collection,
504 // which can't be mutated during the enumeration. Treat the collection as
505 // the initial value of the element.
506 if (!Value) {
507 if (auto *FCS = findObjCForCollectionStmtOfElement(V))
508 Value = FCS->getCollection();
509 }
510 if (Value) {
511 if (isPtrOriginSafe(V, Value, DeclWithIssue, Origin, SinkType))
512 return;
513 } else if (Model->checksForInteriorDestruction())
514 return;
515 reportBug(V, SinkType, Value, BindingDecl: nullptr, DeclWithIssue, Origin);
516 }
517 }
518
519 bool isPtrOriginSafe(const VarDecl *V, const Expr *Value,
520 const Decl *DeclWithIssue, const Expr *&Origin,
521 QualType SinkType = QualType()) const {
522 return tryToFindPtrOrigin(
523 E: Value, /*StopAtFirstRefCountedObj=*/false,
524 FollowLifetimeBound: Model->checksForInteriorDestruction(),
525 isSafePtr: [&](const clang::CXXRecordDecl *Record) {
526 return Model->isSafePtr(Record);
527 },
528 isSafePtrType: [&](const clang::QualType Type) { return Model->isSafePtrType(T: Type); },
529 isSafeGlobalDecl: [&](const clang::Decl *D) {
530 return Model->isSafeDecl(D, BR->getSourceManager());
531 },
532 callback: [&](const clang::Expr *InitArgOrigin, bool IsSafe,
533 bool OriginDependsOnFullExpressionTemporary,
534 bool PtrIsLifetimeBoundToOrigin) {
535 if (!InitArgOrigin)
536 return true;
537
538 if (IsSafe) {
539 if (!OriginDependsOnFullExpressionTemporary)
540 return true;
541 if (!Origin)
542 Origin = InitArgOrigin;
543 return false;
544 }
545
546 if (isa<CXXThisExpr>(Val: InitArgOrigin))
547 return true;
548
549 if (isNullPtr(E: InitArgOrigin))
550 return true;
551
552 if (isa<IntegerLiteral>(Val: InitArgOrigin))
553 return true;
554
555 if (isConstOwnerPtrMemberExpr(E: InitArgOrigin))
556 return true;
557
558 if (EFA.isACallToEnsureFn(E: InitArgOrigin))
559 return true;
560
561 if (Model->isSafeExpr(Origin: InitArgOrigin, PtrIsLifetimeBoundToOrigin,
562 SinkType, /*SinkMayEscape=*/false))
563 return true;
564
565 if (!Model->checksForInteriorDestruction() &&
566 hasGuardian(V, InitArgOrigin, DeclWithIssue))
567 return true;
568
569 if (!Origin)
570 Origin = InitArgOrigin;
571 return false;
572 });
573 }
574
575 bool hasGuardian(const VarDecl *V, const Expr *InitArgOrigin,
576 const Decl *DeclWithIssue) const {
577 auto *Ref = dyn_cast<DeclRefExpr>(Val: InitArgOrigin);
578 if (!Ref)
579 return false;
580
581 auto *MaybeGuardian = dyn_cast_or_null<VarDecl>(Val: Ref->getFoundDecl());
582 if (!MaybeGuardian)
583 return false;
584
585 QualType GuardianType = MaybeGuardian->getType();
586 // The collection of a fast enumeration is evaluated before the loop body is
587 // entered and keeps its elements alive. A raw pointer local variable or
588 // parameter holding the collection is checked on its own, so it only needs
589 // to be left untouched by the loop body.
590 if (auto *FCS = findObjCForCollectionStmtOfElement(V);
591 FCS && !GuardianType.isNull() && GuardianType->isAnyPointerType() &&
592 (MaybeGuardian->isLocalVarDecl() || isa<ParmVarDecl>(Val: MaybeGuardian))) {
593 GuardianVisitor Visitor(MaybeGuardian, /*GuardianIsRawPtrOrRef=*/true);
594 return Visitor.TraverseStmt(S: const_cast<Stmt *>(FCS->getBody()));
595 }
596
597 if (!GuardianType.isNull()) {
598 if (auto *Record = GuardianType->getAsCXXRecordDecl()) {
599 if (MaybeGuardian->isLocalVarDecl() &&
600 (Model->isSafePtr(Record) ||
601 isRefcountedStringsHack(V: MaybeGuardian))) {
602 // The collection of a fast enumeration is evaluated before the loop
603 // body is entered so the guardian only needs to outlive the body.
604 if (auto *FCS = findObjCForCollectionStmtOfElement(V)) {
605 GuardianVisitor Visitor(MaybeGuardian);
606 return Visitor.TraverseStmt(S: const_cast<Stmt *>(FCS->getBody()));
607 }
608 if (isGuardedScopeEmbeddedInGuardianScope(Guarded: V, MaybeGuardian))
609 return true;
610 }
611 }
612 }
613
614 if (isa<ParmVarDecl>(Val: MaybeGuardian)) {
615 bool IsRawPtrOrRef = isUnsafePtr(T: GuardianType).value_or(u: false);
616 GuardianVisitor Visitor{MaybeGuardian, IsRawPtrOrRef};
617 if (auto *FD = dyn_cast<FunctionDecl>(Val: DeclWithIssue))
618 return Visitor.TraverseStmt(S: FD->getBody());
619 if (auto *MD = dyn_cast<ObjCMethodDecl>(Val: DeclWithIssue))
620 return Visitor.TraverseStmt(S: MD->getBody());
621 }
622
623 return false;
624 }
625
626 bool shouldSkipVarDecl(const VarDecl *V) const {
627 assert(V);
628 if (isa<ImplicitParamDecl>(Val: V))
629 return true;
630 if (V->isInitCapture())
631 return true;
632 return BR->getSourceManager().isInSystemHeader(Loc: V->getLocation());
633 }
634
635 void reportBug(const VarDecl *V, QualType SinkType, const Expr *Value,
636 const Decl *BindingDecl, const Decl *DeclWithIssue,
637 const Expr *Origin) const {
638 assert(V);
639 SmallString<100> Buf;
640 llvm::raw_svector_ostream Os(Buf);
641
642 if (isa<ParmVarDecl>(Val: V)) {
643 Os << "Parameter ";
644 printQuotedQualifiedName(Os, D: V);
645 Os << " is a ";
646 Model->describeHazard(Os, Origin, SinkType);
647
648 SourceLocation ExprLoc = (Value) ? Value->getExprLoc() : V->getLocation();
649 PathDiagnosticLocation BSLoc(ExprLoc, BR->getSourceManager());
650 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
651 if (Value)
652 Report->addRange(R: Value->getSourceRange());
653 Report->setDeclWithIssue(DeclWithIssue);
654 BR->emitReport(R: std::move(Report));
655 } else {
656 if (V->hasLocalStorage())
657 Os << "Local variable ";
658 else if (V->isStaticLocal())
659 Os << "Static local variable ";
660 else if (V->hasGlobalStorage())
661 Os << "Global variable ";
662 else
663 Os << "Variable ";
664 if (BindingDecl)
665 Os << "'" << safeGetName(ASTNode: BindingDecl) << "'";
666 else
667 printQuotedQualifiedName(Os, D: V);
668 Os << " is a ";
669 Model->describeHazard(Os, Origin, SinkType);
670
671 PathDiagnosticLocation BSLoc(V->getLocation(), BR->getSourceManager());
672 auto Report = std::make_unique<BasicBugReport>(args: Bug, args: Os.str(), args&: BSLoc);
673 Report->addRange(R: V->getSourceRange());
674 Report->setDeclWithIssue(DeclWithIssue);
675 BR->emitReport(R: std::move(Report));
676 }
677 }
678};
679
680class UncountedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
681public:
682 UncountedLocalVarsChecker()
683 : RawPtrRefLocalVarsChecker("Uncounted raw pointer or reference not "
684 "provably backed by ref-counted variable",
685 makeRefPtrSafetyModel()) {}
686};
687
688class UncheckedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
689public:
690 UncheckedLocalVarsChecker()
691 : RawPtrRefLocalVarsChecker("Unchecked raw pointer or reference not "
692 "provably backed by checked variable",
693 makeCheckedPtrSafetyModel()) {}
694};
695
696class UnretainedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
697public:
698 UnretainedLocalVarsChecker()
699 : RawPtrRefLocalVarsChecker("Unretained raw pointer or reference not "
700 "provably backed by a RetainPtr",
701 makeRetainPtrSafetyModel()) {}
702};
703
704class UnborrowedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
705public:
706 UnborrowedLocalVarsChecker()
707 : RawPtrRefLocalVarsChecker("Unborrowed raw pointer or reference not "
708 "provably backed by a Borrow",
709 makeBorrowSafetyModel()) {}
710};
711
712} // namespace
713
714void ento::registerUncountedLocalVarsChecker(CheckerManager &Mgr) {
715 Mgr.registerChecker<UncountedLocalVarsChecker>();
716}
717
718bool ento::shouldRegisterUncountedLocalVarsChecker(const CheckerManager &) {
719 return true;
720}
721
722void ento::registerUncheckedLocalVarsChecker(CheckerManager &Mgr) {
723 Mgr.registerChecker<UncheckedLocalVarsChecker>();
724}
725
726bool ento::shouldRegisterUncheckedLocalVarsChecker(const CheckerManager &) {
727 return true;
728}
729
730void ento::registerUnretainedLocalVarsChecker(CheckerManager &Mgr) {
731 Mgr.registerChecker<UnretainedLocalVarsChecker>();
732}
733
734bool ento::shouldRegisterUnretainedLocalVarsChecker(const CheckerManager &) {
735 return true;
736}
737
738void ento::registerUnborrowedLocalVarsChecker(CheckerManager &Mgr) {
739 Mgr.registerChecker<UnborrowedLocalVarsChecker>();
740}
741
742bool ento::shouldRegisterUnborrowedLocalVarsChecker(const CheckerManager &) {
743 return true;
744}
745