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/.
10 #ifndef LO_CLANG_SHARED_PLUGINS
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.
31 public loplugin::FilteringPlugin
<VCLWidgets
>
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
*);
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
)
64 bool isDerivedFromVclReferenceBase(const CXXRecordDecl
*decl
) {
67 if (loplugin::DeclCheck(decl
).Class(BASE_REF_COUNTED_CLASS
)
72 if (!decl
->hasDefinition()) {
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
, true)) {
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())
95 return containsVclReferenceBaseSubclass(qType
.getTypePtr());
98 bool containsVclReferenceBaseSubclass(const clang::Type
* pType0
) {
101 const clang::Type
* pType
= pType0
->getUnqualifiedDesugaredType();
104 const CXXRecordDecl
* pRecordDecl
= pType
->getAsCXXRecordDecl();
106 const ClassTemplateSpecializationDecl
* pTemplate
= dyn_cast
<ClassTemplateSpecializationDecl
>(pRecordDecl
);
108 auto check
= loplugin::DeclCheck(pTemplate
);
109 if (check
.Class("VclStatusListener").GlobalNamespace()) {
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) {
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
);
135 return isDerivedFromVclReferenceBase(pRecordDecl
);
139 bool VCLWidgets::VisitCXXDestructorDecl(const CXXDestructorDecl
* pCXXDestructorDecl
)
141 if (ignoreLocation(pCXXDestructorDecl
)) {
144 if (!pCXXDestructorDecl
->isThisDeclarationADefinition()) {
147 const CXXRecordDecl
* pRecordDecl
= pCXXDestructorDecl
->getParent();
149 if (loplugin::DeclCheck(pRecordDecl
).Class(BASE_REF_COUNTED_CLASS
)
154 // check if this class is derived from VclReferenceBase
155 if (!isDerivedFromVclReferenceBase(pRecordDecl
)) {
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;
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;
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)) {
190 if (bFoundVclPtrField
&& (!pCompoundStatement
|| pCompoundStatement
->size() == 0)) {
192 DiagnosticsEngine::Warning
,
193 BASE_REF_COUNTED_CLASS
" subclass with VclPtr field must call disposeOnce() from its destructor",
194 compat::getBeginLoc(pCXXDestructorDecl
))
195 << pCXXDestructorDecl
->getSourceRange();
198 // Check that the destructor for a BASE_REF_COUNTED_CLASS subclass either
199 // only calls disposeOnce() or, if !bFoundVclPtrField, does nothing at all:
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), ...;
212 for (auto loc
= compat::getBeginLoc(*i
);
213 compiler
.getSourceManager().isMacroBodyExpansion(loc
);
214 loc
= compiler
.getSourceManager().getImmediateMacroCallerLoc(
217 auto const name
= Lexer::getImmediateMacroName(
218 loc
, compiler
.getSourceManager(), compiler
.getLangOpts());
219 if (name
== "SAL_DEBUG" || name
== "assert") {
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;
236 nNumExtraStatements
++;
238 bOk
= (bFoundDisposeOnce
|| !bFoundVclPtrField
)
239 && nNumExtraStatements
== 0;
242 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
243 compat::getBeginLoc(pCXXDestructorDecl
));
244 StringRef filename
= getFileNameOfSpellingLoc(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")) )
251 DiagnosticsEngine::Warning
,
252 BASE_REF_COUNTED_CLASS
" subclass should have nothing in its destructor but a call to disposeOnce()",
253 compat::getBeginLoc(pCXXDestructorDecl
))
254 << pCXXDestructorDecl
->getSourceRange();
260 bool VCLWidgets::VisitBinaryOperator(const BinaryOperator
* binaryOperator
)
262 if (ignoreLocation(binaryOperator
)) {
265 if ( !binaryOperator
->isAssignmentOp() ) {
268 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
269 compat::getBeginLoc(binaryOperator
));
270 checkAssignmentForVclPtrToRawConversion(spellingLocation
, binaryOperator
->getLHS()->getType().getTypePtr(), binaryOperator
->getRHS());
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
)) {
284 StringRef filename
= getFileNameOfSpellingLoc(spellingLocation
);
285 if (loplugin::isSamePathname(filename
, SRCDIR
"/include/rtl/ref.hxx")) {
288 const CXXRecordDecl
* pointeeClass
= lhsType
->getPointeeType()->getAsCXXRecordDecl();
289 if (!isDerivedFromVclReferenceBase(pointeeClass
)) {
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
) {
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
) {
306 rhs
= exprWithCleanups
->IgnoreCasts();
313 if (isa
<CXXNullPtrLiteralExpr
>(rhs
)) {
316 if (isa
<CXXThisExpr
>(rhs
)) {
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())) {
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())) {
341 if (auto declRefExpr
= dyn_cast
<DeclRefExpr
>(rhs
->IgnoreImpCasts())) {
342 if (isa
<VarDecl
>(declRefExpr
->getDecl())) {
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
)) {
358 if (isa
<ParmVarDecl
>(pVarDecl
)) {
361 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
362 compat::getBeginLoc(pVarDecl
));
363 if (pVarDecl
->getInit()) {
364 checkAssignmentForVclPtrToRawConversion(spellingLocation
, pVarDecl
->getType().getTypePtr(), pVarDecl
->getInit());
366 StringRef aFileName
= getFileNameOfSpellingLoc(spellingLocation
);
367 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/vcl/vclptr.hxx"))
369 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/vcl/source/window/layout.cxx"))
371 // whitelist the valid things that can contain pointers.
372 // It is containing stuff like std::unique_ptr we get worried
373 if (pVarDecl
->getType()->isArrayType()) {
376 auto tc
= loplugin::TypeCheck(pVarDecl
->getType());
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())
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())
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
) {
403 if (containsVclReferenceBaseSubclass(pVarDecl
->getType())) {
405 DiagnosticsEngine::Warning
,
406 BASE_REF_COUNTED_CLASS
" subclass %0 should be wrapped in VclPtr",
407 pVarDecl
->getLocation())
408 << pVarDecl
->getType() << pVarDecl
->getSourceRange();
414 bool VCLWidgets::VisitFieldDecl(const FieldDecl
* fieldDecl
) {
415 if (ignoreLocation(fieldDecl
)) {
418 StringRef aFileName
= getFileNameOfSpellingLoc(
419 compiler
.getSourceManager().getSpellingLoc(compat::getBeginLoc(fieldDecl
)));
420 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/vcl/vclptr.hxx"))
422 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/rtl/ref.hxx"))
424 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/include/o3tl/enumarray.hxx"))
426 if (loplugin::isSamePathname(aFileName
, SRCDIR
"/vcl/source/window/layout.cxx"))
428 if (fieldDecl
->isBitField()) {
431 const CXXRecordDecl
*pParentRecordDecl
= isa
<RecordDecl
>(fieldDecl
->getDeclContext()) ? dyn_cast
<CXXRecordDecl
>(fieldDecl
->getParent()) : nullptr;
432 if (loplugin::DeclCheck(pParentRecordDecl
).Class("VclPtr")
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()))
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())) {
450 DiagnosticsEngine::Note
,
451 "template field here",
452 parent
->getPointOfInstantiation());
457 const RecordType
*recordType
= fieldDecl
->getType()->getAs
<RecordType
>();
458 if (recordType
== nullptr) {
461 const CXXRecordDecl
*recordDecl
= dyn_cast
<CXXRecordDecl
>(recordType
->getDecl());
462 if (recordDecl
== nullptr) {
466 // check if this field is derived fromVclReferenceBase
467 if (isDerivedFromVclReferenceBase(recordDecl
)) {
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;
490 if (!bFoundDispose
) {
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()) {
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();
509 bool VCLWidgets::VisitParmVarDecl(ParmVarDecl
const * pvDecl
)
511 if (ignoreLocation(pvDecl
)) {
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")
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())
532 static void findDisposeAndClearStatements(std::set
<const FieldDecl
*>& aVclPtrFields
, const Stmt
*pStmt
)
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
);
545 if (isa
<ForStmt
>(pStmt
)) {
546 findDisposeAndClearStatements(aVclPtrFields
, dyn_cast
<ForStmt
>(pStmt
)->getBody());
549 if (isa
<IfStmt
>(pStmt
)) {
550 findDisposeAndClearStatements(aVclPtrFields
, dyn_cast
<IfStmt
>(pStmt
)->getThen());
551 findDisposeAndClearStatements(aVclPtrFields
, dyn_cast
<IfStmt
>(pStmt
)->getElse());
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")))
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());
575 aVclPtrFields
.erase(xxx
);
579 bool VCLWidgets::VisitFunctionDecl( const FunctionDecl
* functionDecl
)
581 if (ignoreLocation(functionDecl
)) {
584 // ignore the stuff in the VclPtr template class
585 if (loplugin::DeclCheck(functionDecl
).MemberFunction().Class("VclPtr")
590 // ignore the BASE_REF_COUNTED_CLASS::dispose() method
591 if (loplugin::DeclCheck(functionDecl
).Function("dispose")
592 .Class(BASE_REF_COUNTED_CLASS
).GlobalNamespace())
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
)) {
602 DiagnosticsEngine::Warning
,
603 BASE_REF_COUNTED_CLASS
" subclass dispose() function MUST call dispose() of its superclass as the last thing it does",
604 compat::getBeginLoc(functionDecl
))
605 << functionDecl
->getSourceRange();
610 // check dispose method to make sure we are actually disposing all of the VclPtr fields
611 // FIXME this is not exhaustive. We should enable shouldVisitTemplateInstantiations and look deeper inside type declarations
612 if (pMethodDecl
&& pMethodDecl
->isInstance() && pMethodDecl
->getBody()
613 && pMethodDecl
->param_size()==0
614 && loplugin::DeclCheck(functionDecl
).Function("dispose")
615 && isDerivedFromVclReferenceBase(pMethodDecl
->getParent()) )
617 auto check
= loplugin::DeclCheck(functionDecl
).MemberFunction();
618 if (check
.Class("VirtualDevice").GlobalNamespace()
619 || check
.Class("Breadcrumb").GlobalNamespace())
624 std::set
<const FieldDecl
*> aVclPtrFields
;
625 for (auto i
= pMethodDecl
->getParent()->field_begin();
626 i
!= pMethodDecl
->getParent()->field_end(); ++i
)
628 auto const type
= loplugin::TypeCheck((*i
)->getType());
629 if (type
.Class("VclPtr").GlobalNamespace()) {
630 aVclPtrFields
.insert(*i
);
631 } else if (type
.Class("vector").StdNamespace()
632 || type
.Class("map").StdNamespace()
633 || type
.Class("list").StdNamespace()
634 || type
.Class("set").StdNamespace())
636 const RecordType
* recordType
= dyn_cast_or_null
<RecordType
>((*i
)->getType()->getUnqualifiedDesugaredType());
638 auto d
= dyn_cast
<ClassTemplateSpecializationDecl
>(recordType
->getDecl());
639 if (d
&& d
->getTemplateArgs().size()>0) {
640 auto const type
= loplugin::TypeCheck(d
->getTemplateArgs()[0].getAsType());
641 if (type
.Class("VclPtr").GlobalNamespace()) {
642 aVclPtrFields
.insert(*i
);
648 if (!aVclPtrFields
.empty()) {
649 findDisposeAndClearStatements( aVclPtrFields
, pMethodDecl
->getBody() );
650 if (!aVclPtrFields
.empty()) {
651 //pMethodDecl->dump();
652 std::string aMessage
= BASE_REF_COUNTED_CLASS
" subclass dispose() method does not call disposeAndClear() or clear() on the following field(s): ";
653 for(auto s
: aVclPtrFields
)
654 aMessage
+= ", " + s
->getNameAsString();
656 DiagnosticsEngine::Warning
,
658 compat::getBeginLoc(functionDecl
))
659 << functionDecl
->getSourceRange();
667 bool VCLWidgets::VisitCXXDeleteExpr(const CXXDeleteExpr
*pCXXDeleteExpr
)
669 if (ignoreLocation(pCXXDeleteExpr
)) {
672 const CXXRecordDecl
*pPointee
= pCXXDeleteExpr
->getArgument()->getType()->getPointeeCXXRecordDecl();
673 if (pPointee
&& isDerivedFromVclReferenceBase(pPointee
)) {
674 SourceLocation spellingLocation
= compiler
.getSourceManager().getSpellingLoc(
675 compat::getBeginLoc(pCXXDeleteExpr
));
676 StringRef filename
= getFileNameOfSpellingLoc(spellingLocation
);
677 if ( !(loplugin::isSamePathname(filename
, SRCDIR
"/include/vcl/vclreferencebase.hxx")))
680 DiagnosticsEngine::Warning
,
681 "calling delete on instance of " BASE_REF_COUNTED_CLASS
" subclass, must rather call disposeAndClear()",
682 compat::getBeginLoc(pCXXDeleteExpr
))
683 << pCXXDeleteExpr
->getSourceRange();
686 const ImplicitCastExpr
* pImplicitCastExpr
= dyn_cast
<ImplicitCastExpr
>(pCXXDeleteExpr
->getArgument());
687 if (!pImplicitCastExpr
) {
690 if (pImplicitCastExpr
->getCastKind() != CK_UserDefinedConversion
) {
694 DiagnosticsEngine::Warning
,
695 "calling delete on instance of VclPtr, must rather call disposeAndClear()",
696 compat::getBeginLoc(pCXXDeleteExpr
))
697 << pCXXDeleteExpr
->getSourceRange();
704 `-CXXMemberCallExpr 0xb06d8b0 'void'
705 `-MemberExpr 0xb06d868 '<bound member function type>' ->dispose 0x9d34880
706 `-ImplicitCastExpr 0xb06d8d8 'class SfxTabPage *' <UncheckedDerivedToBase (SfxTabPage)>
707 `-CXXThisExpr 0xb06d850 'class SfxAcceleratorConfigPage *' this
710 bool VCLWidgets::isDisposeCallingSuperclassDispose(const CXXMethodDecl
* pMethodDecl
)
712 const CompoundStmt
*pCompoundStatement
= dyn_cast
<CompoundStmt
>(pMethodDecl
->getBody());
713 if (!pCompoundStatement
) return false;
714 if (pCompoundStatement
->size() == 0) return false;
715 // find the last statement
716 const CXXMemberCallExpr
*pCallExpr
= dyn_cast
<CXXMemberCallExpr
>(*pCompoundStatement
->body_rbegin());
717 if (!pCallExpr
) return false;
718 const MemberExpr
*pMemberExpr
= dyn_cast
<MemberExpr
>(pCallExpr
->getCallee());
719 if (!pMemberExpr
) return false;
720 if (!loplugin::DeclCheck(pMemberExpr
->getMemberDecl()).Function("dispose")) return false;
721 const CXXMethodDecl
*pDirectCallee
= dyn_cast
<CXXMethodDecl
>(pCallExpr
->getDirectCallee());
722 if (!pDirectCallee
) return false;
723 /* Not working yet. Partially because sometimes the superclass does not a dispose() method, so it gets passed up the chain.
724 Need complex checking for that case.
725 if (pDirectCallee->getParent()->getTypeForDecl() != (*pMethodDecl->getParent()->bases_begin()).getType().getTypePtr()) {
727 DiagnosticsEngine::Warning,
728 "dispose() method calling wrong baseclass, calling " + pDirectCallee->getParent()->getQualifiedNameAsString() +
729 " should be calling " + (*pMethodDecl->getParent()->bases_begin()).getType().getAsString(),
730 pCallExpr->getLocStart())
731 << pCallExpr->getSourceRange();
737 bool containsVclPtr(const clang::Type
* pType0
);
739 bool containsVclPtr(const QualType
& qType
) {
740 auto check
= loplugin::TypeCheck(qType
);
741 if (check
.Class("ScopedVclPtr").GlobalNamespace()
742 || check
.Class("ScopedVclPtrInstance").GlobalNamespace()
743 || check
.Class("VclPtr").GlobalNamespace()
744 || check
.Class("VclPtrInstance").GlobalNamespace())
748 return containsVclPtr(qType
.getTypePtr());
751 bool containsVclPtr(const clang::Type
* pType0
) {
754 const clang::Type
* pType
= pType0
->getUnqualifiedDesugaredType();
757 if (pType
->isPointerType()) {
759 } else if (pType
->isArrayType()) {
760 const clang::ArrayType
* pArrayType
= dyn_cast
<clang::ArrayType
>(pType
);
761 QualType elementType
= pArrayType
->getElementType();
762 return containsVclPtr(elementType
);
764 const CXXRecordDecl
* pRecordDecl
= pType
->getAsCXXRecordDecl();
767 auto check
= loplugin::DeclCheck(pRecordDecl
);
768 if (check
.Class("ScopedVclPtr").GlobalNamespace()
769 || check
.Class("ScopedVclPtrInstance").GlobalNamespace()
770 || check
.Class("VclPtr").GlobalNamespace()
771 || check
.Class("VclPtrInstance").GlobalNamespace())
775 for(auto fieldDecl
= pRecordDecl
->field_begin();
776 fieldDecl
!= pRecordDecl
->field_end(); ++fieldDecl
)
778 const RecordType
*pFieldRecordType
= fieldDecl
->getType()->getAs
<RecordType
>();
779 if (pFieldRecordType
&& containsVclPtr(pFieldRecordType
)) {
783 for(auto baseSpecifier
= pRecordDecl
->bases_begin();
784 baseSpecifier
!= pRecordDecl
->bases_end(); ++baseSpecifier
)
786 const RecordType
*pFieldRecordType
= baseSpecifier
->getType()->getAs
<RecordType
>();
787 if (pFieldRecordType
&& containsVclPtr(pFieldRecordType
)) {
796 bool VCLWidgets::VisitCallExpr(const CallExpr
* pCallExpr
)
798 if (ignoreLocation(pCallExpr
)) {
801 FunctionDecl
const * fdecl
= pCallExpr
->getDirectCallee();
802 if (fdecl
== nullptr) {
805 std::string qname
{ fdecl
->getQualifiedNameAsString() };
806 if (qname
.find("memcpy") == std::string::npos
807 && qname
.find("bcopy") == std::string::npos
808 && qname
.find("memmove") == std::string::npos
809 && qname
.find("rtl_copy") == std::string::npos
) {
812 mbCheckingMemcpy
= true;
813 Stmt
* pStmt
= const_cast<Stmt
*>(static_cast<const Stmt
*>(pCallExpr
->getArg(0)));
815 mbCheckingMemcpy
= false;
819 bool VCLWidgets::VisitDeclRefExpr(const DeclRefExpr
* pDeclRefExpr
)
821 if (!mbCheckingMemcpy
) {
824 if (ignoreLocation(pDeclRefExpr
)) {
827 QualType pType
= pDeclRefExpr
->getDecl()->getType();
828 if (pType
->isPointerType()) {
829 pType
= pType
->getPointeeType();
831 if (!containsVclPtr(pType
)) {
835 DiagnosticsEngine::Warning
,
836 "Calling memcpy on a type which contains a VclPtr",
837 pDeclRefExpr
->getExprLoc());
841 bool VCLWidgets::VisitCXXConstructExpr( const CXXConstructExpr
* constructExpr
)
843 if (ignoreLocation(constructExpr
)) {
846 if (constructExpr
->getConstructionKind() != CXXConstructExpr::CK_Complete
) {
849 const CXXConstructorDecl
* pConstructorDecl
= constructExpr
->getConstructor();
850 const CXXRecordDecl
* recordDecl
= pConstructorDecl
->getParent();
851 if (isDerivedFromVclReferenceBase(recordDecl
)) {
852 StringRef aFileName
= getFileNameOfSpellingLoc(
853 compiler
.getSourceManager().getSpellingLoc(compat::getBeginLoc(constructExpr
)));
854 if (!loplugin::isSamePathname(aFileName
, SRCDIR
"/include/vcl/vclptr.hxx")) {
856 DiagnosticsEngine::Warning
,
857 "Calling constructor of a VclReferenceBase-derived type directly; all such creation should go via VclPtr<>::Create",
858 constructExpr
->getExprLoc());
864 loplugin::Plugin::Registration
< VCLWidgets
> vclwidgets("vclwidgets");
868 #endif // LO_CLANG_SHARED_PLUGINS
870 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */