Version 24.2.2.2, tag libreoffice-24.2.2.2
[LibreOffice.git] / compilerplugins / clang / vclwidgets.cxx
blob422041688a78d298d75e23d5038fb55889014acc
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 "compat.hxx"
17 #include "config_clang.h"
18 #include "clang/AST/CXXInheritance.h"
20 // Final goal: Checker for VCL widget references. Makes sure that VCL Window subclasses are properly referenced counted and dispose()'ed.
22 // But at the moment it just finds subclasses of Window which are not heap-allocated
24 // TODO do I need to check for local and static variables, too ?
25 // TODO when we have a dispose() method, verify that the dispose() methods releases all of the Window references
26 // TODO when we have a dispose() method, verify that it calls the super-class dispose() method at some point.
28 namespace {
30 class VCLWidgets:
31 public loplugin::FilteringPlugin<VCLWidgets>
33 public:
34 explicit VCLWidgets(loplugin::InstantiationData const & data): FilteringPlugin(data)
37 virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
39 bool shouldVisitTemplateInstantiations () const { return true; }
41 bool VisitVarDecl(const VarDecl *);
42 bool VisitFieldDecl(const FieldDecl *);
43 bool VisitParmVarDecl(const ParmVarDecl *);
44 bool VisitFunctionDecl(const FunctionDecl *);
45 bool VisitCXXDestructorDecl(const CXXDestructorDecl *);
46 bool VisitCXXDeleteExpr(const CXXDeleteExpr *);
47 bool VisitCallExpr(const CallExpr *);
48 bool VisitDeclRefExpr(const DeclRefExpr *);
49 bool VisitCXXConstructExpr(const CXXConstructExpr *);
50 bool VisitBinaryOperator(const BinaryOperator *);
51 private:
52 void checkAssignmentForVclPtrToRawConversion(const SourceLocation& sourceLoc, const clang::Type* lhsType, const Expr* rhs);
53 bool isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl);
54 bool mbCheckingMemcpy = false;
57 #define BASE_REF_COUNTED_CLASS "VclReferenceBase"
59 bool BaseCheckNotWindowSubclass(const CXXRecordDecl *BaseDefinition) {
60 return !loplugin::DeclCheck(BaseDefinition).Class(BASE_REF_COUNTED_CLASS)
61 .GlobalNamespace();
64 bool isDerivedFromVclReferenceBase(const CXXRecordDecl *decl) {
65 if (!decl)
66 return false;
67 if (loplugin::DeclCheck(decl).Class(BASE_REF_COUNTED_CLASS)
68 .GlobalNamespace())
70 return true;
72 if (!decl->hasDefinition()) {
73 return false;
75 if (// not sure what hasAnyDependentBases() does,
76 // but it avoids classes we don't want, e.g. WeakAggComponentImplHelper1
77 !decl->hasAnyDependentBases() &&
78 !decl->forallBases(BaseCheckNotWindowSubclass)) {
79 return true;
81 return false;
84 bool containsVclReferenceBaseSubclass(const clang::Type* pType0);
86 bool containsVclReferenceBaseSubclass(const QualType& qType) {
87 auto check = loplugin::TypeCheck(qType);
88 if (check.Class("ScopedVclPtr").GlobalNamespace()
89 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
90 || check.Class("VclPtr").GlobalNamespace()
91 || check.Class("VclPtrInstance").GlobalNamespace())
93 return false;
95 return containsVclReferenceBaseSubclass(qType.getTypePtr());
98 bool containsVclReferenceBaseSubclass(const clang::Type* pType0) {
99 if (!pType0)
100 return false;
101 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
102 if (!pType)
103 return false;
104 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
105 if (pRecordDecl) {
106 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
107 if (pTemplate) {
108 auto check = loplugin::DeclCheck(pTemplate);
109 if (check.Class("VclStatusListener").GlobalNamespace()) {
110 return false;
112 bool link = bool(check.Class("Link").GlobalNamespace());
113 for(unsigned i=0; i<pTemplate->getTemplateArgs().size(); ++i) {
114 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[i];
115 if (rArg.getKind() == TemplateArgument::ArgKind::Type &&
116 containsVclReferenceBaseSubclass(rArg.getAsType()))
118 // OK for first template argument of tools/link.hxx Link
119 // to be a Window-derived pointer:
120 if (!link || i != 0) {
121 return true;
127 if (pType->isPointerType()) {
128 QualType pointeeType = pType->getPointeeType();
129 return containsVclReferenceBaseSubclass(pointeeType);
130 } else if (pType->isArrayType()) {
131 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
132 QualType elementType = pArrayType->getElementType();
133 return containsVclReferenceBaseSubclass(elementType);
134 } else {
135 return isDerivedFromVclReferenceBase(pRecordDecl);
139 bool VCLWidgets::VisitCXXDestructorDecl(const CXXDestructorDecl* pCXXDestructorDecl)
141 if (ignoreLocation(pCXXDestructorDecl)) {
142 return true;
144 if (!pCXXDestructorDecl->isThisDeclarationADefinition()) {
145 return true;
147 const CXXRecordDecl * pRecordDecl = pCXXDestructorDecl->getParent();
148 // ignore
149 if (loplugin::DeclCheck(pRecordDecl).Class(BASE_REF_COUNTED_CLASS)
150 .GlobalNamespace())
152 return true;
154 // check if this class is derived from VclReferenceBase
155 if (!isDerivedFromVclReferenceBase(pRecordDecl)) {
156 return true;
158 // check if we have any VclPtr<> fields
159 bool bFoundVclPtrField = false;
160 for(auto fieldDecl = pRecordDecl->field_begin();
161 fieldDecl != pRecordDecl->field_end(); ++fieldDecl)
163 const RecordType *pFieldRecordType = fieldDecl->getType()->getAs<RecordType>();
164 if (pFieldRecordType) {
165 if (loplugin::DeclCheck(pFieldRecordType->getDecl())
166 .Class("VclPtr").GlobalNamespace())
168 bFoundVclPtrField = true;
169 break;
173 // check if there is a dispose() method
174 bool bFoundDispose = false;
175 for(auto methodDecl = pRecordDecl->method_begin();
176 methodDecl != pRecordDecl->method_end(); ++methodDecl)
178 if (methodDecl->isInstance() && methodDecl->param_size()==0
179 && loplugin::DeclCheck(*methodDecl).Function("dispose"))
181 bFoundDispose = true;
182 break;
185 const CompoundStmt *pCompoundStatement = dyn_cast_or_null<CompoundStmt>(pCXXDestructorDecl->getBody());
186 // having an empty body and no dispose() method is fine
187 if (!bFoundVclPtrField && !bFoundDispose && (!pCompoundStatement || pCompoundStatement->size() == 0)) {
188 return true;
190 if (bFoundVclPtrField && (!pCompoundStatement || pCompoundStatement->size() == 0)) {
191 report(
192 DiagnosticsEngine::Warning,
193 BASE_REF_COUNTED_CLASS " subclass with VclPtr field must call disposeOnce() from its destructor",
194 pCXXDestructorDecl->getBeginLoc())
195 << pCXXDestructorDecl->getSourceRange();
196 return true;
198 // Check that the destructor for a BASE_REF_COUNTED_CLASS subclass either
199 // only calls disposeOnce() or, if !bFoundVclPtrField, does nothing at all:
200 bool bOk = false;
201 if (pCompoundStatement) {
202 bool bFoundDisposeOnce = false;
203 int nNumExtraStatements = 0;
204 for (auto i = pCompoundStatement->body_begin();
205 i != pCompoundStatement->body_end(); ++i)
207 //TODO: The below erroneously also skips past entire statements like
209 // assert(true), ...;
211 auto skip = false;
212 for (auto loc = (*i)->getBeginLoc();
213 compiler.getSourceManager().isMacroBodyExpansion(loc);
214 loc = compiler.getSourceManager().getImmediateMacroCallerLoc(
215 loc))
217 auto const name = Lexer::getImmediateMacroName(
218 loc, compiler.getSourceManager(), compiler.getLangOpts());
219 if (name == "SAL_DEBUG" || name == "assert") {
220 skip = true;
221 break;
224 if (skip) {
225 continue;
227 if (auto const pCallExpr = dyn_cast<CXXMemberCallExpr>(*i)) {
228 if( const FunctionDecl* func = pCallExpr->getDirectCallee()) {
229 if( func->getNumParams() == 0 && func->getIdentifier() != NULL
230 && ( func->getName() == "disposeOnce" )) {
231 bFoundDisposeOnce = true;
232 continue;
236 nNumExtraStatements++;
238 bOk = (bFoundDisposeOnce || !bFoundVclPtrField)
239 && nNumExtraStatements == 0;
241 if (!bOk) {
242 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
243 pCXXDestructorDecl->getBeginLoc());
244 StringRef filename = getFilenameOfLocation(spellingLocation);
245 if ( !(loplugin::isSamePathname(filename, SRCDIR "/vcl/source/window/window.cxx"))
246 && !(loplugin::isSamePathname(filename, SRCDIR "/vcl/source/gdi/virdev.cxx"))
247 && !(loplugin::isSamePathname(filename, SRCDIR "/vcl/qa/cppunit/lifecycle.cxx"))
248 && !(loplugin::isSamePathname(filename, SRCDIR "/sfx2/source/dialog/tabdlg.cxx")) )
250 report(
251 DiagnosticsEngine::Warning,
252 BASE_REF_COUNTED_CLASS " subclass should have nothing in its destructor but a call to disposeOnce()",
253 pCXXDestructorDecl->getBeginLoc())
254 << pCXXDestructorDecl->getSourceRange();
257 return true;
260 bool VCLWidgets::VisitBinaryOperator(const BinaryOperator * binaryOperator)
262 if (ignoreLocation(binaryOperator)) {
263 return true;
265 if ( !binaryOperator->isAssignmentOp() ) {
266 return true;
268 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
269 binaryOperator->getBeginLoc());
270 checkAssignmentForVclPtrToRawConversion(spellingLocation, binaryOperator->getLHS()->getType().getTypePtr(), binaryOperator->getRHS());
271 return true;
274 // Look for places where we are accidentally assigning a returned-by-value VclPtr<T> to a T*, which generally
275 // ends up in a use-after-free.
276 void VCLWidgets::checkAssignmentForVclPtrToRawConversion(const SourceLocation& spellingLocation, const clang::Type* lhsType, const Expr* rhs)
278 if (!lhsType || !isa<clang::PointerType>(lhsType)) {
279 return;
281 if (!rhs) {
282 return;
284 StringRef filename = getFilenameOfLocation(spellingLocation);
285 if (loplugin::isSamePathname(filename, SRCDIR "/include/rtl/ref.hxx")) {
286 return;
288 const CXXRecordDecl* pointeeClass = lhsType->getPointeeType()->getAsCXXRecordDecl();
289 if (!isDerivedFromVclReferenceBase(pointeeClass)) {
290 return;
293 // if we have T* on the LHS and VclPtr<T> on the RHS, we expect to see either
294 // an ImplicitCastExpr
295 // or an ExprWithCleanups and then an ImplicitCastExpr
296 if (auto implicitCastExpr = dyn_cast<ImplicitCastExpr>(rhs)) {
297 if (implicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
298 return;
300 rhs = rhs->IgnoreCasts();
301 } else if (auto exprWithCleanups = dyn_cast<ExprWithCleanups>(rhs)) {
302 if (auto implicitCastExpr = dyn_cast<ImplicitCastExpr>(exprWithCleanups->getSubExpr())) {
303 if (implicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
304 return;
306 rhs = exprWithCleanups->IgnoreCasts();
307 } else {
308 return;
310 } else {
311 return;
313 if (isa<CXXNullPtrLiteralExpr>(rhs)) {
314 return;
316 if (isa<CXXThisExpr>(rhs)) {
317 return;
320 // ignore assignments from a member field to a local variable, to avoid unnecessary refcounting traffic
321 if (auto callExpr = dyn_cast<CXXMemberCallExpr>(rhs)) {
322 if (auto calleeMemberExpr = dyn_cast<MemberExpr>(callExpr->getCallee())) {
323 if ((calleeMemberExpr = dyn_cast<MemberExpr>(calleeMemberExpr->getBase()->IgnoreImpCasts()))) {
324 if (isa<FieldDecl>(calleeMemberExpr->getMemberDecl())) {
325 return;
331 // ignore assignments from a local variable to a local variable, to avoid unnecessary refcounting traffic
332 if (auto callExpr = dyn_cast<CXXMemberCallExpr>(rhs)) {
333 if (auto calleeMemberExpr = dyn_cast<MemberExpr>(callExpr->getCallee())) {
334 if (auto declRefExpr = dyn_cast<DeclRefExpr>(calleeMemberExpr->getBase()->IgnoreImpCasts())) {
335 if (isa<VarDecl>(declRefExpr->getDecl())) {
336 return;
341 if (auto declRefExpr = dyn_cast<DeclRefExpr>(rhs->IgnoreImpCasts())) {
342 if (isa<VarDecl>(declRefExpr->getDecl())) {
343 return;
347 report(
348 DiagnosticsEngine::Warning,
349 "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",
350 rhs->getSourceRange().getBegin())
351 << rhs->getSourceRange();
354 bool VCLWidgets::VisitVarDecl(const VarDecl * pVarDecl) {
355 if (ignoreLocation(pVarDecl)) {
356 return true;
358 if (isa<ParmVarDecl>(pVarDecl)) {
359 return true;
361 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
362 pVarDecl->getBeginLoc());
363 if (pVarDecl->getInit()) {
364 checkAssignmentForVclPtrToRawConversion(spellingLocation, pVarDecl->getType().getTypePtr(), pVarDecl->getInit());
366 StringRef aFileName = getFilenameOfLocation(spellingLocation);
367 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx"))
368 return true;
369 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
370 return true;
371 // allowlist the valid things that can contain pointers.
372 // It is containing stuff like std::unique_ptr we get worried
373 if (pVarDecl->getType()->isArrayType()) {
374 return true;
376 auto tc = loplugin::TypeCheck(pVarDecl->getType());
377 if (tc.Pointer()
378 || tc.Class("map").StdNamespace()
379 || tc.Class("multimap").StdNamespace()
380 || tc.Class("vector").StdNamespace()
381 || tc.Class("list").StdNamespace()
382 || tc.Class("mem_fun1_t").StdNamespace()
383 // registration template thing, doesn't actually allocate anything we need to care about
384 || tc.Class("OMultiInstanceAutoRegistration").Namespace("compmodule").GlobalNamespace())
386 return true;
388 // Apparently I should be doing some kind of lookup for a partial specialisations of std::iterator_traits<T> to see if an
389 // object is an iterator, but that sounds like too much work
390 auto t = pVarDecl->getType().getDesugaredType(compiler.getASTContext());
391 std::string s = t.getAsString();
392 if (s.find("iterator") != std::string::npos
393 || loplugin::TypeCheck(t).Class("__wrap_iter").StdNamespace())
395 return true;
397 // 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
398 // it's an ElaboratedType (whatever that is)
399 if (s.find("pair") != std::string::npos) {
400 return true;
403 if (containsVclReferenceBaseSubclass(pVarDecl->getType())) {
404 report(
405 DiagnosticsEngine::Warning,
406 BASE_REF_COUNTED_CLASS " subclass %0 should be wrapped in VclPtr",
407 pVarDecl->getLocation())
408 << pVarDecl->getType() << pVarDecl->getSourceRange();
409 return true;
411 return true;
414 bool VCLWidgets::VisitFieldDecl(const FieldDecl * fieldDecl) {
415 if (ignoreLocation(fieldDecl)) {
416 return true;
418 StringRef aFileName = getFilenameOfLocation(
419 compiler.getSourceManager().getSpellingLoc(fieldDecl->getBeginLoc()));
420 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx"))
421 return true;
422 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/rtl/ref.hxx"))
423 return true;
424 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/o3tl/enumarray.hxx"))
425 return true;
426 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
427 return true;
428 if (fieldDecl->isBitField()) {
429 return true;
431 const CXXRecordDecl *pParentRecordDecl = isa<RecordDecl>(fieldDecl->getDeclContext()) ? dyn_cast<CXXRecordDecl>(fieldDecl->getParent()) : nullptr;
432 if (loplugin::DeclCheck(pParentRecordDecl).Class("VclPtr")
433 .GlobalNamespace())
435 return true;
437 if (containsVclReferenceBaseSubclass(fieldDecl->getType())) {
438 // have to ignore this for now, nasty reverse dependency from tools->vcl
439 auto check = loplugin::DeclCheck(pParentRecordDecl);
440 if (!(check.Struct("ImplErrorContext").GlobalNamespace()
441 || check.Class("ScHFEditPage").GlobalNamespace()))
443 report(
444 DiagnosticsEngine::Warning,
445 BASE_REF_COUNTED_CLASS " subclass %0 declared as a pointer member, should be wrapped in VclPtr",
446 fieldDecl->getLocation())
447 << fieldDecl->getType() << fieldDecl->getSourceRange();
448 if (auto parent = dyn_cast<ClassTemplateSpecializationDecl>(fieldDecl->getParent())) {
449 report(
450 DiagnosticsEngine::Note,
451 "template field here",
452 parent->getPointOfInstantiation());
454 return true;
457 const RecordType *recordType = fieldDecl->getType()->getAs<RecordType>();
458 if (recordType == nullptr) {
459 return true;
461 const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl());
462 if (recordDecl == nullptr) {
463 return true;
466 // check if this field is derived fromVclReferenceBase
467 if (isDerivedFromVclReferenceBase(recordDecl)) {
468 report(
469 DiagnosticsEngine::Warning,
470 BASE_REF_COUNTED_CLASS " subclass allocated as a class member, should be allocated via VclPtr",
471 fieldDecl->getLocation())
472 << fieldDecl->getSourceRange();
475 // If this field is a VclPtr field, then the class MUST have a dispose method
476 if (pParentRecordDecl && isDerivedFromVclReferenceBase(pParentRecordDecl)
477 && loplugin::DeclCheck(recordDecl).Class("VclPtr").GlobalNamespace())
479 bool bFoundDispose = false;
480 for(auto methodDecl = pParentRecordDecl->method_begin();
481 methodDecl != pParentRecordDecl->method_end(); ++methodDecl)
483 if (methodDecl->isInstance() && methodDecl->param_size()==0
484 && loplugin::DeclCheck(*methodDecl).Function("dispose"))
486 bFoundDispose = true;
487 break;
490 if (!bFoundDispose) {
491 report(
492 DiagnosticsEngine::Warning,
493 BASE_REF_COUNTED_CLASS " subclass with a VclPtr field MUST override dispose() (and call its superclass dispose() as the last thing it does)",
494 fieldDecl->getLocation())
495 << fieldDecl->getSourceRange();
497 if (!pParentRecordDecl->hasUserDeclaredDestructor()) {
498 report(
499 DiagnosticsEngine::Warning,
500 BASE_REF_COUNTED_CLASS " subclass with a VclPtr field MUST have a user-provided destructor (that calls disposeOnce())",
501 fieldDecl->getLocation())
502 << fieldDecl->getSourceRange();
506 return true;
509 bool VCLWidgets::VisitParmVarDecl(ParmVarDecl const * pvDecl)
511 if (ignoreLocation(pvDecl)) {
512 return true;
514 // ignore the stuff in the VclPtr template class
515 const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(pvDecl->getDeclContext());
516 if (loplugin::DeclCheck(pMethodDecl).MemberFunction().Class("VclPtr")
517 .GlobalNamespace())
519 return true;
521 // we exclude this method in VclBuilder because it's so useful to have it like this
522 auto check = loplugin::DeclCheck(pMethodDecl).Function("get");
523 if (check.Class("VclBuilder").GlobalNamespace()
524 || check.Class("VclBuilderContainer").GlobalNamespace())
526 return true;
528 return true;
532 static void findDisposeAndClearStatements(std::set<const FieldDecl*>& aVclPtrFields, const Stmt *pStmt)
534 if (!pStmt)
535 return;
536 if (isa<CompoundStmt>(pStmt)) {
537 const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pStmt);
538 for (auto i = pCompoundStatement->body_begin();
539 i != pCompoundStatement->body_end(); ++i)
541 findDisposeAndClearStatements(aVclPtrFields, *i);
543 return;
545 if (isa<ForStmt>(pStmt)) {
546 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<ForStmt>(pStmt)->getBody());
547 return;
549 if (isa<IfStmt>(pStmt)) {
550 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<IfStmt>(pStmt)->getThen());
551 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<IfStmt>(pStmt)->getElse());
552 return;
554 if (!isa<CallExpr>(pStmt)) return;
555 const CallExpr *pCallExpr = dyn_cast<CallExpr>(pStmt);
557 if (!pCallExpr->getDirectCallee()) return;
558 if (!isa<CXXMethodDecl>(pCallExpr->getDirectCallee())) return;
559 auto check = loplugin::DeclCheck(
560 dyn_cast<CXXMethodDecl>(pCallExpr->getDirectCallee()));
561 if (!(check.Function("disposeAndClear") || check.Function("clear")))
562 return;
564 if (!pCallExpr->getCallee()) return;
566 if (!isa<MemberExpr>(pCallExpr->getCallee())) return;
567 const MemberExpr *pCalleeMemberExpr = dyn_cast<MemberExpr>(pCallExpr->getCallee());
569 if (!pCalleeMemberExpr->getBase()) return;
570 const MemberExpr *pCalleeMemberExprBase = dyn_cast<MemberExpr>(pCalleeMemberExpr->getBase()->IgnoreImpCasts());
571 if (pCalleeMemberExprBase == nullptr) return;
573 const FieldDecl* xxx = dyn_cast_or_null<FieldDecl>(pCalleeMemberExprBase->getMemberDecl());
574 if (xxx)
575 aVclPtrFields.erase(xxx);
579 bool VCLWidgets::VisitFunctionDecl( const FunctionDecl* functionDecl )
581 if (ignoreLocation(functionDecl)) {
582 return true;
584 // ignore the stuff in the VclPtr template class
585 if (loplugin::DeclCheck(functionDecl).MemberFunction().Class("VclPtr")
586 .GlobalNamespace())
588 return true;
590 // ignore the BASE_REF_COUNTED_CLASS::dispose() method
591 if (loplugin::DeclCheck(functionDecl).Function("dispose")
592 .Class(BASE_REF_COUNTED_CLASS).GlobalNamespace())
594 return true;
596 const CXXMethodDecl *pMethodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
597 if (functionDecl->hasBody() && pMethodDecl && isDerivedFromVclReferenceBase(pMethodDecl->getParent())) {
598 // check the last thing that the dispose() method does, is to call into the superclass dispose method
599 if (loplugin::DeclCheck(functionDecl).Function("dispose")) {
600 if (!isDisposeCallingSuperclassDispose(pMethodDecl)) {
601 // We specifically have to clear a member variable AFTER calling super::dispose() here, unfortunately
602 if (!loplugin::DeclCheck(pMethodDecl->getParent()).Class("WindowOutputDevice"))
603 report(
604 DiagnosticsEngine::Warning,
605 BASE_REF_COUNTED_CLASS " subclass dispose() function MUST call dispose() of its superclass as the last thing it does",
606 functionDecl->getBeginLoc())
607 << functionDecl->getSourceRange();
612 // check dispose method to make sure we are actually disposing all of the VclPtr fields
613 // FIXME this is not exhaustive. We should enable shouldVisitTemplateInstantiations and look deeper inside type declarations
614 if (pMethodDecl && pMethodDecl->isInstance() && pMethodDecl->getBody()
615 && pMethodDecl->param_size()==0
616 && loplugin::DeclCheck(functionDecl).Function("dispose")
617 && isDerivedFromVclReferenceBase(pMethodDecl->getParent()) )
619 auto check = loplugin::DeclCheck(functionDecl).MemberFunction();
620 if (check.Class("VirtualDevice").GlobalNamespace()
621 || check.Class("Breadcrumb").GlobalNamespace())
623 return true;
626 std::set<const FieldDecl*> aVclPtrFields;
627 for (auto i = pMethodDecl->getParent()->field_begin();
628 i != pMethodDecl->getParent()->field_end(); ++i)
630 auto const type = loplugin::TypeCheck((*i)->getType());
631 if (type.Class("VclPtr").GlobalNamespace()) {
632 aVclPtrFields.insert(*i);
633 } else if (type.Class("vector").StdNamespace()
634 || type.Class("map").StdNamespace()
635 || type.Class("list").StdNamespace()
636 || type.Class("set").StdNamespace())
638 const RecordType* recordType = dyn_cast_or_null<RecordType>((*i)->getType()->getUnqualifiedDesugaredType());
639 if (recordType) {
640 auto d = dyn_cast<ClassTemplateSpecializationDecl>(recordType->getDecl());
641 if (d && d->getTemplateArgs().size()>0) {
642 auto const type = loplugin::TypeCheck(d->getTemplateArgs()[0].getAsType());
643 if (type.Class("VclPtr").GlobalNamespace()) {
644 aVclPtrFields.insert(*i);
650 if (!aVclPtrFields.empty()) {
651 findDisposeAndClearStatements( aVclPtrFields, pMethodDecl->getBody() );
652 if (!aVclPtrFields.empty()) {
653 //pMethodDecl->dump();
654 std::string aMessage = BASE_REF_COUNTED_CLASS " subclass dispose() method does not call disposeAndClear() or clear() on the following field(s): ";
655 for(auto s : aVclPtrFields)
656 aMessage += ", " + s->getNameAsString();
657 report(
658 DiagnosticsEngine::Warning,
659 aMessage,
660 functionDecl->getBeginLoc())
661 << functionDecl->getSourceRange();
666 return true;
669 bool VCLWidgets::VisitCXXDeleteExpr(const CXXDeleteExpr *pCXXDeleteExpr)
671 if (ignoreLocation(pCXXDeleteExpr)) {
672 return true;
674 const CXXRecordDecl *pPointee = pCXXDeleteExpr->getArgument()->getType()->getPointeeCXXRecordDecl();
675 if (pPointee && isDerivedFromVclReferenceBase(pPointee)) {
676 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
677 pCXXDeleteExpr->getBeginLoc());
678 StringRef filename = getFilenameOfLocation(spellingLocation);
679 if ( !(loplugin::isSamePathname(filename, SRCDIR "/include/vcl/vclreferencebase.hxx")))
681 report(
682 DiagnosticsEngine::Warning,
683 "calling delete on instance of " BASE_REF_COUNTED_CLASS " subclass, must rather call disposeAndClear()",
684 pCXXDeleteExpr->getBeginLoc())
685 << pCXXDeleteExpr->getSourceRange();
688 const ImplicitCastExpr* pImplicitCastExpr = dyn_cast<ImplicitCastExpr>(pCXXDeleteExpr->getArgument());
689 if (!pImplicitCastExpr) {
690 return true;
692 if (pImplicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
693 return true;
695 if (!loplugin::TypeCheck(pImplicitCastExpr->getSubExprAsWritten()->getType()).Class("VclPtr")
696 .GlobalNamespace())
698 return true;
700 report(
701 DiagnosticsEngine::Warning,
702 "calling delete on instance of VclPtr, must rather call disposeAndClear()",
703 pCXXDeleteExpr->getBeginLoc())
704 << pCXXDeleteExpr->getSourceRange();
705 return true;
710 The AST looks like:
711 `-CXXMemberCallExpr 0xb06d8b0 'void'
712 `-MemberExpr 0xb06d868 '<bound member function type>' ->dispose 0x9d34880
713 `-ImplicitCastExpr 0xb06d8d8 'class SfxTabPage *' <UncheckedDerivedToBase (SfxTabPage)>
714 `-CXXThisExpr 0xb06d850 'class SfxAcceleratorConfigPage *' this
717 bool VCLWidgets::isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl)
719 const CompoundStmt *pCompoundStatement = dyn_cast<CompoundStmt>(pMethodDecl->getBody());
720 if (!pCompoundStatement) return false;
721 if (pCompoundStatement->size() == 0) return false;
722 // find the last statement
723 const CXXMemberCallExpr *pCallExpr = dyn_cast<CXXMemberCallExpr>(*pCompoundStatement->body_rbegin());
724 if (!pCallExpr) return false;
725 const MemberExpr *pMemberExpr = dyn_cast<MemberExpr>(pCallExpr->getCallee());
726 if (!pMemberExpr) return false;
727 if (!loplugin::DeclCheck(pMemberExpr->getMemberDecl()).Function("dispose")) return false;
728 const CXXMethodDecl *pDirectCallee = dyn_cast<CXXMethodDecl>(pCallExpr->getDirectCallee());
729 if (!pDirectCallee) return false;
730 /* Not working yet. Partially because sometimes the superclass does not a dispose() method, so it gets passed up the chain.
731 Need complex checking for that case.
732 if (pDirectCallee->getParent()->getTypeForDecl() != (*pMethodDecl->getParent()->bases_begin()).getType().getTypePtr()) {
733 report(
734 DiagnosticsEngine::Warning,
735 "dispose() method calling wrong baseclass, calling " + pDirectCallee->getParent()->getQualifiedNameAsString() +
736 " should be calling " + (*pMethodDecl->getParent()->bases_begin()).getType().getAsString(),
737 pCallExpr->getLocStart())
738 << pCallExpr->getSourceRange();
739 return false;
741 return true;
744 bool containsVclPtr(const clang::Type* pType0);
746 bool containsVclPtr(const QualType& qType) {
747 auto check = loplugin::TypeCheck(qType);
748 if (check.Class("ScopedVclPtr").GlobalNamespace()
749 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
750 || check.Class("VclPtr").GlobalNamespace()
751 || check.Class("VclPtrInstance").GlobalNamespace())
753 return true;
755 return containsVclPtr(qType.getTypePtr());
758 bool containsVclPtr(const clang::Type* pType0) {
759 if (!pType0)
760 return false;
761 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
762 if (!pType)
763 return false;
764 if (pType->isPointerType()) {
765 return false;
766 } else if (pType->isArrayType()) {
767 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
768 QualType elementType = pArrayType->getElementType();
769 return containsVclPtr(elementType);
770 } else {
771 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
772 if (pRecordDecl)
774 auto check = loplugin::DeclCheck(pRecordDecl);
775 if (check.Class("ScopedVclPtr").GlobalNamespace()
776 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
777 || check.Class("VclPtr").GlobalNamespace()
778 || check.Class("VclPtrInstance").GlobalNamespace())
780 return true;
782 for(auto fieldDecl = pRecordDecl->field_begin();
783 fieldDecl != pRecordDecl->field_end(); ++fieldDecl)
785 const RecordType *pFieldRecordType = fieldDecl->getType()->getAs<RecordType>();
786 if (pFieldRecordType && containsVclPtr(pFieldRecordType)) {
787 return true;
790 for(auto baseSpecifier = pRecordDecl->bases_begin();
791 baseSpecifier != pRecordDecl->bases_end(); ++baseSpecifier)
793 const RecordType *pFieldRecordType = baseSpecifier->getType()->getAs<RecordType>();
794 if (pFieldRecordType && containsVclPtr(pFieldRecordType)) {
795 return true;
800 return false;
803 bool VCLWidgets::VisitCallExpr(const CallExpr* pCallExpr)
805 if (ignoreLocation(pCallExpr)) {
806 return true;
808 FunctionDecl const * fdecl = pCallExpr->getDirectCallee();
809 if (fdecl == nullptr) {
810 return true;
812 std::string qname { fdecl->getQualifiedNameAsString() };
813 if (qname.find("memcpy") == std::string::npos
814 && qname.find("bcopy") == std::string::npos
815 && qname.find("memmove") == std::string::npos
816 && qname.find("rtl_copy") == std::string::npos) {
817 return true;
819 mbCheckingMemcpy = true;
820 Stmt * pStmt = const_cast<Stmt*>(static_cast<const Stmt*>(pCallExpr->getArg(0)));
821 TraverseStmt(pStmt);
822 mbCheckingMemcpy = false;
823 return true;
826 bool VCLWidgets::VisitDeclRefExpr(const DeclRefExpr* pDeclRefExpr)
828 if (!mbCheckingMemcpy) {
829 return true;
831 if (ignoreLocation(pDeclRefExpr)) {
832 return true;
834 QualType pType = pDeclRefExpr->getDecl()->getType();
835 if (pType->isPointerType()) {
836 pType = pType->getPointeeType();
838 if (!containsVclPtr(pType)) {
839 return true;
841 report(
842 DiagnosticsEngine::Warning,
843 "Calling memcpy on a type which contains a VclPtr",
844 pDeclRefExpr->getExprLoc());
845 return true;
848 bool VCLWidgets::VisitCXXConstructExpr( const CXXConstructExpr* constructExpr )
850 if (ignoreLocation(constructExpr)) {
851 return true;
853 if (constructExpr->getConstructionKind() != compat::CXXConstructionKind::Complete) {
854 return true;
856 const CXXConstructorDecl* pConstructorDecl = constructExpr->getConstructor();
857 const CXXRecordDecl* recordDecl = pConstructorDecl->getParent();
858 if (isDerivedFromVclReferenceBase(recordDecl)) {
859 StringRef aFileName = getFilenameOfLocation(
860 compiler.getSourceManager().getSpellingLoc(constructExpr->getBeginLoc()));
861 if (!loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx")) {
862 report(
863 DiagnosticsEngine::Warning,
864 "Calling constructor of a VclReferenceBase-derived type directly; all such creation should go via VclPtr<>::Create",
865 constructExpr->getExprLoc());
868 return true;
871 loplugin::Plugin::Registration< VCLWidgets > vclwidgets("vclwidgets");
875 // Cannot be shared, uses TraverseStmt().
877 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */