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
|
//=======- RefCntblBaseVirtualDtor.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/CXXInheritance.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/StmtVisitor.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 "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include <optional>
using namespace clang;
using namespace ento;
namespace {
class DerefFuncDeleteExprVisitor
: public ConstStmtVisitor<DerefFuncDeleteExprVisitor, bool> {
// Returns true if any of child statements return true.
bool VisitChildren(const Stmt *S) {
for (const Stmt *Child : S->children()) {
if (Child && Visit(Child))
return true;
}
return false;
}
bool VisitBody(const Stmt *Body) {
if (!Body)
return false;
auto [It, IsNew] = VisitedBody.insert(Body);
if (!IsNew) // This body is recursive
return false;
return Visit(Body);
}
public:
DerefFuncDeleteExprVisitor(const TemplateArgumentList &ArgList,
const CXXRecordDecl *ClassDecl)
: ArgList(&ArgList), ClassDecl(ClassDecl) {}
DerefFuncDeleteExprVisitor(const CXXRecordDecl *ClassDecl)
: ClassDecl(ClassDecl) {}
std::optional<bool> HasSpecializedDelete(CXXMethodDecl *Decl) {
if (auto *Body = Decl->getBody())
return VisitBody(Body);
if (Decl->getTemplateInstantiationPattern())
return std::nullopt; // Indeterminate. There was no concrete instance.
return false;
}
bool VisitCallExpr(const CallExpr *CE) {
const Decl *D = CE->getCalleeDecl();
if (D && D->hasBody())
return VisitBody(D->getBody());
else {
auto name = safeGetName(D);
if (name == "ensureOnMainThread" || name == "ensureOnMainRunLoop") {
for (unsigned i = 0; i < CE->getNumArgs(); ++i) {
auto *Arg = CE->getArg(i);
if (VisitLambdaArgument(Arg))
return true;
}
}
}
return false;
}
bool VisitLambdaArgument(const Expr *E) {
E = E->IgnoreParenCasts();
if (auto *TempE = dyn_cast<CXXBindTemporaryExpr>(E))
E = TempE->getSubExpr();
E = E->IgnoreParenCasts();
if (auto *Ref = dyn_cast<DeclRefExpr>(E)) {
if (auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()))
return VisitLambdaArgument(VD->getInit());
return false;
}
if (auto *Lambda = dyn_cast<LambdaExpr>(E)) {
if (VisitBody(Lambda->getBody()))
return true;
}
if (auto *ConstructE = dyn_cast<CXXConstructExpr>(E)) {
for (unsigned i = 0; i < ConstructE->getNumArgs(); ++i) {
if (VisitLambdaArgument(ConstructE->getArg(i)))
return true;
}
}
return false;
}
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
auto *Arg = E->getArgument();
while (Arg) {
if (auto *Paren = dyn_cast<ParenExpr>(Arg))
Arg = Paren->getSubExpr();
else if (auto *Cast = dyn_cast<CastExpr>(Arg)) {
Arg = Cast->getSubExpr();
auto CastType = Cast->getType();
if (auto *PtrType = dyn_cast<PointerType>(CastType)) {
auto PointeeType = PtrType->getPointeeType();
while (auto *ET = dyn_cast<ElaboratedType>(PointeeType)) {
if (ET->isSugared())
PointeeType = ET->desugar();
}
if (auto *ParmType = dyn_cast<TemplateTypeParmType>(PointeeType)) {
if (ArgList) {
auto ParmIndex = ParmType->getIndex();
auto Type = ArgList->get(ParmIndex).getAsType();
if (Type->getAsCXXRecordDecl() == ClassDecl)
return true;
}
} else if (auto *RD = dyn_cast<RecordType>(PointeeType)) {
if (RD->getDecl() == ClassDecl)
return true;
} else if (auto *ST =
dyn_cast<SubstTemplateTypeParmType>(PointeeType)) {
auto Type = ST->getReplacementType();
if (auto *RD = dyn_cast<RecordType>(Type)) {
if (RD->getDecl() == ClassDecl)
return true;
}
}
}
} else
break;
}
return false;
}
bool VisitStmt(const Stmt *S) { return VisitChildren(S); }
// Return false since the contents of lambda isn't necessarily executed.
// If it is executed, VisitCallExpr above will visit its body.
bool VisitLambdaExpr(const LambdaExpr *) { return false; }
private:
const TemplateArgumentList *ArgList{nullptr};
const CXXRecordDecl *ClassDecl;
llvm::DenseSet<const Stmt *> VisitedBody;
};
class RefCntblBaseVirtualDtorChecker
: public Checker<check::ASTDecl<TranslationUnitDecl>> {
private:
BugType Bug;
mutable BugReporter *BR;
public:
RefCntblBaseVirtualDtorChecker()
: Bug(this,
"Reference-countable base class doesn't have virtual destructor",
"WebKit coding guidelines") {}
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 RefCntblBaseVirtualDtorChecker *Checker;
explicit LocalVisitor(const RefCntblBaseVirtualDtorChecker *Checker)
: Checker(Checker) {
assert(Checker);
ShouldVisitTemplateInstantiations = true;
ShouldVisitImplicitCode = false;
}
bool VisitCXXRecordDecl(CXXRecordDecl *RD) override {
if (!RD->hasDefinition())
return true;
Decls.insert(RD);
for (auto &Base : RD->bases()) {
const auto AccSpec = Base.getAccessSpecifier();
if (AccSpec == AS_protected || AccSpec == AS_private ||
(AccSpec == AS_none && RD->isClass()))
continue;
QualType T = Base.getType();
if (T.isNull())
continue;
const CXXRecordDecl *C = T->getAsCXXRecordDecl();
if (!C)
continue;
if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(C)) {
for (auto &Arg : CTSD->getTemplateArgs().asArray()) {
if (Arg.getKind() != TemplateArgument::Type)
continue;
auto TemplT = Arg.getAsType();
if (TemplT.isNull())
continue;
bool IsCRTP = TemplT->getAsCXXRecordDecl() == RD;
if (!IsCRTP)
continue;
CRTPs.insert(C);
}
}
}
return true;
}
llvm::SetVector<const CXXRecordDecl *> Decls;
llvm::DenseSet<const CXXRecordDecl *> CRTPs;
};
LocalVisitor visitor(this);
visitor.TraverseDecl(const_cast<TranslationUnitDecl *>(TUD));
for (auto *RD : visitor.Decls) {
if (visitor.CRTPs.contains(RD))
continue;
visitCXXRecordDecl(RD);
}
}
void visitCXXRecordDecl(const CXXRecordDecl *RD) const {
if (shouldSkipDecl(RD))
return;
for (auto &Base : RD->bases()) {
const auto AccSpec = Base.getAccessSpecifier();
if (AccSpec == AS_protected || AccSpec == AS_private ||
(AccSpec == AS_none && RD->isClass()))
continue;
auto hasRefInBase = clang::hasPublicMethodInBase(&Base, "ref");
auto hasDerefInBase = clang::hasPublicMethodInBase(&Base, "deref");
bool hasRef = hasRefInBase && *hasRefInBase != nullptr;
bool hasDeref = hasDerefInBase && *hasDerefInBase != nullptr;
QualType T = Base.getType();
if (T.isNull())
continue;
const CXXRecordDecl *C = T->getAsCXXRecordDecl();
if (!C)
continue;
bool AnyInconclusiveBase = false;
const auto hasPublicRefInBase =
[&AnyInconclusiveBase](const CXXBaseSpecifier *Base, CXXBasePath &) {
auto hasRefInBase = clang::hasPublicMethodInBase(Base, "ref");
if (!hasRefInBase) {
AnyInconclusiveBase = true;
return false;
}
return (*hasRefInBase) != nullptr;
};
const auto hasPublicDerefInBase =
[&AnyInconclusiveBase](const CXXBaseSpecifier *Base, CXXBasePath &) {
auto hasDerefInBase = clang::hasPublicMethodInBase(Base, "deref");
if (!hasDerefInBase) {
AnyInconclusiveBase = true;
return false;
}
return (*hasDerefInBase) != nullptr;
};
CXXBasePaths Paths;
Paths.setOrigin(C);
hasRef = hasRef || C->lookupInBases(hasPublicRefInBase, Paths,
/*LookupInDependent =*/true);
hasDeref = hasDeref || C->lookupInBases(hasPublicDerefInBase, Paths,
/*LookupInDependent =*/true);
if (AnyInconclusiveBase || !hasRef || !hasDeref)
continue;
auto HasSpecializedDelete = isClassWithSpecializedDelete(C, RD);
if (!HasSpecializedDelete || *HasSpecializedDelete)
continue;
if (C->lookupInBases(
[&](const CXXBaseSpecifier *Base, CXXBasePath &) {
auto *T = Base->getType().getTypePtrOrNull();
if (!T)
return false;
auto *R = T->getAsCXXRecordDecl();
if (!R)
return false;
auto Result = isClassWithSpecializedDelete(R, RD);
if (!Result)
AnyInconclusiveBase = true;
return Result && *Result;
},
Paths, /*LookupInDependent =*/true))
continue;
if (AnyInconclusiveBase)
continue;
const auto *Dtor = C->getDestructor();
if (!Dtor || !Dtor->isVirtual()) {
auto *ProblematicBaseSpecifier = &Base;
auto *ProblematicBaseClass = C;
reportBug(RD, ProblematicBaseSpecifier, ProblematicBaseClass);
}
}
}
bool shouldSkipDecl(const CXXRecordDecl *RD) const {
if (!RD->isThisDeclarationADefinition())
return true;
if (RD->isImplicit())
return true;
if (RD->isLambda())
return true;
// If the construct doesn't have a source file, then it's not something
// we want to diagnose.
const auto RDLocation = RD->getLocation();
if (!RDLocation.isValid())
return true;
const auto Kind = RD->getTagKind();
if (Kind != TagTypeKind::Struct && Kind != TagTypeKind::Class)
return true;
// Ignore CXXRecords that come from system headers.
if (BR->getSourceManager().getFileCharacteristic(RDLocation) !=
SrcMgr::C_User)
return true;
return false;
}
static bool isRefCountedClass(const CXXRecordDecl *D) {
if (!D->getTemplateInstantiationPattern())
return false;
auto *NsDecl = D->getParent();
if (!NsDecl || !isa<NamespaceDecl>(NsDecl))
return false;
auto NamespaceName = safeGetName(NsDecl);
auto ClsNameStr = safeGetName(D);
StringRef ClsName = ClsNameStr; // FIXME: Make safeGetName return StringRef.
return NamespaceName == "WTF" &&
(ClsName.ends_with("RefCounted") ||
ClsName == "ThreadSafeRefCountedAndCanMakeThreadSafeWeakPtr");
}
static std::optional<bool>
isClassWithSpecializedDelete(const CXXRecordDecl *C,
const CXXRecordDecl *DerivedClass) {
if (auto *ClsTmplSpDecl = dyn_cast<ClassTemplateSpecializationDecl>(C)) {
for (auto *MethodDecl : C->methods()) {
if (safeGetName(MethodDecl) == "deref") {
DerefFuncDeleteExprVisitor Visitor(ClsTmplSpDecl->getTemplateArgs(),
DerivedClass);
auto Result = Visitor.HasSpecializedDelete(MethodDecl);
if (!Result || *Result)
return Result;
}
}
return false;
}
for (auto *MethodDecl : C->methods()) {
if (safeGetName(MethodDecl) == "deref") {
DerefFuncDeleteExprVisitor Visitor(DerivedClass);
auto Result = Visitor.HasSpecializedDelete(MethodDecl);
if (!Result || *Result)
return Result;
}
}
return false;
}
void reportBug(const CXXRecordDecl *DerivedClass,
const CXXBaseSpecifier *BaseSpec,
const CXXRecordDecl *ProblematicBaseClass) const {
assert(DerivedClass);
assert(BaseSpec);
assert(ProblematicBaseClass);
SmallString<100> Buf;
llvm::raw_svector_ostream Os(Buf);
Os << (ProblematicBaseClass->isClass() ? "Class" : "Struct") << " ";
printQuotedQualifiedName(Os, ProblematicBaseClass);
Os << " is used as a base of "
<< (DerivedClass->isClass() ? "class" : "struct") << " ";
printQuotedQualifiedName(Os, DerivedClass);
Os << " but doesn't have virtual destructor";
PathDiagnosticLocation BSLoc(BaseSpec->getSourceRange().getBegin(),
BR->getSourceManager());
auto Report = std::make_unique<BasicBugReport>(Bug, Os.str(), BSLoc);
Report->addRange(BaseSpec->getSourceRange());
BR->emitReport(std::move(Report));
}
};
} // namespace
void ento::registerRefCntblBaseVirtualDtorChecker(CheckerManager &Mgr) {
Mgr.registerChecker<RefCntblBaseVirtualDtorChecker>();
}
bool ento::shouldRegisterRefCntblBaseVirtualDtorChecker(
const CheckerManager &mgr) {
return true;
}
|