1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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/.
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.
29 public RecursiveASTVisitor
<VCLWidgets
>, public loplugin::Plugin
32 explicit VCLWidgets(loplugin::InstantiationData
const & data
): Plugin(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
*);
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
)
62 bool isDerivedFromVclReferenceBase(const CXXRecordDecl
*decl
) {
65 if (loplugin::DeclCheck(decl
).Class(BASE_REF_COUNTED_CLASS
)
70 if (!decl
->hasDefinition()) {
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
, true)) {
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())
93 return containsVclReferenceBaseSubclass(qType
.getTypePtr());
96 bool containsVclReferenceBaseSubclass(const clang::Type
* pType0
) {
99 const clang::Type
* pType
= pType0
->getUnqualifiedDesugaredType();
102 const CXXRecordDecl
* pRecordDecl
= pType
->getAsCXXRecordDecl();
104 const ClassTemplateSpecializationDecl
* pTemplate
= dyn_cast
<ClassTemplateSpecializationDecl
>(pRecordDecl
);
106 auto check
= loplugin::DeclCheck(pTemplate
);
107 if (check
.Class("VclStatusListener").GlobalNamespace()) {
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) {
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
);
133 return isDerivedFromVclReferenceBase(pRecordDecl
);
137 bool VCLWidgets::VisitCXXDestructorDecl(const CXXDestructorDecl
* pCXXDestructorDecl
)
139 if (ignoreLocation(pCXXDestructorDecl
)) {
142 if (!pCXXDestructorDecl
->isThisDeclarationADefinition()) {
145 const CXXRecordDecl
* pRecordDecl
= pCXXDestructorDecl
->getParent();
147 if (loplugin::DeclCheck(pRecordDecl
).Class(BASE_REF_COUNTED_CLASS
)
152 // check if this class is derived from VclReferenceBase
153 if (!isDerivedFromVclReferenceBase(pRecordDecl
)) {
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;
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;
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)) {
188 if (bFoundVclPtrField
&& (!pCompoundStatement
|| pCompoundStatement
->size() == 0)) {
190 DiagnosticsEngine::Warning
,
191 BASE_REF_COUNTED_CLASS
" subclass with VclPtr field must call disposeOnce() from its destructor",
192 pCXXDestructorDecl
->getLocStart())
193 << pCXXDestructorDecl
->getSourceRange();
196 // Check that the destructor for a BASE_REF_COUNTED_CLASS subclass either
197 // only calls disposeOnce() or, if !bFoundVclPtrField, does nothing at all:
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), ...;
210 for (auto loc
= (*i
)->getLocStart();
211 compiler
.getSourceManager().isMacroBodyExpansion(loc
);
212 loc
= compiler
.getSourceManager().getImmediateMacroCallerLoc(
215 auto const name
= Lexer::getImmediateMacroName(
216 loc
, compiler
.getSourceManager(), compiler
.getLangOpts());
217 if (name
== "SAL_DEBUG" || name
== "assert") {
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;
234 nNumExtraStatements
++;
236 bOk
= (bFoundDisposeOnce
|| !bFoundVclPtrField
)
237 && nNumExtraStatements
== 0;
240 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
241 pCXXDestructorDecl
->getLocStart());
242 StringRef filename
= compiler
.getSourceManager().getFilename(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")) )
248 DiagnosticsEngine::Warning
,
249 BASE_REF_COUNTED_CLASS
" subclass should have nothing in its destructor but a call to disposeOnce()",
250 pCXXDestructorDecl
->getLocStart())
251 << pCXXDestructorDecl
->getSourceRange();
257 bool VCLWidgets::VisitBinaryOperator(const BinaryOperator
* binaryOperator
)
259 if (ignoreLocation(binaryOperator
)) {
262 if ( !binaryOperator
->isAssignmentOp() ) {
265 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
266 binaryOperator
->getLocStart());
267 checkAssignmentForVclPtrToRawConversion(spellingLocation
, binaryOperator
->getLHS()->getType().getTypePtr(), binaryOperator
->getRHS());
271 // Look for places where we are accidentally assigning a returned-by-value VclPtr<T> to a T*, which generally
272 // ends up in a use-after-free.
273 void VCLWidgets::checkAssignmentForVclPtrToRawConversion(const SourceLocation
& spellingLocation
, const clang::Type
* lhsType
, const Expr
* rhs
)
275 if (!lhsType
|| !isa
<clang::PointerType
>(lhsType
)) {
281 StringRef filename
= compiler
.getSourceManager().getFilename(spellingLocation
);
282 if (loplugin::isSamePathname(filename
, SRCDIR
"/include/rtl/ref.hxx")) {
285 const CXXRecordDecl
* pointeeClass
= lhsType
->getPointeeType()->getAsCXXRecordDecl();
286 if (!isDerivedFromVclReferenceBase(pointeeClass
)) {
290 // if we have T* on the LHS and VclPtr<T> on the RHS, we expect to see either
291 // an ImplicitCastExpr
292 // or a ExprWithCleanups and then an ImplicitCastExpr
293 if (auto implicitCastExpr
= dyn_cast
<ImplicitCastExpr
>(rhs
)) {
294 if (implicitCastExpr
->getCastKind() != CK_UserDefinedConversion
) {
297 rhs
= rhs
->IgnoreCasts();
298 } else if (auto exprWithCleanups
= dyn_cast
<ExprWithCleanups
>(rhs
)) {
299 if (auto implicitCastExpr
= dyn_cast
<ImplicitCastExpr
>(exprWithCleanups
->getSubExpr())) {
300 if (implicitCastExpr
->getCastKind() != CK_UserDefinedConversion
) {
303 rhs
= exprWithCleanups
->IgnoreCasts();
310 if (isa
<CXXNullPtrLiteralExpr
>(rhs
)) {
313 if (isa
<CXXThisExpr
>(rhs
)) {
317 // ignore assignments from a member field to a local variable, to avoid unnecessary refcounting traffic
318 if (auto callExpr
= dyn_cast
<CXXMemberCallExpr
>(rhs
)) {
319 if (auto calleeMemberExpr
= dyn_cast
<MemberExpr
>(callExpr
->getCallee())) {
320 if ((calleeMemberExpr
= dyn_cast
<MemberExpr
>(calleeMemberExpr
->getBase()->IgnoreImpCasts()))) {
321 if (isa
<FieldDecl
>(calleeMemberExpr
->getMemberDecl())) {
328 // ignore assignments from a local variable to a local variable, to avoid unnecessary refcounting traffic
329 if (auto callExpr
= dyn_cast
<CXXMemberCallExpr
>(rhs
)) {
330 if (auto calleeMemberExpr
= dyn_cast
<MemberExpr
>(callExpr
->getCallee())) {
331 if (auto declRefExpr
= dyn_cast
<DeclRefExpr
>(calleeMemberExpr
->getBase()->IgnoreImpCasts())) {
332 if (isa
<VarDecl
>(declRefExpr
->getDecl())) {
338 if (auto declRefExpr
= dyn_cast
<DeclRefExpr
>(rhs
->IgnoreImpCasts())) {
339 if (isa
<VarDecl
>(declRefExpr
->getDecl())) {
345 DiagnosticsEngine::Warning
,
346 "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",
347 rhs
->getSourceRange().getBegin())
348 << rhs
->getSourceRange();
351 bool VCLWidgets::VisitVarDecl(const VarDecl
* pVarDecl
) {
352 if (ignoreLocation(pVarDecl
)) {
355 if (isa
<ParmVarDecl
>(pVarDecl
)) {
358 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
359 pVarDecl
->getLocStart());
360 if (pVarDecl
->getInit()) {
361 checkAssignmentForVclPtrToRawConversion(spellingLocation
, pVarDecl
->getType().getTypePtr(), pVarDecl
->getInit());
363 StringRef aFileName
= compiler
.getSourceManager().getFilename(spellingLocation
);
364 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/vcl/vclptr.hxx"))
366 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/vcl/source/window/layout.cxx"))
368 // whitelist the valid things that can contain pointers.
369 // It is containing stuff like std::unique_ptr we get worried
370 if (pVarDecl
->getType()->isArrayType()) {
373 auto tc
= loplugin::TypeCheck(pVarDecl
->getType());
375 || tc
.Class("map").StdNamespace()
376 || tc
.Class("multimap").StdNamespace()
377 || tc
.Class("vector").StdNamespace()
378 || tc
.Class("list").StdNamespace()
379 || tc
.Class("mem_fun1_t").StdNamespace()
380 // registration template thing, doesn't actually allocate anything we need to care about
381 || tc
.Class("OMultiInstanceAutoRegistration").Namespace("compmodule").GlobalNamespace())
385 // Apparently I should be doing some kind of lookup for a partial specialisations of std::iterator_traits<T> to see if an
386 // object is an iterator, but that sounds like too much work
387 auto t
= pVarDecl
->getType().getDesugaredType(compiler
.getASTContext());
388 std::string s
= t
.getAsString();
389 if (s
.find("iterator") != std::string::npos
390 || loplugin::TypeCheck(t
).Class("__wrap_iter").StdNamespace())
394 // 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
395 // its an ElaboratedType (whatever that is)
396 if (s
.find("pair") != std::string::npos
) {
400 if (containsVclReferenceBaseSubclass(pVarDecl
->getType())) {
402 DiagnosticsEngine::Warning
,
403 BASE_REF_COUNTED_CLASS
" subclass %0 should be wrapped in VclPtr",
404 pVarDecl
->getLocation())
405 << pVarDecl
->getType() << pVarDecl
->getSourceRange();
411 bool VCLWidgets::VisitFieldDecl(const FieldDecl
* fieldDecl
) {
412 if (ignoreLocation(fieldDecl
)) {
415 StringRef aFileName
= compiler
.getSourceManager().getFilename(compiler
.getSourceManager().getSpellingLoc(fieldDecl
->getLocStart()));
416 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/vcl/vclptr.hxx"))
418 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/rtl/ref.hxx"))
420 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/o3tl/enumarray.hxx"))
422 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/vcl/source/window/layout.cxx"))
424 if (fieldDecl
->isBitField()) {
427 const CXXRecordDecl
*pParentRecordDecl
= isa
<RecordDecl
>(fieldDecl
->getDeclContext()) ? dyn_cast
<CXXRecordDecl
>(fieldDecl
->getParent()) : nullptr;
428 if (loplugin::DeclCheck(pParentRecordDecl
).Class("VclPtr")
433 if (containsVclReferenceBaseSubclass(fieldDecl
->getType())) {
434 // have to ignore this for now, nasty reverse dependency from tools->vcl
435 auto check
= loplugin::DeclCheck(pParentRecordDecl
);
436 if (!(check
.Struct("ImplErrorContext").GlobalNamespace()
437 || check
.Class("ScHFEditPage").GlobalNamespace()))
440 DiagnosticsEngine::Warning
,
441 BASE_REF_COUNTED_CLASS
" subclass %0 declared as a pointer member, should be wrapped in VclPtr",
442 fieldDecl
->getLocation())
443 << fieldDecl
->getType() << fieldDecl
->getSourceRange();
444 if (auto parent
= dyn_cast
<ClassTemplateSpecializationDecl
>(fieldDecl
->getParent())) {
446 DiagnosticsEngine::Note
,
447 "template field here",
448 parent
->getPointOfInstantiation());
453 const RecordType
*recordType
= fieldDecl
->getType()->getAs
<RecordType
>();
454 if (recordType
== nullptr) {
457 const CXXRecordDecl
*recordDecl
= dyn_cast
<CXXRecordDecl
>(recordType
->getDecl());
458 if (recordDecl
== nullptr) {
462 // check if this field is derived fromVclReferenceBase
463 if (isDerivedFromVclReferenceBase(recordDecl
)) {
465 DiagnosticsEngine::Warning
,
466 BASE_REF_COUNTED_CLASS
" subclass allocated as a class member, should be allocated via VclPtr",
467 fieldDecl
->getLocation())
468 << fieldDecl
->getSourceRange();
471 // If this field is a VclPtr field, then the class MUST have a dispose method
472 if (pParentRecordDecl
&& isDerivedFromVclReferenceBase(pParentRecordDecl
)
473 && loplugin::DeclCheck(recordDecl
).Class("VclPtr").GlobalNamespace())
475 bool bFoundDispose
= false;
476 for(auto methodDecl
= pParentRecordDecl
->method_begin();
477 methodDecl
!= pParentRecordDecl
->method_end(); ++methodDecl
)
479 if (methodDecl
->isInstance() && methodDecl
->param_size()==0
480 && loplugin::DeclCheck(*methodDecl
).Function("dispose"))
482 bFoundDispose
= true;
486 if (!bFoundDispose
) {
488 DiagnosticsEngine::Warning
,
489 BASE_REF_COUNTED_CLASS
" subclass with a VclPtr field MUST override dispose() (and call its superclass dispose() as the last thing it does)",
490 fieldDecl
->getLocation())
491 << fieldDecl
->getSourceRange();
493 if (!pParentRecordDecl
->hasUserDeclaredDestructor()) {
495 DiagnosticsEngine::Warning
,
496 BASE_REF_COUNTED_CLASS
" subclass with a VclPtr field MUST have a user-provided destructor (that calls disposeOnce())",
497 fieldDecl
->getLocation())
498 << fieldDecl
->getSourceRange();
505 bool VCLWidgets::VisitParmVarDecl(ParmVarDecl
const * pvDecl
)
507 if (ignoreLocation(pvDecl
)) {
510 // ignore the stuff in the VclPtr template class
511 const CXXMethodDecl
*pMethodDecl
= dyn_cast
<CXXMethodDecl
>(pvDecl
->getDeclContext());
512 if (loplugin::DeclCheck(pMethodDecl
).MemberFunction().Class("VclPtr")
517 // we exclude this method in VclBuilder because it's so useful to have it like this
518 auto check
= loplugin::DeclCheck(pMethodDecl
).Function("get");
519 if (check
.Class("VclBuilder").GlobalNamespace()
520 || check
.Class("VclBuilderContainer").GlobalNamespace())
528 static void findDisposeAndClearStatements(std::set
<const FieldDecl
*>& aVclPtrFields
, const Stmt
*pStmt
)
532 if (isa
<CompoundStmt
>(pStmt
)) {
533 const CompoundStmt
*pCompoundStatement
= dyn_cast
<CompoundStmt
>(pStmt
);
534 for (auto i
= pCompoundStatement
->body_begin();
535 i
!= pCompoundStatement
->body_end(); ++i
)
537 findDisposeAndClearStatements(aVclPtrFields
, *i
);
541 if (isa
<ForStmt
>(pStmt
)) {
542 findDisposeAndClearStatements(aVclPtrFields
, dyn_cast
<ForStmt
>(pStmt
)->getBody());
545 if (isa
<IfStmt
>(pStmt
)) {
546 findDisposeAndClearStatements(aVclPtrFields
, dyn_cast
<IfStmt
>(pStmt
)->getThen());
547 findDisposeAndClearStatements(aVclPtrFields
, dyn_cast
<IfStmt
>(pStmt
)->getElse());
550 if (!isa
<CallExpr
>(pStmt
)) return;
551 const CallExpr
*pCallExpr
= dyn_cast
<CallExpr
>(pStmt
);
553 if (!pCallExpr
->getDirectCallee()) return;
554 if (!isa
<CXXMethodDecl
>(pCallExpr
->getDirectCallee())) return;
555 auto check
= loplugin::DeclCheck(
556 dyn_cast
<CXXMethodDecl
>(pCallExpr
->getDirectCallee()));
557 if (!(check
.Function("disposeAndClear") || check
.Function("clear")))
560 if (!pCallExpr
->getCallee()) return;
562 if (!isa
<MemberExpr
>(pCallExpr
->getCallee())) return;
563 const MemberExpr
*pCalleeMemberExpr
= dyn_cast
<MemberExpr
>(pCallExpr
->getCallee());
565 if (!pCalleeMemberExpr
->getBase()) return;
566 const MemberExpr
*pCalleeMemberExprBase
= dyn_cast
<MemberExpr
>(pCalleeMemberExpr
->getBase()->IgnoreImpCasts());
567 if (pCalleeMemberExprBase
== nullptr) return;
569 const FieldDecl
* xxx
= dyn_cast_or_null
<FieldDecl
>(pCalleeMemberExprBase
->getMemberDecl());
571 aVclPtrFields
.erase(xxx
);
575 bool VCLWidgets::VisitFunctionDecl( const FunctionDecl
* functionDecl
)
577 if (ignoreLocation(functionDecl
)) {
580 // ignore the stuff in the VclPtr template class
581 if (loplugin::DeclCheck(functionDecl
).MemberFunction().Class("VclPtr")
586 // ignore the BASE_REF_COUNTED_CLASS::dispose() method
587 if (loplugin::DeclCheck(functionDecl
).Function("dispose")
588 .Class(BASE_REF_COUNTED_CLASS
).GlobalNamespace())
592 const CXXMethodDecl
*pMethodDecl
= dyn_cast
<CXXMethodDecl
>(functionDecl
);
593 if (functionDecl
->hasBody() && pMethodDecl
&& isDerivedFromVclReferenceBase(pMethodDecl
->getParent())) {
594 // check the last thing that the dispose() method does, is to call into the superclass dispose method
595 if (loplugin::DeclCheck(functionDecl
).Function("dispose")) {
596 if (!isDisposeCallingSuperclassDispose(pMethodDecl
)) {
598 DiagnosticsEngine::Warning
,
599 BASE_REF_COUNTED_CLASS
" subclass dispose() function MUST call dispose() of its superclass as the last thing it does",
600 functionDecl
->getLocStart())
601 << functionDecl
->getSourceRange();
606 // check dispose method to make sure we are actually disposing all of the VclPtr fields
607 // FIXME this is not exhaustive. We should enable shouldVisitTemplateInstantiations and look deeper inside type declarations
608 if (pMethodDecl
&& pMethodDecl
->isInstance() && pMethodDecl
->getBody()
609 && pMethodDecl
->param_size()==0
610 && loplugin::DeclCheck(functionDecl
).Function("dispose")
611 && isDerivedFromVclReferenceBase(pMethodDecl
->getParent()) )
613 auto check
= loplugin::DeclCheck(functionDecl
).MemberFunction();
614 if (check
.Class("VirtualDevice").GlobalNamespace()
615 || check
.Class("Breadcrumb").GlobalNamespace())
620 std::set
<const FieldDecl
*> aVclPtrFields
;
621 for (auto i
= pMethodDecl
->getParent()->field_begin();
622 i
!= pMethodDecl
->getParent()->field_end(); ++i
)
624 auto const type
= loplugin::TypeCheck((*i
)->getType());
625 if (type
.Class("VclPtr").GlobalNamespace()) {
626 aVclPtrFields
.insert(*i
);
627 } else if (type
.Class("vector").StdNamespace()
628 || type
.Class("map").StdNamespace()
629 || type
.Class("list").StdNamespace()
630 || type
.Class("set").StdNamespace())
632 const RecordType
* recordType
= dyn_cast_or_null
<RecordType
>((*i
)->getType()->getUnqualifiedDesugaredType());
634 auto d
= dyn_cast
<ClassTemplateSpecializationDecl
>(recordType
->getDecl());
635 if (d
&& d
->getTemplateArgs().size()>0) {
636 auto const type
= loplugin::TypeCheck(d
->getTemplateArgs()[0].getAsType());
637 if (type
.Class("VclPtr").GlobalNamespace()) {
638 aVclPtrFields
.insert(*i
);
644 if (!aVclPtrFields
.empty()) {
645 findDisposeAndClearStatements( aVclPtrFields
, pMethodDecl
->getBody() );
646 if (!aVclPtrFields
.empty()) {
647 //pMethodDecl->dump();
648 std::string aMessage
= BASE_REF_COUNTED_CLASS
" subclass dispose() method does not call disposeAndClear() or clear() on the following field(s): ";
649 for(auto s
: aVclPtrFields
)
650 aMessage
+= ", " + s
->getNameAsString();
652 DiagnosticsEngine::Warning
,
654 functionDecl
->getLocStart())
655 << functionDecl
->getSourceRange();
663 bool VCLWidgets::VisitCXXDeleteExpr(const CXXDeleteExpr
*pCXXDeleteExpr
)
665 if (ignoreLocation(pCXXDeleteExpr
)) {
668 const CXXRecordDecl
*pPointee
= pCXXDeleteExpr
->getArgument()->getType()->getPointeeCXXRecordDecl();
669 if (pPointee
&& isDerivedFromVclReferenceBase(pPointee
)) {
670 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
671 pCXXDeleteExpr
->getLocStart());
672 StringRef filename
= compiler
.getSourceManager().getFilename(spellingLocation
);
673 if ( !(loplugin::isSamePathname(filename
, SRCDIR
"/include/vcl/vclreferencebase.hxx")))
676 DiagnosticsEngine::Warning
,
677 "calling delete on instance of " BASE_REF_COUNTED_CLASS
" subclass, must rather call disposeAndClear()",
678 pCXXDeleteExpr
->getLocStart())
679 << pCXXDeleteExpr
->getSourceRange();
682 const ImplicitCastExpr
* pImplicitCastExpr
= dyn_cast
<ImplicitCastExpr
>(pCXXDeleteExpr
->getArgument());
683 if (!pImplicitCastExpr
) {
686 if (pImplicitCastExpr
->getCastKind() != CK_UserDefinedConversion
) {
690 DiagnosticsEngine::Warning
,
691 "calling delete on instance of VclPtr, must rather call disposeAndClear()",
692 pCXXDeleteExpr
->getLocStart())
693 << pCXXDeleteExpr
->getSourceRange();
700 `-CXXMemberCallExpr 0xb06d8b0 'void'
701 `-MemberExpr 0xb06d868 '<bound member function type>' ->dispose 0x9d34880
702 `-ImplicitCastExpr 0xb06d8d8 'class SfxTabPage *' <UncheckedDerivedToBase (SfxTabPage)>
703 `-CXXThisExpr 0xb06d850 'class SfxAcceleratorConfigPage *' this
706 bool VCLWidgets::isDisposeCallingSuperclassDispose(const CXXMethodDecl
* pMethodDecl
)
708 const CompoundStmt
*pCompoundStatement
= dyn_cast
<CompoundStmt
>(pMethodDecl
->getBody());
709 if (!pCompoundStatement
) return false;
710 if (pCompoundStatement
->size() == 0) return false;
711 // find the last statement
712 const CXXMemberCallExpr
*pCallExpr
= dyn_cast
<CXXMemberCallExpr
>(*pCompoundStatement
->body_rbegin());
713 if (!pCallExpr
) return false;
714 const MemberExpr
*pMemberExpr
= dyn_cast
<MemberExpr
>(pCallExpr
->getCallee());
715 if (!pMemberExpr
) return false;
716 if (!loplugin::DeclCheck(pMemberExpr
->getMemberDecl()).Function("dispose")) return false;
717 const CXXMethodDecl
*pDirectCallee
= dyn_cast
<CXXMethodDecl
>(pCallExpr
->getDirectCallee());
718 if (!pDirectCallee
) return false;
719 /* Not working yet. Partially because sometimes the superclass does not a dispose() method, so it gets passed up the chain.
720 Need complex checking for that case.
721 if (pDirectCallee->getParent()->getTypeForDecl() != (*pMethodDecl->getParent()->bases_begin()).getType().getTypePtr()) {
723 DiagnosticsEngine::Warning,
724 "dispose() method calling wrong baseclass, calling " + pDirectCallee->getParent()->getQualifiedNameAsString() +
725 " should be calling " + (*pMethodDecl->getParent()->bases_begin()).getType().getAsString(),
726 pCallExpr->getLocStart())
727 << pCallExpr->getSourceRange();
733 bool containsVclPtr(const clang::Type
* pType0
);
735 bool containsVclPtr(const QualType
& qType
) {
736 auto check
= loplugin::TypeCheck(qType
);
737 if (check
.Class("ScopedVclPtr").GlobalNamespace()
738 || check
.Class("ScopedVclPtrInstance").GlobalNamespace()
739 || check
.Class("VclPtr").GlobalNamespace()
740 || check
.Class("VclPtrInstance").GlobalNamespace())
744 return containsVclPtr(qType
.getTypePtr());
747 bool containsVclPtr(const clang::Type
* pType0
) {
750 const clang::Type
* pType
= pType0
->getUnqualifiedDesugaredType();
753 if (pType
->isPointerType()) {
755 } else if (pType
->isArrayType()) {
756 const clang::ArrayType
* pArrayType
= dyn_cast
<clang::ArrayType
>(pType
);
757 QualType elementType
= pArrayType
->getElementType();
758 return containsVclPtr(elementType
);
760 const CXXRecordDecl
* pRecordDecl
= pType
->getAsCXXRecordDecl();
763 auto check
= loplugin::DeclCheck(pRecordDecl
);
764 if (check
.Class("ScopedVclPtr").GlobalNamespace()
765 || check
.Class("ScopedVclPtrInstance").GlobalNamespace()
766 || check
.Class("VclPtr").GlobalNamespace()
767 || check
.Class("VclPtrInstance").GlobalNamespace())
771 for(auto fieldDecl
= pRecordDecl
->field_begin();
772 fieldDecl
!= pRecordDecl
->field_end(); ++fieldDecl
)
774 const RecordType
*pFieldRecordType
= fieldDecl
->getType()->getAs
<RecordType
>();
775 if (pFieldRecordType
&& containsVclPtr(pFieldRecordType
)) {
779 for(auto baseSpecifier
= pRecordDecl
->bases_begin();
780 baseSpecifier
!= pRecordDecl
->bases_end(); ++baseSpecifier
)
782 const RecordType
*pFieldRecordType
= baseSpecifier
->getType()->getAs
<RecordType
>();
783 if (pFieldRecordType
&& containsVclPtr(pFieldRecordType
)) {
792 bool VCLWidgets::VisitCallExpr(const CallExpr
* pCallExpr
)
794 if (ignoreLocation(pCallExpr
)) {
797 FunctionDecl
const * fdecl
= pCallExpr
->getDirectCallee();
798 if (fdecl
== nullptr) {
801 std::string qname
{ fdecl
->getQualifiedNameAsString() };
802 if (qname
.find("memcpy") == std::string::npos
803 && qname
.find("bcopy") == std::string::npos
804 && qname
.find("memmove") == std::string::npos
805 && qname
.find("rtl_copy") == std::string::npos
) {
808 mbCheckingMemcpy
= true;
809 Stmt
* pStmt
= const_cast<Stmt
*>(static_cast<const Stmt
*>(pCallExpr
->getArg(0)));
811 mbCheckingMemcpy
= false;
815 bool VCLWidgets::VisitDeclRefExpr(const DeclRefExpr
* pDeclRefExpr
)
817 if (!mbCheckingMemcpy
) {
820 if (ignoreLocation(pDeclRefExpr
)) {
823 QualType pType
= pDeclRefExpr
->getDecl()->getType();
824 if (pType
->isPointerType()) {
825 pType
= pType
->getPointeeType();
827 if (!containsVclPtr(pType
)) {
831 DiagnosticsEngine::Warning
,
832 "Calling memcpy on a type which contains a VclPtr",
833 pDeclRefExpr
->getExprLoc());
837 bool VCLWidgets::VisitCXXConstructExpr( const CXXConstructExpr
* constructExpr
)
839 if (ignoreLocation(constructExpr
)) {
842 if (constructExpr
->getConstructionKind() != CXXConstructExpr::CK_Complete
) {
845 const CXXConstructorDecl
* pConstructorDecl
= constructExpr
->getConstructor();
846 const CXXRecordDecl
* recordDecl
= pConstructorDecl
->getParent();
847 if (isDerivedFromVclReferenceBase(recordDecl
)) {
848 StringRef aFileName
= compiler
.getSourceManager().getFilename(compiler
.getSourceManager().getSpellingLoc(constructExpr
->getLocStart()));
849 if (!loplugin::isSamePathname(aFileName
, SRCDIR
"/include/vcl/vclptr.hxx")) {
851 DiagnosticsEngine::Warning
,
852 "Calling constructor of a VclReferenceBase-derived type directly; all such creation should go via VclPtr<>::Create",
853 constructExpr
->getExprLoc());
859 loplugin::Plugin::Registration
< VCLWidgets
> X("vclwidgets");
863 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */