bump product version to 6.3.0.0.beta1
[LibreOffice.git] / compilerplugins / clang / vclwidgets.cxx
blob45dbe450ec87c5ee5c027e8bc84fe5d47adfe0ad
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 #ifndef LO_CLANG_SHARED_PLUGINS
12 #include <memory>
13 #include <string>
14 #include <iostream>
16 #include "plugin.hxx"
17 #include "check.hxx"
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, true)) {
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 compat::getBeginLoc(pCXXDestructorDecl))
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 = compat::getBeginLoc(*i);
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 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")) )
250 report(
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();
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 compat::getBeginLoc(binaryOperator));
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 = getFileNameOfSpellingLoc(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 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"))
368 return true;
369 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
370 return true;
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()) {
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 = getFileNameOfSpellingLoc(
419 compiler.getSourceManager().getSpellingLoc(compat::getBeginLoc(fieldDecl)));
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 report(
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())
621 return true;
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());
637 if (recordType) {
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();
655 report(
656 DiagnosticsEngine::Warning,
657 aMessage,
658 compat::getBeginLoc(functionDecl))
659 << functionDecl->getSourceRange();
664 return true;
667 bool VCLWidgets::VisitCXXDeleteExpr(const CXXDeleteExpr *pCXXDeleteExpr)
669 if (ignoreLocation(pCXXDeleteExpr)) {
670 return true;
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")))
679 report(
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) {
688 return true;
690 if (pImplicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
691 return true;
693 report(
694 DiagnosticsEngine::Warning,
695 "calling delete on instance of VclPtr, must rather call disposeAndClear()",
696 compat::getBeginLoc(pCXXDeleteExpr))
697 << pCXXDeleteExpr->getSourceRange();
698 return true;
703 The AST looks like:
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()) {
726 report(
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();
732 return false;
734 return true;
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())
746 return true;
748 return containsVclPtr(qType.getTypePtr());
751 bool containsVclPtr(const clang::Type* pType0) {
752 if (!pType0)
753 return false;
754 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
755 if (!pType)
756 return false;
757 if (pType->isPointerType()) {
758 return false;
759 } else if (pType->isArrayType()) {
760 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
761 QualType elementType = pArrayType->getElementType();
762 return containsVclPtr(elementType);
763 } else {
764 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
765 if (pRecordDecl)
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())
773 return true;
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)) {
780 return true;
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)) {
788 return true;
793 return false;
796 bool VCLWidgets::VisitCallExpr(const CallExpr* pCallExpr)
798 if (ignoreLocation(pCallExpr)) {
799 return true;
801 FunctionDecl const * fdecl = pCallExpr->getDirectCallee();
802 if (fdecl == nullptr) {
803 return true;
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) {
810 return true;
812 mbCheckingMemcpy = true;
813 Stmt * pStmt = const_cast<Stmt*>(static_cast<const Stmt*>(pCallExpr->getArg(0)));
814 TraverseStmt(pStmt);
815 mbCheckingMemcpy = false;
816 return true;
819 bool VCLWidgets::VisitDeclRefExpr(const DeclRefExpr* pDeclRefExpr)
821 if (!mbCheckingMemcpy) {
822 return true;
824 if (ignoreLocation(pDeclRefExpr)) {
825 return true;
827 QualType pType = pDeclRefExpr->getDecl()->getType();
828 if (pType->isPointerType()) {
829 pType = pType->getPointeeType();
831 if (!containsVclPtr(pType)) {
832 return true;
834 report(
835 DiagnosticsEngine::Warning,
836 "Calling memcpy on a type which contains a VclPtr",
837 pDeclRefExpr->getExprLoc());
838 return true;
841 bool VCLWidgets::VisitCXXConstructExpr( const CXXConstructExpr* constructExpr )
843 if (ignoreLocation(constructExpr)) {
844 return true;
846 if (constructExpr->getConstructionKind() != CXXConstructExpr::CK_Complete) {
847 return true;
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")) {
855 report(
856 DiagnosticsEngine::Warning,
857 "Calling constructor of a VclReferenceBase-derived type directly; all such creation should go via VclPtr<>::Create",
858 constructExpr->getExprLoc());
861 return true;
864 loplugin::Plugin::Registration< VCLWidgets > vclwidgets("vclwidgets");
868 #endif // LO_CLANG_SHARED_PLUGINS
870 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */