1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
|
//=======- UncountedLambdaCapturesChecker.cpp --------------------*- C++ -*-==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "ASTUtils.h"
#include "DiagOutputUtils.h"
#include "PtrTypesSemantics.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include <optional>
using namespace clang;
using namespace ento;
namespace {
class RawPtrRefLambdaCapturesChecker
: public Checker<check::ASTDecl<TranslationUnitDecl>> {
private:
BugType Bug;
mutable BugReporter *BR = nullptr;
TrivialFunctionAnalysis TFA;
protected:
mutable std::optional<RetainTypeChecker> RTC;
public:
RawPtrRefLambdaCapturesChecker(const char *description)
: Bug(this, description, "WebKit coding guidelines") {}
virtual std::optional<bool> isUnsafePtr(QualType) const = 0;
virtual bool isPtrType(const std::string &) const = 0;
virtual const char *ptrKind(QualType QT) const = 0;
void checkASTDecl(const TranslationUnitDecl *TUD, AnalysisManager &MGR,
BugReporter &BRArg) const {
BR = &BRArg;
// The calls to checkAST* from AnalysisConsumer don't
// visit template instantiations or lambda classes. We
// want to visit those, so we make our own RecursiveASTVisitor.
struct LocalVisitor : DynamicRecursiveASTVisitor {
const RawPtrRefLambdaCapturesChecker *Checker;
llvm::DenseSet<const DeclRefExpr *> DeclRefExprsToIgnore;
llvm::DenseSet<const LambdaExpr *> LambdasToIgnore;
llvm::DenseSet<const ValueDecl *> ProtectedThisDecls;
llvm::DenseSet<const CXXConstructExpr *> ConstructToIgnore;
QualType ClsType;
explicit LocalVisitor(const RawPtrRefLambdaCapturesChecker *Checker)
: Checker(Checker) {
assert(Checker);
ShouldVisitTemplateInstantiations = true;
ShouldVisitImplicitCode = false;
}
bool TraverseCXXMethodDecl(CXXMethodDecl *CXXMD) override {
llvm::SaveAndRestore SavedDecl(ClsType);
if (CXXMD->isInstance())
ClsType = CXXMD->getThisType();
return DynamicRecursiveASTVisitor::TraverseCXXMethodDecl(CXXMD);
}
bool TraverseObjCMethodDecl(ObjCMethodDecl *OCMD) override {
llvm::SaveAndRestore SavedDecl(ClsType);
if (OCMD && OCMD->isInstanceMethod()) {
if (auto *ImplParamDecl = OCMD->getSelfDecl())
ClsType = ImplParamDecl->getType();
}
return DynamicRecursiveASTVisitor::TraverseObjCMethodDecl(OCMD);
}
bool VisitTypedefDecl(TypedefDecl *TD) override {
if (Checker->RTC)
Checker->RTC->visitTypedef(TD);
return true;
}
bool shouldCheckThis() {
auto result =
!ClsType.isNull() ? Checker->isUnsafePtr(ClsType) : std::nullopt;
return result && *result;
}
bool VisitLambdaExpr(LambdaExpr *L) override {
if (LambdasToIgnore.contains(L))
return true;
Checker->visitLambdaExpr(L, shouldCheckThis() && !hasProtectedThis(L),
ClsType);
return true;
}
bool VisitVarDecl(VarDecl *VD) override {
auto *Init = VD->getInit();
if (!Init)
return true;
auto *L = dyn_cast_or_null<LambdaExpr>(Init->IgnoreParenCasts());
if (!L)
return true;
LambdasToIgnore.insert(L); // Evaluate lambdas in VisitDeclRefExpr.
return true;
}
bool VisitDeclRefExpr(DeclRefExpr *DRE) override {
if (DeclRefExprsToIgnore.contains(DRE))
return true;
auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl());
if (!VD)
return true;
auto *Init = VD->getInit();
if (!Init)
return true;
auto *L = dyn_cast_or_null<LambdaExpr>(Init->IgnoreParenCasts());
if (!L)
return true;
LambdasToIgnore.insert(L);
Checker->visitLambdaExpr(L, shouldCheckThis() && !hasProtectedThis(L),
ClsType);
return true;
}
bool shouldTreatAllArgAsNoEscape(FunctionDecl *Decl) {
auto *NsDecl = Decl->getParent();
if (!NsDecl || !isa<NamespaceDecl>(NsDecl))
return false;
// WTF::switchOn(T, F... f) is a variadic template function and couldn't
// be annotated with NOESCAPE. We hard code it here to workaround that.
if (safeGetName(NsDecl) == "WTF" && safeGetName(Decl) == "switchOn")
return true;
// Treat every argument of functions in std::ranges as noescape.
if (safeGetName(NsDecl) == "ranges") {
if (auto *OuterDecl = NsDecl->getParent();
OuterDecl && isa<NamespaceDecl>(OuterDecl) &&
safeGetName(OuterDecl) == "std")
return true;
}
return false;
}
bool VisitCXXConstructExpr(CXXConstructExpr *CE) override {
if (ConstructToIgnore.contains(CE))
return true;
if (auto *Callee = CE->getConstructor()) {
unsigned ArgIndex = 0;
for (auto *Param : Callee->parameters()) {
if (ArgIndex >= CE->getNumArgs())
return true;
auto *Arg = CE->getArg(ArgIndex)->IgnoreParenCasts();
if (auto *L = findLambdaInArg(Arg)) {
LambdasToIgnore.insert(L);
if (!Param->hasAttr<NoEscapeAttr>())
Checker->visitLambdaExpr(
L, shouldCheckThis() && !hasProtectedThis(L), ClsType);
}
++ArgIndex;
}
}
return true;
}
bool VisitCallExpr(CallExpr *CE) override {
checkCalleeLambda(CE);
if (auto *Callee = CE->getDirectCallee()) {
unsigned ArgIndex = isa<CXXOperatorCallExpr>(CE);
bool TreatAllArgsAsNoEscape = shouldTreatAllArgAsNoEscape(Callee);
for (auto *Param : Callee->parameters()) {
if (ArgIndex >= CE->getNumArgs())
return true;
auto *Arg = CE->getArg(ArgIndex)->IgnoreParenCasts();
if (auto *L = findLambdaInArg(Arg)) {
LambdasToIgnore.insert(L);
if (!Param->hasAttr<NoEscapeAttr>() && !TreatAllArgsAsNoEscape)
Checker->visitLambdaExpr(
L, shouldCheckThis() && !hasProtectedThis(L), ClsType);
}
++ArgIndex;
}
}
return true;
}
LambdaExpr *findLambdaInArg(Expr *E) {
if (auto *Lambda = dyn_cast_or_null<LambdaExpr>(E))
return Lambda;
auto *TempExpr = dyn_cast_or_null<CXXBindTemporaryExpr>(E);
if (!TempExpr)
return nullptr;
E = TempExpr->getSubExpr()->IgnoreParenCasts();
if (!E)
return nullptr;
if (auto *Lambda = dyn_cast<LambdaExpr>(E))
return Lambda;
auto *CE = dyn_cast_or_null<CXXConstructExpr>(E);
if (!CE || !CE->getNumArgs())
return nullptr;
auto *CtorArg = CE->getArg(0)->IgnoreParenCasts();
if (!CtorArg)
return nullptr;
auto *InnerCE = dyn_cast_or_null<CXXConstructExpr>(CtorArg);
if (InnerCE && InnerCE->getNumArgs())
CtorArg = InnerCE->getArg(0)->IgnoreParenCasts();
auto updateIgnoreList = [&] {
ConstructToIgnore.insert(CE);
if (InnerCE)
ConstructToIgnore.insert(InnerCE);
};
if (auto *Lambda = dyn_cast<LambdaExpr>(CtorArg)) {
updateIgnoreList();
return Lambda;
}
if (auto *TempExpr = dyn_cast<CXXBindTemporaryExpr>(CtorArg)) {
E = TempExpr->getSubExpr()->IgnoreParenCasts();
if (auto *Lambda = dyn_cast<LambdaExpr>(E)) {
updateIgnoreList();
return Lambda;
}
}
auto *DRE = dyn_cast<DeclRefExpr>(CtorArg);
if (!DRE)
return nullptr;
auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl());
if (!VD)
return nullptr;
auto *Init = VD->getInit();
if (!Init)
return nullptr;
if (auto *Lambda = dyn_cast<LambdaExpr>(Init)) {
updateIgnoreList();
return Lambda;
}
TempExpr = dyn_cast<CXXBindTemporaryExpr>(Init->IgnoreParenCasts());
if (!TempExpr)
return nullptr;
updateIgnoreList();
return dyn_cast_or_null<LambdaExpr>(TempExpr->getSubExpr());
}
void checkCalleeLambda(CallExpr *CE) {
auto *Callee = CE->getCallee();
if (!Callee)
return;
auto *DRE = dyn_cast<DeclRefExpr>(Callee->IgnoreParenCasts());
if (!DRE)
return;
auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl());
if (!MD || CE->getNumArgs() < 1)
return;
auto *Arg = CE->getArg(0)->IgnoreParenCasts();
if (auto *L = dyn_cast_or_null<LambdaExpr>(Arg)) {
LambdasToIgnore.insert(L); // Calling a lambda upon creation is safe.
return;
}
auto *ArgRef = dyn_cast<DeclRefExpr>(Arg);
if (!ArgRef)
return;
auto *VD = dyn_cast_or_null<VarDecl>(ArgRef->getDecl());
if (!VD)
return;
auto *Init = VD->getInit();
if (!Init)
return;
auto *L = dyn_cast_or_null<LambdaExpr>(Init->IgnoreParenCasts());
if (!L)
return;
DeclRefExprsToIgnore.insert(ArgRef);
LambdasToIgnore.insert(L);
}
bool hasProtectedThis(LambdaExpr *L) {
for (const LambdaCapture &OtherCapture : L->captures()) {
if (!OtherCapture.capturesVariable())
continue;
if (auto *ValueDecl = OtherCapture.getCapturedVar()) {
if (declProtectsThis(ValueDecl)) {
ProtectedThisDecls.insert(ValueDecl);
return true;
}
}
}
return false;
}
bool declProtectsThis(const ValueDecl *ValueDecl) const {
auto *VD = dyn_cast<VarDecl>(ValueDecl);
if (!VD)
return false;
auto *Init = VD->getInit();
if (!Init)
return false;
const Expr *Arg = Init->IgnoreParenCasts();
do {
if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Arg))
Arg = BTE->getSubExpr()->IgnoreParenCasts();
if (auto *CE = dyn_cast<CXXConstructExpr>(Arg)) {
auto *Ctor = CE->getConstructor();
if (!Ctor)
return false;
auto clsName = safeGetName(Ctor->getParent());
if (Checker->isPtrType(clsName) && CE->getNumArgs()) {
Arg = CE->getArg(0)->IgnoreParenCasts();
continue;
}
if (auto *Type = ClsType.getTypePtrOrNull()) {
if (auto *CXXR = Type->getPointeeCXXRecordDecl()) {
if (CXXR == Ctor->getParent() && Ctor->isMoveConstructor() &&
CE->getNumArgs() == 1) {
Arg = CE->getArg(0)->IgnoreParenCasts();
continue;
}
}
}
return false;
}
if (auto *CE = dyn_cast<CallExpr>(Arg)) {
if (CE->isCallToStdMove() && CE->getNumArgs() == 1) {
Arg = CE->getArg(0)->IgnoreParenCasts();
continue;
}
if (auto *Callee = CE->getDirectCallee()) {
if (isCtorOfSafePtr(Callee) && CE->getNumArgs() == 1) {
Arg = CE->getArg(0)->IgnoreParenCasts();
continue;
}
}
}
if (auto *OpCE = dyn_cast<CXXOperatorCallExpr>(Arg)) {
auto OpCode = OpCE->getOperator();
if (OpCode == OO_Star || OpCode == OO_Amp) {
auto *Callee = OpCE->getDirectCallee();
if (!Callee)
return false;
auto clsName = safeGetName(Callee->getParent());
if (!Checker->isPtrType(clsName) || !OpCE->getNumArgs())
return false;
Arg = OpCE->getArg(0)->IgnoreParenCasts();
continue;
}
}
if (auto *UO = dyn_cast<UnaryOperator>(Arg)) {
auto OpCode = UO->getOpcode();
if (OpCode == UO_Deref || OpCode == UO_AddrOf) {
Arg = UO->getSubExpr()->IgnoreParenCasts();
continue;
}
}
break;
} while (Arg);
if (auto *DRE = dyn_cast<DeclRefExpr>(Arg)) {
auto *Decl = DRE->getDecl();
if (auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(Decl)) {
auto kind = ImplicitParam->getParameterKind();
return kind == ImplicitParamKind::ObjCSelf ||
kind == ImplicitParamKind::CXXThis;
}
return ProtectedThisDecls.contains(Decl);
}
return isa<CXXThisExpr>(Arg);
}
};
LocalVisitor visitor(this);
if (RTC)
RTC->visitTranslationUnitDecl(TUD);
visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
}
void visitLambdaExpr(LambdaExpr *L, bool shouldCheckThis, const QualType T,
bool ignoreParamVarDecl = false) const {
if (TFA.isTrivial(L->getBody()))
return;
for (const LambdaCapture &C : L->captures()) {
if (C.capturesVariable()) {
ValueDecl *CapturedVar = C.getCapturedVar();
if (ignoreParamVarDecl && isa<ParmVarDecl>(CapturedVar))
continue;
if (auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(CapturedVar)) {
auto kind = ImplicitParam->getParameterKind();
if ((kind == ImplicitParamKind::ObjCSelf ||
kind == ImplicitParamKind::CXXThis) &&
!shouldCheckThis)
continue;
}
QualType CapturedVarQualType = CapturedVar->getType();
auto IsUncountedPtr = isUnsafePtr(CapturedVar->getType());
if (C.getCaptureKind() == LCK_ByCopy &&
CapturedVarQualType->isReferenceType())
continue;
if (IsUncountedPtr && *IsUncountedPtr)
reportBug(C, CapturedVar, CapturedVarQualType, L);
} else if (C.capturesThis() && shouldCheckThis) {
if (ignoreParamVarDecl) // this is always a parameter to this function.
continue;
reportBugOnThisPtr(C, T);
}
}
}
void reportBug(const LambdaCapture &Capture, ValueDecl *CapturedVar,
const QualType T, LambdaExpr *L) const {
assert(CapturedVar);
auto Location = Capture.getLocation();
if (isa<ImplicitParamDecl>(CapturedVar) && !Location.isValid())
Location = L->getBeginLoc();
SmallString<100> Buf;
llvm::raw_svector_ostream Os(Buf);
if (Capture.isExplicit()) {
Os << "Captured ";
} else {
Os << "Implicitly captured ";
}
if (isa<PointerType>(T) || isa<ObjCObjectPointerType>(T)) {
Os << "raw-pointer ";
} else {
Os << "reference ";
}
printQuotedQualifiedName(Os, CapturedVar);
Os << " to " << ptrKind(T) << " type is unsafe.";
PathDiagnosticLocation BSLoc(Location, BR->getSourceManager());
auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
BR->emitReport(std::move(Report));
}
void reportBugOnThisPtr(const LambdaCapture &Capture,
const QualType T) const {
SmallString<100> Buf;
llvm::raw_svector_ostream Os(Buf);
if (Capture.isExplicit()) {
Os << "Captured ";
} else {
Os << "Implicitly captured ";
}
Os << "raw-pointer 'this' to " << ptrKind(T) << " type is unsafe.";
PathDiagnosticLocation BSLoc(Capture.getLocation(), BR->getSourceManager());
auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
BR->emitReport(std::move(Report));
}
};
class UncountedLambdaCapturesChecker : public RawPtrRefLambdaCapturesChecker {
public:
UncountedLambdaCapturesChecker()
: RawPtrRefLambdaCapturesChecker("Lambda capture of uncounted or "
"unchecked variable") {}
std::optional<bool> isUnsafePtr(QualType QT) const final {
auto result1 = isUncountedPtr(QT);
auto result2 = isUncheckedPtr(QT);
if (result1 && *result1)
return true;
if (result2 && *result2)
return true;
if (result1)
return *result1;
return result2;
}
virtual bool isPtrType(const std::string &Name) const final {
return isRefType(Name) || isCheckedPtr(Name);
}
const char *ptrKind(QualType QT) const final {
if (isUncounted(QT))
return "uncounted";
return "unchecked";
}
};
class UnretainedLambdaCapturesChecker : public RawPtrRefLambdaCapturesChecker {
public:
UnretainedLambdaCapturesChecker()
: RawPtrRefLambdaCapturesChecker("Lambda capture of unretained "
"variables") {
RTC = RetainTypeChecker();
}
std::optional<bool> isUnsafePtr(QualType QT) const final {
return RTC->isUnretained(QT);
}
virtual bool isPtrType(const std::string &Name) const final {
return isRetainPtr(Name);
}
const char *ptrKind(QualType QT) const final { return "unretained"; }
};
} // namespace
void ento::registerUncountedLambdaCapturesChecker(CheckerManager &Mgr) {
Mgr.registerChecker<UncountedLambdaCapturesChecker>();
}
bool ento::shouldRegisterUncountedLambdaCapturesChecker(
const CheckerManager &mgr) {
return true;
}
void ento::registerUnretainedLambdaCapturesChecker(CheckerManager &Mgr) {
Mgr.registerChecker<UnretainedLambdaCapturesChecker>();
}
bool ento::shouldRegisterUnretainedLambdaCapturesChecker(
const CheckerManager &mgr) {
return true;
}
|