clang 24.0.0git
RawPtrRefLocalVarsChecker.cpp
Go to the documentation of this file.
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"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclCXX.h"
18#include "clang/AST/StmtObjC.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(CXXRD)))
44 return true;
45 }
46 if (T->isPointerType() || T->isReferenceType()) {
47 if (auto *CXXRD = T->getPointeeCXXRecordDecl()) {
48 if (safeClass(safeGetName(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>(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(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(Callee))
96 return true;
97 if (auto *Method = dyn_cast<CXXMethodDecl>(Callee)) {
98 if (isGetterOfSafePtr(Method).value_or(false))
99 return true;
100 }
101 // For a member operator call, the first argument is the implicit object.
102 auto *OperatorMethod = dyn_cast<CXXMethodDecl>(Callee);
103 if (!isa<CXXOperatorCallExpr>(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(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(MCE);
135 Prototype && Prototype->getMethodQuals().hasConst())
136 return true;
137 }
138 auto *ThisArg = MCE->getImplicitObjectArgument()->IgnoreParenCasts();
139 if (auto *UO = dyn_cast<UnaryOperator>(ThisArg);
140 UO && UO->getOpcode() == UO_AddrOf)
141 ThisArg = UO->getSubExpr()->IgnoreParenCasts();
142 if (auto *VarRef = dyn_cast<DeclRefExpr>(ThisArg)) {
143 if (!isa_and_nonnull<CXXConversionDecl>(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>(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(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>(Arg);
192 UO && UO->getOpcode() == UO_AddrOf) {
193 Arg = UO->getSubExpr()->IgnoreParenCasts();
194 IsAddressOf = true;
195 }
196 auto *VarRef = dyn_cast<DeclRefExpr>(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(*MaybeGuardian);
228 !guardianAncestors.empty();
229 guardianAncestors = ctx.getParents(
230 *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(*Guarded);
250 !guardedVarAncestors.empty();
251 guardedVarAncestors = ctx.getParents(
252 *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(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(*V)) {
279 auto *DS = VarParent.get<DeclStmt>();
280 if (!DS || !DS->isSingleDecl())
281 continue;
282 for (auto &DeclStmtParent : Ctx.getParents(*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>(DestExpr))
295 return dyn_cast_or_null<VarDecl>(DRE->getDecl());
296 if (auto *UO = dyn_cast<UnaryOperator>(DestExpr);
297 UO && UO->getOpcode() == UO_Deref) {
298 DestExpr = UO->getSubExpr();
299 continue;
300 }
301 if (auto *ASE = dyn_cast<ArraySubscriptExpr>(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, 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>(D) && D->isTemplated())
356 return true;
357 llvm::SaveAndRestore SavedDecl(DeclWithIssue);
358 if (D && (isa<FunctionDecl>(D) || isa<ObjCMethodDecl>(D)))
359 DeclWithIssue = D;
361 }
362
363 bool TraverseLambdaExpr(LambdaExpr *L) override {
365 if (!FTD)
366 return DynamicRecursiveASTVisitor::TraverseLambdaExpr(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(Init))
381 return false;
382 }
383 return TraverseDecl(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, V->getType(), 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(BO->getLHS()))
403 Checker->visitVarDecl(V, BO->getLHS()->getType(), BO->getRHS(),
404 DeclWithIssue);
405 } else if (auto *VarRef = dyn_cast<DeclRefExpr>(BO->getLHS())) {
406 if (auto *V = dyn_cast<VarDecl>(VarRef->getDecl()))
407 Checker->visitVarDecl(V, V->getType(), 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(Then)) {
421 if (auto *Else = IS->getElse(); Else && !TFA.isTrivial(Else))
422 return TraverseStmt(Else);
423 return true;
424 }
425 }
426 if (!TFA.isTrivial(IS))
427 return DynamicRecursiveASTVisitor::TraverseIfStmt(IS);
428 return true;
429 }
430
431 bool TraverseForStmt(ForStmt *FS) override {
432 if (!TFA.isTrivial(FS))
433 return DynamicRecursiveASTVisitor::TraverseForStmt(FS);
434 return true;
435 }
436
437 bool TraverseCXXForRangeStmt(CXXForRangeStmt *FRS) override {
438 if (!TFA.isTrivial(FRS))
439 return DynamicRecursiveASTVisitor::TraverseCXXForRangeStmt(FRS);
440 return true;
441 }
442
443 bool TraverseWhileStmt(WhileStmt *WS) override {
444 if (!TFA.isTrivial(WS))
445 return DynamicRecursiveASTVisitor::TraverseWhileStmt(WS);
446 return true;
447 }
448
449 bool TraverseCompoundStmt(CompoundStmt *CS) override {
450 if (!TFA.isTrivial(CS))
451 return DynamicRecursiveASTVisitor::TraverseCompoundStmt(CS);
452 return true;
453 }
454
455 bool TraverseClassTemplateDecl(ClassTemplateDecl *Decl) override {
456 if (isSmartPtrClass(safeGetName(Decl)))
457 return true;
458 return DynamicRecursiveASTVisitor::TraverseClassTemplateDecl(Decl);
459 }
460 };
461
462 LocalVisitor visitor(this);
463 if (auto *RTC = Model->retainTypeChecker())
464 RTC->visitTranslationUnitDecl(TUD);
465 visitor.TraverseDecl(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>(V)) {
474 const auto *InitList =
475 Value ? dyn_cast<InitListExpr>(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(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(Index) : Value;
492 if (isPtrOriginSafe(V, Source, DeclWithIssue, Origin,
493 Binding->getType()))
494 continue;
495 }
496 reportBug(V, V->getType(), nullptr, BD, DeclWithIssue, Origin);
497 }
498 }
499
500 std::optional<bool> IsUncountedPtr = isUnsafePtr(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, 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 Value, /*StopAtFirstRefCountedObj=*/false,
524 Model->checksForInteriorDestruction(),
525 [&](const clang::CXXRecordDecl *Record) {
526 return Model->isSafePtr(Record);
527 },
528 [&](const clang::QualType Type) { return Model->isSafePtrType(Type); },
529 [&](const clang::Decl *D) {
530 return Model->isSafeDecl(D, BR->getSourceManager());
531 },
532 [&](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>(InitArgOrigin))
547 return true;
548
549 if (isNullPtr(InitArgOrigin))
550 return true;
551
552 if (isa<IntegerLiteral>(InitArgOrigin))
553 return true;
554
555 if (isConstOwnerPtrMemberExpr(InitArgOrigin))
556 return true;
557
558 if (EFA.isACallToEnsureFn(InitArgOrigin))
559 return true;
560
561 if (Model->isSafeExpr(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>(InitArgOrigin);
578 if (!Ref)
579 return false;
580
581 auto *MaybeGuardian = dyn_cast_or_null<VarDecl>(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>(MaybeGuardian))) {
593 GuardianVisitor Visitor(MaybeGuardian, /*GuardianIsRawPtrOrRef=*/true);
594 return Visitor.TraverseStmt(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(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(const_cast<Stmt *>(FCS->getBody()));
607 }
608 if (isGuardedScopeEmbeddedInGuardianScope(V, MaybeGuardian))
609 return true;
610 }
611 }
612 }
613
614 if (isa<ParmVarDecl>(MaybeGuardian)) {
615 bool IsRawPtrOrRef = isUnsafePtr(GuardianType).value_or(false);
616 GuardianVisitor Visitor{MaybeGuardian, IsRawPtrOrRef};
617 if (auto *FD = dyn_cast<FunctionDecl>(DeclWithIssue))
618 return Visitor.TraverseStmt(FD->getBody());
619 if (auto *MD = dyn_cast<ObjCMethodDecl>(DeclWithIssue))
620 return Visitor.TraverseStmt(MD->getBody());
621 }
622
623 return false;
624 }
625
626 bool shouldSkipVarDecl(const VarDecl *V) const {
627 assert(V);
629 return true;
630 if (V->isInitCapture())
631 return true;
632 return BR->getSourceManager().isInSystemHeader(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);
640 llvm::raw_svector_ostream Os(Buf);
641
642 if (isa<ParmVarDecl>(V)) {
643 Os << "Parameter ";
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>(Bug, Os.str(), BSLoc);
651 if (Value)
652 Report->addRange(Value->getSourceRange());
653 Report->setDeclWithIssue(DeclWithIssue);
654 BR->emitReport(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(BindingDecl) << "'";
666 else
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>(Bug, Os.str(), BSLoc);
673 Report->addRange(V->getSourceRange());
674 Report->setDeclWithIssue(DeclWithIssue);
675 BR->emitReport(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",
686};
687
688class UncheckedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
689public:
690 UncheckedLocalVarsChecker()
691 : RawPtrRefLocalVarsChecker("Unchecked raw pointer or reference not "
692 "provably backed by checked variable",
694};
695
696class UnretainedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
697public:
698 UnretainedLocalVarsChecker()
699 : RawPtrRefLocalVarsChecker("Unretained raw pointer or reference not "
700 "provably backed by a RetainPtr",
702};
703
704class UnborrowedLocalVarsChecker final : public RawPtrRefLocalVarsChecker {
705public:
706 UnborrowedLocalVarsChecker()
707 : RawPtrRefLocalVarsChecker("Unborrowed raw pointer or reference not "
708 "provably backed by a Borrow",
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}
#define V(N, I)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
llvm::MachO::Record Record
Definition MachO.h:31
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the Objective-C statement AST node classes.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:246
DynTypedNodeList getParents(const NodeT &Node)
Forwards to get node parents from the ParentMapContext.
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4184
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4243
A binding in a decomposition declaration.
Definition DeclCXX.h:4232
arg_range arguments()
Definition ExprCXX.h:1677
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
CXXMethodDecl * getMethodDecl() const
Retrieve the declaration of the called method.
Definition ExprCXX.cpp:773
Expr * getImplicitObjectArgument() const
Retrieve the implicit object argument for the member call.
Definition ExprCXX.cpp:754
QualType getObjectType() const
Retrieve the type of the object argument.
Definition ExprCXX.cpp:766
FunctionTemplateDecl * getDependentLambdaCallOperator() const
Retrieve the dependent lambda call operator of the closure type if this is a templated closure type.
Definition DeclCXX.cpp:1739
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition DeclBase.cpp:308
Container for either a single DynTypedNode or for an ArrayRef to DynTypedNode.
virtual bool TraverseDecl(MaybeConst< Decl > *D)
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3135
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3126
QualType getType() const
Definition Expr.h:146
Stmt * getThen()
Definition Stmt.h:2359
Stmt * getElse()
Definition Stmt.h:2368
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition ExprCXX.cpp:1395
unsigned capture_size() const
Determine the number of captures in this lambda.
Definition ExprCXX.h:2054
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2099
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1432
Represents Objective-C's collection statement.
Definition StmtObjC.h:23
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8680
Encodes a location in the source.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Stmt - This represents one statement.
Definition Stmt.h:85
bool isTrivial(const Decl *D) const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isAnyPointerType() const
Definition TypeBase.h:8925
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
const SourceManager & getSourceManager()
virtual void emitReport(std::unique_ptr< BugReport > R)
Add the given report to the set of reports tracked by BugReporter.
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.
Definition Checker.h:565
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.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
std::unique_ptr< PtrRefSafetyModel > makeBorrowSafetyModel()
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool isPtrConversion(const FunctionDecl *F)
std::unique_ptr< PtrRefSafetyModel > makeCheckedPtrSafetyModel()
void printQuotedQualifiedName(llvm::raw_ostream &Os, const NamedDeclDerivedT &D)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
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...
bool isSmartPtrClass(const std::string &Name)
std::optional< bool > isGetterOfSafePtr(const CXXMethodDecl *M)
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:109
bool isNullPtr(const clang::Expr *E)
Definition ASTUtils.cpp:535
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
std::unique_ptr< PtrRefSafetyModel > makeRefPtrSafetyModel()
bool tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound, std::function< bool(const clang::CXXRecordDecl *)> isSafePtr, std::function< bool(const clang::QualType)> isSafePtrType, std::function< bool(const clang::Decl *)> isSafeGlobalDecl, std::function< bool(const clang::Expr *, bool, bool, bool)> callback)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
Definition ASTUtils.cpp:478
std::unique_ptr< PtrRefSafetyModel > makeRetainPtrSafetyModel()
bool isConstOwnerPtrMemberExpr(const clang::Expr *E)
Definition ASTUtils.cpp:545