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