replace usage of whitelist with allowlist
[LibreOffice.git] / compilerplugins / clang / vclwidgets.cxx
blob61805ff5ad031829c014c1ad391ea4a69e7715de
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <memory>
11 #include <string>
12 #include <iostream>
14 #include "plugin.hxx"
15 #include "check.hxx"
16 #include "clang/AST/CXXInheritance.h"
18 // Final goal: Checker for VCL widget references. Makes sure that VCL Window subclasses are properly referenced counted and dispose()'ed.
20 // But at the moment it just finds subclasses of Window which are not heap-allocated
22 // TODO do I need to check for local and static variables, too ?
23 // TODO when we have a dispose() method, verify that the dispose() methods releases all of the Window references
24 // TODO when we have a dispose() method, verify that it calls the super-class dispose() method at some point.
26 namespace {
28 class VCLWidgets:
29 public loplugin::FilteringPlugin<VCLWidgets>
31 public:
32 explicit VCLWidgets(loplugin::InstantiationData const & data): FilteringPlugin(data)
35 virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
37 bool shouldVisitTemplateInstantiations () const { return true; }
39 bool VisitVarDecl(const VarDecl *);
40 bool VisitFieldDecl(const FieldDecl *);
41 bool VisitParmVarDecl(const ParmVarDecl *);
42 bool VisitFunctionDecl(const FunctionDecl *);
43 bool VisitCXXDestructorDecl(const CXXDestructorDecl *);
44 bool VisitCXXDeleteExpr(const CXXDeleteExpr *);
45 bool VisitCallExpr(const CallExpr *);
46 bool VisitDeclRefExpr(const DeclRefExpr *);
47 bool VisitCXXConstructExpr(const CXXConstructExpr *);
48 bool VisitBinaryOperator(const BinaryOperator *);
49 private:
50 void checkAssignmentForVclPtrToRawConversion(const SourceLocation& sourceLoc, const clang::Type* lhsType, const Expr* rhs);
51 bool isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl);
52 bool mbCheckingMemcpy = false;
55 #define BASE_REF_COUNTED_CLASS "VclReferenceBase"
57 bool BaseCheckNotWindowSubclass(const CXXRecordDecl *BaseDefinition) {
58 return !loplugin::DeclCheck(BaseDefinition).Class(BASE_REF_COUNTED_CLASS)
59 .GlobalNamespace();
62 bool isDerivedFromVclReferenceBase(const CXXRecordDecl *decl) {
63 if (!decl)
64 return false;
65 if (loplugin::DeclCheck(decl).Class(BASE_REF_COUNTED_CLASS)
66 .GlobalNamespace())
68 return true;
70 if (!decl->hasDefinition()) {
71 return false;
73 if (// not sure what hasAnyDependentBases() does,
74 // but it avoids classes we don't want, e.g. WeakAggComponentImplHelper1
75 !decl->hasAnyDependentBases() &&
76 !decl->forallBases(BaseCheckNotWindowSubclass)) {
77 return true;
79 return false;
82 bool containsVclReferenceBaseSubclass(const clang::Type* pType0);
84 bool containsVclReferenceBaseSubclass(const QualType& qType) {
85 auto check = loplugin::TypeCheck(qType);
86 if (check.Class("ScopedVclPtr").GlobalNamespace()
87 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
88 || check.Class("VclPtr").GlobalNamespace()
89 || check.Class("VclPtrInstance").GlobalNamespace())
91 return false;
93 return containsVclReferenceBaseSubclass(qType.getTypePtr());
96 bool containsVclReferenceBaseSubclass(const clang::Type* pType0) {
97 if (!pType0)
98 return false;
99 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
100 if (!pType)
101 return false;
102 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
103 if (pRecordDecl) {
104 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
105 if (pTemplate) {
106 auto check = loplugin::DeclCheck(pTemplate);
107 if (check.Class("VclStatusListener").GlobalNamespace()) {
108 return false;
110 bool link = bool(check.Class("Link").GlobalNamespace());
111 for(unsigned i=0; i<pTemplate->getTemplateArgs().size(); ++i) {
112 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[i];
113 if (rArg.getKind() == TemplateArgument::ArgKind::Type &&
114 containsVclReferenceBaseSubclass(rArg.getAsType()))
116 // OK for first template argument of tools/link.hxx Link
117 // to be a Window-derived pointer:
118 if (!link || i != 0) {
119 return true;
125 if (pType->isPointerType()) {
126 QualType pointeeType = pType->getPointeeType();
127 return containsVclReferenceBaseSubclass(pointeeType);
128 } else if (pType->isArrayType()) {
129 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
130 QualType elementType = pArrayType->getElementType();
131 return containsVclReferenceBaseSubclass(elementType);
132 } else {
133 return isDerivedFromVclReferenceBase(pRecordDecl);
137 bool VCLWidgets::VisitCXXDestructorDecl(const CXXDestructorDecl* pCXXDestructorDecl)
139 if (ignoreLocation(pCXXDestructorDecl)) {
140 return true;
142 if (!pCXXDestructorDecl->isThisDeclarationADefinition()) {
143 return true;
145 const CXXRecordDecl * pRecordDecl = pCXXDestructorDecl->getParent();
146 // ignore
147 if (loplugin::DeclCheck(pRecordDecl).Class(BASE_REF_COUNTED_CLASS)
148 .GlobalNamespace())
150 return true;
152 // check if this class is derived from VclReferenceBase
153 if (!isDerivedFromVclReferenceBase(pRecordDecl)) {
154 return true;
156 // check if we have any VclPtr<> fields
157 bool bFoundVclPtrField = false;
158 for(auto fieldDecl = pRecordDecl->field_begin();
159 fieldDecl != pRecordDecl->field_end(); ++fieldDecl)
161 const RecordType *pFieldRecordType = fieldDecl->getType()->getAs<RecordType>();
162 if (pFieldRecordType) {
163 if (loplugin::DeclCheck(pFieldRecordType->getDecl())
164 .Class("VclPtr").GlobalNamespace())
166 bFoundVclPtrField = true;
167 break;
171 // check if there is a dispose() method
172 bool bFoundDispose = false;
173 for(auto methodDecl = pRecordDecl->method_begin();
174 methodDecl != pRecordDecl->method_end(); ++methodDecl)
176 if (methodDecl->isInstance() && methodDecl->param_size()==0
177 && loplugin::DeclCheck(*methodDecl).Function("dispose"))
179 bFoundDispose = true;
180 break;
183 const CompoundStmt *pCompoundStatement = dyn_cast_or_null<CompoundStmt>(pCXXDestructorDecl->getBody());
184 // having an empty body and no dispose() method is fine
185 if (!bFoundVclPtrField && !bFoundDispose && (!pCompoundStatement || pCompoundStatement->size() == 0)) {
186 return true;
188 if (bFoundVclPtrField && (!pCompoundStatement || pCompoundStatement->size() == 0)) {
189 report(
190 DiagnosticsEngine::Warning,
191 BASE_REF_COUNTED_CLASS " subclass with VclPtr field must call disposeOnce() from its destructor",
192 compat::getBeginLoc(pCXXDestructorDecl))
193 << pCXXDestructorDecl->getSourceRange();
194 return true;
196 // Check that the destructor for a BASE_REF_COUNTED_CLASS subclass either
197 // only calls disposeOnce() or, if !bFoundVclPtrField, does nothing at all:
198 bool bOk = false;
199 if (pCompoundStatement) {
200 bool bFoundDisposeOnce = false;
201 int nNumExtraStatements = 0;
202 for (auto i = pCompoundStatement->body_begin();
203 i != pCompoundStatement->body_end(); ++i)
205 //TODO: The below erroneously also skips past entire statements like
207 // assert(true), ...;
209 auto skip = false;
210 for (auto loc = compat::getBeginLoc(*i);
211 compiler.getSourceManager().isMacroBodyExpansion(loc);
212 loc = compiler.getSourceManager().getImmediateMacroCallerLoc(
213 loc))
215 auto const name = Lexer::getImmediateMacroName(
216 loc, compiler.getSourceManager(), compiler.getLangOpts());
217 if (name == "SAL_DEBUG" || name == "assert") {
218 skip = true;
219 break;
222 if (skip) {
223 continue;
225 if (auto const pCallExpr = dyn_cast<CXXMemberCallExpr>(*i)) {
226 if( const FunctionDecl* func = pCallExpr->getDirectCallee()) {
227 if( func->getNumParams() == 0 && func->getIdentifier() != NULL
228 && ( func->getName() == "disposeOnce" )) {
229 bFoundDisposeOnce = true;
230 continue;
234 nNumExtraStatements++;
236 bOk = (bFoundDisposeOnce || !bFoundVclPtrField)
237 && nNumExtraStatements == 0;
239 if (!bOk) {
240 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
241 compat::getBeginLoc(pCXXDestructorDecl));
242 StringRef filename = getFilenameOfLocation(spellingLocation);
243 if ( !(loplugin::isSamePathname(filename, SRCDIR "/vcl/source/window/window.cxx"))
244 && !(loplugin::isSamePathname(filename, SRCDIR "/vcl/source/gdi/virdev.cxx"))
245 && !(loplugin::isSamePathname(filename, SRCDIR "/vcl/qa/cppunit/lifecycle.cxx"))
246 && !(loplugin::isSamePathname(filename, SRCDIR "/sfx2/source/dialog/tabdlg.cxx")) )
248 report(
249 DiagnosticsEngine::Warning,
250 BASE_REF_COUNTED_CLASS " subclass should have nothing in its destructor but a call to disposeOnce()",
251 compat::getBeginLoc(pCXXDestructorDecl))
252 << pCXXDestructorDecl->getSourceRange();
255 return true;
258 bool VCLWidgets::VisitBinaryOperator(const BinaryOperator * binaryOperator)
260 if (ignoreLocation(binaryOperator)) {
261 return true;
263 if ( !binaryOperator->isAssignmentOp() ) {
264 return true;
266 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
267 compat::getBeginLoc(binaryOperator));
268 checkAssignmentForVclPtrToRawConversion(spellingLocation, binaryOperator->getLHS()->getType().getTypePtr(), binaryOperator->getRHS());
269 return true;
272 // Look for places where we are accidentally assigning a returned-by-value VclPtr<T> to a T*, which generally
273 // ends up in a use-after-free.
274 void VCLWidgets::checkAssignmentForVclPtrToRawConversion(const SourceLocation& spellingLocation, const clang::Type* lhsType, const Expr* rhs)
276 if (!lhsType || !isa<clang::PointerType>(lhsType)) {
277 return;
279 if (!rhs) {
280 return;
282 StringRef filename = getFilenameOfLocation(spellingLocation);
283 if (loplugin::isSamePathname(filename, SRCDIR "/include/rtl/ref.hxx")) {
284 return;
286 const CXXRecordDecl* pointeeClass = lhsType->getPointeeType()->getAsCXXRecordDecl();
287 if (!isDerivedFromVclReferenceBase(pointeeClass)) {
288 return;
291 // if we have T* on the LHS and VclPtr<T> on the RHS, we expect to see either
292 // an ImplicitCastExpr
293 // or an ExprWithCleanups and then an ImplicitCastExpr
294 if (auto implicitCastExpr = dyn_cast<ImplicitCastExpr>(rhs)) {
295 if (implicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
296 return;
298 rhs = rhs->IgnoreCasts();
299 } else if (auto exprWithCleanups = dyn_cast<ExprWithCleanups>(rhs)) {
300 if (auto implicitCastExpr = dyn_cast<ImplicitCastExpr>(exprWithCleanups->getSubExpr())) {
301 if (implicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
302 return;
304 rhs = exprWithCleanups->IgnoreCasts();
305 } else {
306 return;
308 } else {
309 return;
311 if (isa<CXXNullPtrLiteralExpr>(rhs)) {
312 return;
314 if (isa<CXXThisExpr>(rhs)) {
315 return;
318 // ignore assignments from a member field to a local variable, to avoid unnecessary refcounting traffic
319 if (auto callExpr = dyn_cast<CXXMemberCallExpr>(rhs)) {
320 if (auto calleeMemberExpr = dyn_cast<MemberExpr>(callExpr->getCallee())) {
321 if ((calleeMemberExpr = dyn_cast<MemberExpr>(calleeMemberExpr->getBase()->IgnoreImpCasts()))) {
322 if (isa<FieldDecl>(calleeMemberExpr->getMemberDecl())) {
323 return;
329 // ignore assignments from a local variable to a local variable, to avoid unnecessary refcounting traffic
330 if (auto callExpr = dyn_cast<CXXMemberCallExpr>(rhs)) {
331 if (auto calleeMemberExpr = dyn_cast<MemberExpr>(callExpr->getCallee())) {
332 if (auto declRefExpr = dyn_cast<DeclRefExpr>(calleeMemberExpr->getBase()->IgnoreImpCasts())) {
333 if (isa<VarDecl>(declRefExpr->getDecl())) {
334 return;
339 if (auto declRefExpr = dyn_cast<DeclRefExpr>(rhs->IgnoreImpCasts())) {
340 if (isa<VarDecl>(declRefExpr->getDecl())) {
341 return;
345 report(
346 DiagnosticsEngine::Warning,
347 "assigning a returned-by-value VclPtr<T> to a T* variable is dodgy, should be assigned to a VclPtr. If you know that the RHS does not return a newly created T, then add a '.get()' to the RHS",
348 rhs->getSourceRange().getBegin())
349 << rhs->getSourceRange();
352 bool VCLWidgets::VisitVarDecl(const VarDecl * pVarDecl) {
353 if (ignoreLocation(pVarDecl)) {
354 return true;
356 if (isa<ParmVarDecl>(pVarDecl)) {
357 return true;
359 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
360 compat::getBeginLoc(pVarDecl));
361 if (pVarDecl->getInit()) {
362 checkAssignmentForVclPtrToRawConversion(spellingLocation, pVarDecl->getType().getTypePtr(), pVarDecl->getInit());
364 StringRef aFileName = getFilenameOfLocation(spellingLocation);
365 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx"))
366 return true;
367 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
368 return true;
369 // allowlist the valid things that can contain pointers.
370 // It is containing stuff like std::unique_ptr we get worried
371 if (pVarDecl->getType()->isArrayType()) {
372 return true;
374 auto tc = loplugin::TypeCheck(pVarDecl->getType());
375 if (tc.Pointer()
376 || tc.Class("map").StdNamespace()
377 || tc.Class("multimap").StdNamespace()
378 || tc.Class("vector").StdNamespace()
379 || tc.Class("list").StdNamespace()
380 || tc.Class("mem_fun1_t").StdNamespace()
381 // registration template thing, doesn't actually allocate anything we need to care about
382 || tc.Class("OMultiInstanceAutoRegistration").Namespace("compmodule").GlobalNamespace())
384 return true;
386 // Apparently I should be doing some kind of lookup for a partial specialisations of std::iterator_traits<T> to see if an
387 // object is an iterator, but that sounds like too much work
388 auto t = pVarDecl->getType().getDesugaredType(compiler.getASTContext());
389 std::string s = t.getAsString();
390 if (s.find("iterator") != std::string::npos
391 || loplugin::TypeCheck(t).Class("__wrap_iter").StdNamespace())
393 return true;
395 // std::pair seems to show up in whacky ways in clang's AST. Sometimes it's a class, sometimes it's a typedef, and sometimes
396 // it's an ElaboratedType (whatever that is)
397 if (s.find("pair") != std::string::npos) {
398 return true;
401 if (containsVclReferenceBaseSubclass(pVarDecl->getType())) {
402 report(
403 DiagnosticsEngine::Warning,
404 BASE_REF_COUNTED_CLASS " subclass %0 should be wrapped in VclPtr",
405 pVarDecl->getLocation())
406 << pVarDecl->getType() << pVarDecl->getSourceRange();
407 return true;
409 return true;
412 bool VCLWidgets::VisitFieldDecl(const FieldDecl * fieldDecl) {
413 if (ignoreLocation(fieldDecl)) {
414 return true;
416 StringRef aFileName = getFilenameOfLocation(
417 compiler.getSourceManager().getSpellingLoc(compat::getBeginLoc(fieldDecl)));
418 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx"))
419 return true;
420 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/rtl/ref.hxx"))
421 return true;
422 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/o3tl/enumarray.hxx"))
423 return true;
424 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
425 return true;
426 if (fieldDecl->isBitField()) {
427 return true;
429 const CXXRecordDecl *pParentRecordDecl = isa<RecordDecl>(fieldDecl->getDeclContext()) ? dyn_cast<CXXRecordDecl>(fieldDecl->getParent()) : nullptr;
430 if (loplugin::DeclCheck(pParentRecordDecl).Class("VclPtr")
431 .GlobalNamespace())
433 return true;
435 if (containsVclReferenceBaseSubclass(fieldDecl->getType())) {
436 // have to ignore this for now, nasty reverse dependency from tools->vcl
437 auto check = loplugin::DeclCheck(pParentRecordDecl);
438 if (!(check.Struct("ImplErrorContext").GlobalNamespace()
439 || check.Class("ScHFEditPage").GlobalNamespace()))
441 report(
442 DiagnosticsEngine::Warning,
443 BASE_REF_COUNTED_CLASS " subclass %0 declared as a pointer member, should be wrapped in VclPtr",
444 fieldDecl->getLocation())
445 << fieldDecl->getType() << fieldDecl->getSourceRange();
446 if (auto parent = dyn_cast<ClassTemplateSpecializationDecl>(fieldDecl->getParent())) {
447 report(
448 DiagnosticsEngine::Note,
449 "template field here",
450 parent->getPointOfInstantiation());
452 return true;
455 const RecordType *recordType = fieldDecl->getType()->getAs<RecordType>();
456 if (recordType == nullptr) {
457 return true;
459 const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl());
460 if (recordDecl == nullptr) {
461 return true;
464 // check if this field is derived fromVclReferenceBase
465 if (isDerivedFromVclReferenceBase(recordDecl)) {
466 report(
467 DiagnosticsEngine::Warning,
468 BASE_REF_COUNTED_CLASS " subclass allocated as a class member, should be allocated via VclPtr",
469 fieldDecl->getLocation())
470 << fieldDecl->getSourceRange();
473 // If this field is a VclPtr field, then the class MUST have a dispose method
474 if (pParentRecordDecl && isDerivedFromVclReferenceBase(pParentRecordDecl)
475 && loplugin::DeclCheck(recordDecl).Class("VclPtr").GlobalNamespace())
477 bool bFoundDispose = false;
478 for(auto methodDecl = pParentRecordDecl->method_begin();
479 methodDecl != pParentRecordDecl->method_end(); ++methodDecl)
481 if (methodDecl->isInstance() && methodDecl->param_size()==0
482 && loplugin::DeclCheck(*methodDecl).Function("dispose"))
484 bFoundDispose = true;
485 break;
488 if (!bFoundDispose) {
489 report(
490 DiagnosticsEngine::Warning,
491 BASE_REF_COUNTED_CLASS " subclass with a VclPtr field MUST override dispose() (and call its superclass dispose() as the last thing it does)",
492 fieldDecl->getLocation())
493 << fieldDecl->getSourceRange();
495 if (!pParentRecordDecl->hasUserDeclaredDestructor()) {
496 report(
497 DiagnosticsEngine::Warning,
498 BASE_REF_COUNTED_CLASS " subclass with a VclPtr field MUST have a user-provided destructor (that calls disposeOnce())",
499 fieldDecl->getLocation())
500 << fieldDecl->getSourceRange();
504 return true;
507 bool VCLWidgets::VisitParmVarDecl(ParmVarDecl const * pvDecl)
509 if (ignoreLocation(pvDecl)) {
510 return true;
512 // ignore the stuff in the VclPtr template class
513 const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(pvDecl->getDeclContext());
514 if (loplugin::DeclCheck(pMethodDecl).MemberFunction().Class("VclPtr")
515 .GlobalNamespace())
517 return true;
519 // we exclude this method in VclBuilder because it's so useful to have it like this
520 auto check = loplugin::DeclCheck(pMethodDecl).Function("get");
521 if (check.Class("VclBuilder").GlobalNamespace()
522 || check.Class("VclBuilderContainer").GlobalNamespace())
524 return true;
526 return true;
530 static void findDisposeAndClearStatements(std::set<const FieldDecl*>& aVclPtrFields, const Stmt *pStmt)
532 if (!pStmt)
533 return;
534 if (isa<CompoundStmt>(pStmt)) {
535 const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pStmt);
536 for (auto i = pCompoundStatement->body_begin();
537 i != pCompoundStatement->body_end(); ++i)
539 findDisposeAndClearStatements(aVclPtrFields, *i);
541 return;
543 if (isa<ForStmt>(pStmt)) {
544 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<ForStmt>(pStmt)->getBody());
545 return;
547 if (isa<IfStmt>(pStmt)) {
548 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<IfStmt>(pStmt)->getThen());
549 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<IfStmt>(pStmt)->getElse());
550 return;
552 if (!isa<CallExpr>(pStmt)) return;
553 const CallExpr *pCallExpr = dyn_cast<CallExpr>(pStmt);
555 if (!pCallExpr->getDirectCallee()) return;
556 if (!isa<CXXMethodDecl>(pCallExpr->getDirectCallee())) return;
557 auto check = loplugin::DeclCheck(
558 dyn_cast<CXXMethodDecl>(pCallExpr->getDirectCallee()));
559 if (!(check.Function("disposeAndClear") || check.Function("clear")))
560 return;
562 if (!pCallExpr->getCallee()) return;
564 if (!isa<MemberExpr>(pCallExpr->getCallee())) return;
565 const MemberExpr *pCalleeMemberExpr = dyn_cast<MemberExpr>(pCallExpr->getCallee());
567 if (!pCalleeMemberExpr->getBase()) return;
568 const MemberExpr *pCalleeMemberExprBase = dyn_cast<MemberExpr>(pCalleeMemberExpr->getBase()->IgnoreImpCasts());
569 if (pCalleeMemberExprBase == nullptr) return;
571 const FieldDecl* xxx = dyn_cast_or_null<FieldDecl>(pCalleeMemberExprBase->getMemberDecl());
572 if (xxx)
573 aVclPtrFields.erase(xxx);
577 bool VCLWidgets::VisitFunctionDecl( const FunctionDecl* functionDecl )
579 if (ignoreLocation(functionDecl)) {
580 return true;
582 // ignore the stuff in the VclPtr template class
583 if (loplugin::DeclCheck(functionDecl).MemberFunction().Class("VclPtr")
584 .GlobalNamespace())
586 return true;
588 // ignore the BASE_REF_COUNTED_CLASS::dispose() method
589 if (loplugin::DeclCheck(functionDecl).Function("dispose")
590 .Class(BASE_REF_COUNTED_CLASS).GlobalNamespace())
592 return true;
594 const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
595 if (functionDecl->hasBody() && pMethodDecl && isDerivedFromVclReferenceBase(pMethodDecl->getParent())) {
596 // check the last thing that the dispose() method does, is to call into the superclass dispose method
597 if (loplugin::DeclCheck(functionDecl).Function("dispose")) {
598 if (!isDisposeCallingSuperclassDispose(pMethodDecl)) {
599 report(
600 DiagnosticsEngine::Warning,
601 BASE_REF_COUNTED_CLASS " subclass dispose() function MUST call dispose() of its superclass as the last thing it does",
602 compat::getBeginLoc(functionDecl))
603 << functionDecl->getSourceRange();
608 // check dispose method to make sure we are actually disposing all of the VclPtr fields
609 // FIXME this is not exhaustive. We should enable shouldVisitTemplateInstantiations and look deeper inside type declarations
610 if (pMethodDecl && pMethodDecl->isInstance() && pMethodDecl->getBody()
611 && pMethodDecl->param_size()==0
612 && loplugin::DeclCheck(functionDecl).Function("dispose")
613 && isDerivedFromVclReferenceBase(pMethodDecl->getParent()) )
615 auto check = loplugin::DeclCheck(functionDecl).MemberFunction();
616 if (check.Class("VirtualDevice").GlobalNamespace()
617 || check.Class("Breadcrumb").GlobalNamespace())
619 return true;
622 std::set<const FieldDecl*> aVclPtrFields;
623 for (auto i = pMethodDecl->getParent()->field_begin();
624 i != pMethodDecl->getParent()->field_end(); ++i)
626 auto const type = loplugin::TypeCheck((*i)->getType());
627 if (type.Class("VclPtr").GlobalNamespace()) {
628 aVclPtrFields.insert(*i);
629 } else if (type.Class("vector").StdNamespace()
630 || type.Class("map").StdNamespace()
631 || type.Class("list").StdNamespace()
632 || type.Class("set").StdNamespace())
634 const RecordType* recordType = dyn_cast_or_null<RecordType>((*i)->getType()->getUnqualifiedDesugaredType());
635 if (recordType) {
636 auto d = dyn_cast<ClassTemplateSpecializationDecl>(recordType->getDecl());
637 if (d && d->getTemplateArgs().size()>0) {
638 auto const type = loplugin::TypeCheck(d->getTemplateArgs()[0].getAsType());
639 if (type.Class("VclPtr").GlobalNamespace()) {
640 aVclPtrFields.insert(*i);
646 if (!aVclPtrFields.empty()) {
647 findDisposeAndClearStatements( aVclPtrFields, pMethodDecl->getBody() );
648 if (!aVclPtrFields.empty()) {
649 //pMethodDecl->dump();
650 std::string aMessage = BASE_REF_COUNTED_CLASS " subclass dispose() method does not call disposeAndClear() or clear() on the following field(s): ";
651 for(auto s : aVclPtrFields)
652 aMessage += ", " + s->getNameAsString();
653 report(
654 DiagnosticsEngine::Warning,
655 aMessage,
656 compat::getBeginLoc(functionDecl))
657 << functionDecl->getSourceRange();
662 return true;
665 bool VCLWidgets::VisitCXXDeleteExpr(const CXXDeleteExpr *pCXXDeleteExpr)
667 if (ignoreLocation(pCXXDeleteExpr)) {
668 return true;
670 const CXXRecordDecl *pPointee = pCXXDeleteExpr->getArgument()->getType()->getPointeeCXXRecordDecl();
671 if (pPointee && isDerivedFromVclReferenceBase(pPointee)) {
672 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
673 compat::getBeginLoc(pCXXDeleteExpr));
674 StringRef filename = getFilenameOfLocation(spellingLocation);
675 if ( !(loplugin::isSamePathname(filename, SRCDIR "/include/vcl/vclreferencebase.hxx")))
677 report(
678 DiagnosticsEngine::Warning,
679 "calling delete on instance of " BASE_REF_COUNTED_CLASS " subclass, must rather call disposeAndClear()",
680 compat::getBeginLoc(pCXXDeleteExpr))
681 << pCXXDeleteExpr->getSourceRange();
684 const ImplicitCastExpr* pImplicitCastExpr = dyn_cast<ImplicitCastExpr>(pCXXDeleteExpr->getArgument());
685 if (!pImplicitCastExpr) {
686 return true;
688 if (pImplicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
689 return true;
691 if (!loplugin::TypeCheck(pImplicitCastExpr->getSubExprAsWritten()->getType()).Class("VclPtr")
692 .GlobalNamespace())
694 return true;
696 report(
697 DiagnosticsEngine::Warning,
698 "calling delete on instance of VclPtr, must rather call disposeAndClear()",
699 compat::getBeginLoc(pCXXDeleteExpr))
700 << pCXXDeleteExpr->getSourceRange();
701 return true;
706 The AST looks like:
707 `-CXXMemberCallExpr 0xb06d8b0 'void'
708 `-MemberExpr 0xb06d868 '<bound member function type>' ->dispose 0x9d34880
709 `-ImplicitCastExpr 0xb06d8d8 'class SfxTabPage *' <UncheckedDerivedToBase (SfxTabPage)>
710 `-CXXThisExpr 0xb06d850 'class SfxAcceleratorConfigPage *' this
713 bool VCLWidgets::isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl)
715 const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pMethodDecl->getBody());
716 if (!pCompoundStatement) return false;
717 if (pCompoundStatement->size() == 0) return false;
718 // find the last statement
719 const CXXMemberCallExpr *pCallExpr = dyn_cast<CXXMemberCallExpr>(*pCompoundStatement->body_rbegin());
720 if (!pCallExpr) return false;
721 const MemberExpr *pMemberExpr = dyn_cast<MemberExpr>(pCallExpr->getCallee());
722 if (!pMemberExpr) return false;
723 if (!loplugin::DeclCheck(pMemberExpr->getMemberDecl()).Function("dispose")) return false;
724 const CXXMethodDecl *pDirectCallee = dyn_cast<CXXMethodDecl>(pCallExpr->getDirectCallee());
725 if (!pDirectCallee) return false;
726 /* Not working yet. Partially because sometimes the superclass does not a dispose() method, so it gets passed up the chain.
727 Need complex checking for that case.
728 if (pDirectCallee->getParent()->getTypeForDecl() != (*pMethodDecl->getParent()->bases_begin()).getType().getTypePtr()) {
729 report(
730 DiagnosticsEngine::Warning,
731 "dispose() method calling wrong baseclass, calling " + pDirectCallee->getParent()->getQualifiedNameAsString() +
732 " should be calling " + (*pMethodDecl->getParent()->bases_begin()).getType().getAsString(),
733 pCallExpr->getLocStart())
734 << pCallExpr->getSourceRange();
735 return false;
737 return true;
740 bool containsVclPtr(const clang::Type* pType0);
742 bool containsVclPtr(const QualType& qType) {
743 auto check = loplugin::TypeCheck(qType);
744 if (check.Class("ScopedVclPtr").GlobalNamespace()
745 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
746 || check.Class("VclPtr").GlobalNamespace()
747 || check.Class("VclPtrInstance").GlobalNamespace())
749 return true;
751 return containsVclPtr(qType.getTypePtr());
754 bool containsVclPtr(const clang::Type* pType0) {
755 if (!pType0)
756 return false;
757 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
758 if (!pType)
759 return false;
760 if (pType->isPointerType()) {
761 return false;
762 } else if (pType->isArrayType()) {
763 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
764 QualType elementType = pArrayType->getElementType();
765 return containsVclPtr(elementType);
766 } else {
767 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
768 if (pRecordDecl)
770 auto check = loplugin::DeclCheck(pRecordDecl);
771 if (check.Class("ScopedVclPtr").GlobalNamespace()
772 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
773 || check.Class("VclPtr").GlobalNamespace()
774 || check.Class("VclPtrInstance").GlobalNamespace())
776 return true;
778 for(auto fieldDecl = pRecordDecl->field_begin();
779 fieldDecl != pRecordDecl->field_end(); ++fieldDecl)
781 const RecordType *pFieldRecordType = fieldDecl->getType()->getAs<RecordType>();
782 if (pFieldRecordType && containsVclPtr(pFieldRecordType)) {
783 return true;
786 for(auto baseSpecifier = pRecordDecl->bases_begin();
787 baseSpecifier != pRecordDecl->bases_end(); ++baseSpecifier)
789 const RecordType *pFieldRecordType = baseSpecifier->getType()->getAs<RecordType>();
790 if (pFieldRecordType && containsVclPtr(pFieldRecordType)) {
791 return true;
796 return false;
799 bool VCLWidgets::VisitCallExpr(const CallExpr* pCallExpr)
801 if (ignoreLocation(pCallExpr)) {
802 return true;
804 FunctionDecl const * fdecl = pCallExpr->getDirectCallee();
805 if (fdecl == nullptr) {
806 return true;
808 std::string qname { fdecl->getQualifiedNameAsString() };
809 if (qname.find("memcpy") == std::string::npos
810 && qname.find("bcopy") == std::string::npos
811 && qname.find("memmove") == std::string::npos
812 && qname.find("rtl_copy") == std::string::npos) {
813 return true;
815 mbCheckingMemcpy = true;
816 Stmt * pStmt = const_cast<Stmt*>(static_cast<const Stmt*>(pCallExpr->getArg(0)));
817 TraverseStmt(pStmt);
818 mbCheckingMemcpy = false;
819 return true;
822 bool VCLWidgets::VisitDeclRefExpr(const DeclRefExpr* pDeclRefExpr)
824 if (!mbCheckingMemcpy) {
825 return true;
827 if (ignoreLocation(pDeclRefExpr)) {
828 return true;
830 QualType pType = pDeclRefExpr->getDecl()->getType();
831 if (pType->isPointerType()) {
832 pType = pType->getPointeeType();
834 if (!containsVclPtr(pType)) {
835 return true;
837 report(
838 DiagnosticsEngine::Warning,
839 "Calling memcpy on a type which contains a VclPtr",
840 pDeclRefExpr->getExprLoc());
841 return true;
844 bool VCLWidgets::VisitCXXConstructExpr( const CXXConstructExpr* constructExpr )
846 if (ignoreLocation(constructExpr)) {
847 return true;
849 if (constructExpr->getConstructionKind() != CXXConstructExpr::CK_Complete) {
850 return true;
852 const CXXConstructorDecl* pConstructorDecl = constructExpr->getConstructor();
853 const CXXRecordDecl* recordDecl = pConstructorDecl->getParent();
854 if (isDerivedFromVclReferenceBase(recordDecl)) {
855 StringRef aFileName = getFilenameOfLocation(
856 compiler.getSourceManager().getSpellingLoc(compat::getBeginLoc(constructExpr)));
857 if (!loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx")) {
858 report(
859 DiagnosticsEngine::Warning,
860 "Calling constructor of a VclReferenceBase-derived type directly; all such creation should go via VclPtr<>::Create",
861 constructExpr->getExprLoc());
864 return true;
867 loplugin::Plugin::Registration< VCLWidgets > vclwidgets("vclwidgets");
871 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */