Version 6.1.0.2, tag libreoffice-6.1.0.2
[LibreOffice.git] / compilerplugins / clang / vclwidgets.cxx
blobaf2b1bf46cdd21d1c45a439f78fd7c108c8d202b
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <memory>
11 #include <string>
12 #include <iostream>
14 #include "plugin.hxx"
15 #include "check.hxx"
16 #include "clang/AST/CXXInheritance.h"
18 // Final goal: Checker for VCL widget references. Makes sure that VCL Window subclasses are properly referenced counted and dispose()'ed.
20 // But at the moment it just finds subclasses of Window which are not heap-allocated
22 // TODO do I need to check for local and static variables, too ?
23 // TODO when we have a dispose() method, verify that the dispose() methods releases all of the Window references
24 // TODO when we have a dispose() method, verify that it calls the super-class dispose() method at some point.
26 namespace {
28 class VCLWidgets:
29 public RecursiveASTVisitor<VCLWidgets>, public loplugin::Plugin
31 public:
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 *);
49 private:
50 void checkAssignmentForVclPtrToRawConversion(const SourceLocation& sourceLoc, const clang::Type* lhsType, const Expr* rhs);
51 bool isDisposeCallingSuperclassDispose(const CXXMethodDecl* pMethodDecl);
52 bool mbCheckingMemcpy = false;
55 #define BASE_REF_COUNTED_CLASS "VclReferenceBase"
57 bool BaseCheckNotWindowSubclass(const CXXRecordDecl *BaseDefinition) {
58 return !loplugin::DeclCheck(BaseDefinition).Class(BASE_REF_COUNTED_CLASS)
59 .GlobalNamespace();
62 bool isDerivedFromVclReferenceBase(const CXXRecordDecl *decl) {
63 if (!decl)
64 return false;
65 if (loplugin::DeclCheck(decl).Class(BASE_REF_COUNTED_CLASS)
66 .GlobalNamespace())
68 return true;
70 if (!decl->hasDefinition()) {
71 return false;
73 if (// not sure what hasAnyDependentBases() does,
74 // but it avoids classes we don't want, e.g. WeakAggComponentImplHelper1
75 !decl->hasAnyDependentBases() &&
76 !decl->forallBases(BaseCheckNotWindowSubclass, true)) {
77 return true;
79 return false;
82 bool containsVclReferenceBaseSubclass(const clang::Type* pType0);
84 bool containsVclReferenceBaseSubclass(const QualType& qType) {
85 auto check = loplugin::TypeCheck(qType);
86 if (check.Class("ScopedVclPtr").GlobalNamespace()
87 || check.Class("ScopedVclPtrInstance").GlobalNamespace()
88 || check.Class("VclPtr").GlobalNamespace()
89 || check.Class("VclPtrInstance").GlobalNamespace())
91 return false;
93 return containsVclReferenceBaseSubclass(qType.getTypePtr());
96 bool containsVclReferenceBaseSubclass(const clang::Type* pType0) {
97 if (!pType0)
98 return false;
99 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
100 if (!pType)
101 return false;
102 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
103 if (pRecordDecl) {
104 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
105 if (pTemplate) {
106 auto check = loplugin::DeclCheck(pTemplate);
107 if (check.Class("VclStatusListener").GlobalNamespace()) {
108 return false;
110 bool link = bool(check.Class("Link").GlobalNamespace());
111 for(unsigned i=0; i<pTemplate->getTemplateArgs().size(); ++i) {
112 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[i];
113 if (rArg.getKind() == TemplateArgument::ArgKind::Type &&
114 containsVclReferenceBaseSubclass(rArg.getAsType()))
116 // OK for first template argument of tools/link.hxx Link
117 // to be a Window-derived pointer:
118 if (!link || i != 0) {
119 return true;
125 if (pType->isPointerType()) {
126 QualType pointeeType = pType->getPointeeType();
127 return containsVclReferenceBaseSubclass(pointeeType);
128 } else if (pType->isArrayType()) {
129 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
130 QualType elementType = pArrayType->getElementType();
131 return containsVclReferenceBaseSubclass(elementType);
132 } else {
133 return isDerivedFromVclReferenceBase(pRecordDecl);
137 bool VCLWidgets::VisitCXXDestructorDecl(const CXXDestructorDecl* pCXXDestructorDecl)
139 if (ignoreLocation(pCXXDestructorDecl)) {
140 return true;
142 if (!pCXXDestructorDecl->isThisDeclarationADefinition()) {
143 return true;
145 const CXXRecordDecl * pRecordDecl = pCXXDestructorDecl->getParent();
146 // ignore
147 if (loplugin::DeclCheck(pRecordDecl).Class(BASE_REF_COUNTED_CLASS)
148 .GlobalNamespace())
150 return true;
152 // check if this class is derived from VclReferenceBase
153 if (!isDerivedFromVclReferenceBase(pRecordDecl)) {
154 return true;
156 // check if we have any VclPtr<> fields
157 bool bFoundVclPtrField = false;
158 for(auto fieldDecl = pRecordDecl->field_begin();
159 fieldDecl != pRecordDecl->field_end(); ++fieldDecl)
161 const RecordType *pFieldRecordType = fieldDecl->getType()->getAs<RecordType>();
162 if (pFieldRecordType) {
163 if (loplugin::DeclCheck(pFieldRecordType->getDecl())
164 .Class("VclPtr").GlobalNamespace())
166 bFoundVclPtrField = true;
167 break;
171 // check if there is a dispose() method
172 bool bFoundDispose = false;
173 for(auto methodDecl = pRecordDecl->method_begin();
174 methodDecl != pRecordDecl->method_end(); ++methodDecl)
176 if (methodDecl->isInstance() && methodDecl->param_size()==0
177 && loplugin::DeclCheck(*methodDecl).Function("dispose"))
179 bFoundDispose = true;
180 break;
183 const CompoundStmt *pCompoundStatement = dyn_cast_or_null<CompoundStmt>(pCXXDestructorDecl->getBody());
184 // having an empty body and no dispose() method is fine
185 if (!bFoundVclPtrField && !bFoundDispose && (!pCompoundStatement || pCompoundStatement->size() == 0)) {
186 return true;
188 if (bFoundVclPtrField && (!pCompoundStatement || pCompoundStatement->size() == 0)) {
189 report(
190 DiagnosticsEngine::Warning,
191 BASE_REF_COUNTED_CLASS " subclass with VclPtr field must call disposeOnce() from its destructor",
192 pCXXDestructorDecl->getLocStart())
193 << pCXXDestructorDecl->getSourceRange();
194 return true;
196 // Check that the destructor for a BASE_REF_COUNTED_CLASS subclass either
197 // only calls disposeOnce() or, if !bFoundVclPtrField, does nothing at all:
198 bool bOk = false;
199 if (pCompoundStatement) {
200 bool bFoundDisposeOnce = false;
201 int nNumExtraStatements = 0;
202 for (auto i = pCompoundStatement->body_begin();
203 i != pCompoundStatement->body_end(); ++i)
205 //TODO: The below erroneously also skips past entire statements like
207 // assert(true), ...;
209 auto skip = false;
210 for (auto loc = (*i)->getLocStart();
211 compiler.getSourceManager().isMacroBodyExpansion(loc);
212 loc = compiler.getSourceManager().getImmediateMacroCallerLoc(
213 loc))
215 auto const name = Lexer::getImmediateMacroName(
216 loc, compiler.getSourceManager(), compiler.getLangOpts());
217 if (name == "SAL_DEBUG" || name == "assert") {
218 skip = true;
219 break;
222 if (skip) {
223 continue;
225 if (auto const pCallExpr = dyn_cast<CXXMemberCallExpr>(*i)) {
226 if( const FunctionDecl* func = pCallExpr->getDirectCallee()) {
227 if( func->getNumParams() == 0 && func->getIdentifier() != NULL
228 && ( func->getName() == "disposeOnce" )) {
229 bFoundDisposeOnce = true;
230 continue;
234 nNumExtraStatements++;
236 bOk = (bFoundDisposeOnce || !bFoundVclPtrField)
237 && nNumExtraStatements == 0;
239 if (!bOk) {
240 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
241 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")) )
247 report(
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();
254 return true;
257 bool VCLWidgets::VisitBinaryOperator(const BinaryOperator * binaryOperator)
259 if (ignoreLocation(binaryOperator)) {
260 return true;
262 if ( !binaryOperator->isAssignmentOp() ) {
263 return true;
265 SourceLocation spellingLocation = compiler.getSourceManager().getSpellingLoc(
266 binaryOperator->getLocStart());
267 checkAssignmentForVclPtrToRawConversion(spellingLocation, binaryOperator->getLHS()->getType().getTypePtr(), binaryOperator->getRHS());
268 return true;
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)) {
276 return;
278 if (!rhs) {
279 return;
281 StringRef filename = compiler.getSourceManager().getFilename(spellingLocation);
282 if (loplugin::isSamePathname(filename, SRCDIR "/include/rtl/ref.hxx")) {
283 return;
285 const CXXRecordDecl* pointeeClass = lhsType->getPointeeType()->getAsCXXRecordDecl();
286 if (!isDerivedFromVclReferenceBase(pointeeClass)) {
287 return;
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) {
295 return;
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) {
301 return;
303 rhs = exprWithCleanups->IgnoreCasts();
304 } else {
305 return;
307 } else {
308 return;
310 if (isa<CXXNullPtrLiteralExpr>(rhs)) {
311 return;
313 if (isa<CXXThisExpr>(rhs)) {
314 return;
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())) {
322 return;
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())) {
333 return;
338 if (auto declRefExpr = dyn_cast<DeclRefExpr>(rhs->IgnoreImpCasts())) {
339 if (isa<VarDecl>(declRefExpr->getDecl())) {
340 return;
344 report(
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)) {
353 return true;
355 if (isa<ParmVarDecl>(pVarDecl)) {
356 return true;
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"))
365 return true;
366 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
367 return true;
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()) {
371 return true;
373 auto tc = loplugin::TypeCheck(pVarDecl->getType());
374 if (tc.Pointer()
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())
383 return true;
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())
392 return true;
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) {
397 return true;
400 if (containsVclReferenceBaseSubclass(pVarDecl->getType())) {
401 report(
402 DiagnosticsEngine::Warning,
403 BASE_REF_COUNTED_CLASS " subclass %0 should be wrapped in VclPtr",
404 pVarDecl->getLocation())
405 << pVarDecl->getType() << pVarDecl->getSourceRange();
406 return true;
408 return true;
411 bool VCLWidgets::VisitFieldDecl(const FieldDecl * fieldDecl) {
412 if (ignoreLocation(fieldDecl)) {
413 return true;
415 StringRef aFileName = compiler.getSourceManager().getFilename(compiler.getSourceManager().getSpellingLoc(fieldDecl->getLocStart()));
416 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/vcl/vclptr.hxx"))
417 return true;
418 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/rtl/ref.hxx"))
419 return true;
420 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/o3tl/enumarray.hxx"))
421 return true;
422 if (loplugin::isSamePathname(aFileName, SRCDIR "/vcl/source/window/layout.cxx"))
423 return true;
424 if (fieldDecl->isBitField()) {
425 return true;
427 const CXXRecordDecl *pParentRecordDecl = isa<RecordDecl>(fieldDecl->getDeclContext()) ? dyn_cast<CXXRecordDecl>(fieldDecl->getParent()) : nullptr;
428 if (loplugin::DeclCheck(pParentRecordDecl).Class("VclPtr")
429 .GlobalNamespace())
431 return true;
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()))
439 report(
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())) {
445 report(
446 DiagnosticsEngine::Note,
447 "template field here",
448 parent->getPointOfInstantiation());
450 return true;
453 const RecordType *recordType = fieldDecl->getType()->getAs<RecordType>();
454 if (recordType == nullptr) {
455 return true;
457 const CXXRecordDecl *recordDecl = dyn_cast<CXXRecordDecl>(recordType->getDecl());
458 if (recordDecl == nullptr) {
459 return true;
462 // check if this field is derived fromVclReferenceBase
463 if (isDerivedFromVclReferenceBase(recordDecl)) {
464 report(
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;
483 break;
486 if (!bFoundDispose) {
487 report(
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()) {
494 report(
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();
502 return true;
505 bool VCLWidgets::VisitParmVarDecl(ParmVarDecl const * pvDecl)
507 if (ignoreLocation(pvDecl)) {
508 return true;
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")
513 .GlobalNamespace())
515 return true;
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())
522 return true;
524 return true;
528 static void findDisposeAndClearStatements(std::set<const FieldDecl*>& aVclPtrFields, const Stmt *pStmt)
530 if (!pStmt)
531 return;
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);
539 return;
541 if (isa<ForStmt>(pStmt)) {
542 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<ForStmt>(pStmt)->getBody());
543 return;
545 if (isa<IfStmt>(pStmt)) {
546 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<IfStmt>(pStmt)->getThen());
547 findDisposeAndClearStatements(aVclPtrFields, dyn_cast<IfStmt>(pStmt)->getElse());
548 return;
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")))
558 return;
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());
570 if (xxx)
571 aVclPtrFields.erase(xxx);
575 bool VCLWidgets::VisitFunctionDecl( const FunctionDecl* functionDecl )
577 if (ignoreLocation(functionDecl)) {
578 return true;
580 // ignore the stuff in the VclPtr template class
581 if (loplugin::DeclCheck(functionDecl).MemberFunction().Class("VclPtr")
582 .GlobalNamespace())
584 return true;
586 // ignore the BASE_REF_COUNTED_CLASS::dispose() method
587 if (loplugin::DeclCheck(functionDecl).Function("dispose")
588 .Class(BASE_REF_COUNTED_CLASS).GlobalNamespace())
590 return true;
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)) {
597 report(
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())
617 return true;
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());
633 if (recordType) {
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();
651 report(
652 DiagnosticsEngine::Warning,
653 aMessage,
654 functionDecl->getLocStart())
655 << functionDecl->getSourceRange();
660 return true;
663 bool VCLWidgets::VisitCXXDeleteExpr(const CXXDeleteExpr *pCXXDeleteExpr)
665 if (ignoreLocation(pCXXDeleteExpr)) {
666 return true;
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")))
675 report(
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) {
684 return true;
686 if (pImplicitCastExpr->getCastKind() != CK_UserDefinedConversion) {
687 return true;
689 report(
690 DiagnosticsEngine::Warning,
691 "calling delete on instance of VclPtr, must rather call disposeAndClear()",
692 pCXXDeleteExpr->getLocStart())
693 << pCXXDeleteExpr->getSourceRange();
694 return true;
699 The AST looks like:
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()) {
722 report(
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();
728 return false;
730 return true;
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())
742 return true;
744 return containsVclPtr(qType.getTypePtr());
747 bool containsVclPtr(const clang::Type* pType0) {
748 if (!pType0)
749 return false;
750 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
751 if (!pType)
752 return false;
753 if (pType->isPointerType()) {
754 return false;
755 } else if (pType->isArrayType()) {
756 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
757 QualType elementType = pArrayType->getElementType();
758 return containsVclPtr(elementType);
759 } else {
760 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
761 if (pRecordDecl)
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())
769 return true;
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)) {
776 return true;
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)) {
784 return true;
789 return false;
792 bool VCLWidgets::VisitCallExpr(const CallExpr* pCallExpr)
794 if (ignoreLocation(pCallExpr)) {
795 return true;
797 FunctionDecl const * fdecl = pCallExpr->getDirectCallee();
798 if (fdecl == nullptr) {
799 return true;
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) {
806 return true;
808 mbCheckingMemcpy = true;
809 Stmt * pStmt = const_cast<Stmt*>(static_cast<const Stmt*>(pCallExpr->getArg(0)));
810 TraverseStmt(pStmt);
811 mbCheckingMemcpy = false;
812 return true;
815 bool VCLWidgets::VisitDeclRefExpr(const DeclRefExpr* pDeclRefExpr)
817 if (!mbCheckingMemcpy) {
818 return true;
820 if (ignoreLocation(pDeclRefExpr)) {
821 return true;
823 QualType pType = pDeclRefExpr->getDecl()->getType();
824 if (pType->isPointerType()) {
825 pType = pType->getPointeeType();
827 if (!containsVclPtr(pType)) {
828 return true;
830 report(
831 DiagnosticsEngine::Warning,
832 "Calling memcpy on a type which contains a VclPtr",
833 pDeclRefExpr->getExprLoc());
834 return true;
837 bool VCLWidgets::VisitCXXConstructExpr( const CXXConstructExpr* constructExpr )
839 if (ignoreLocation(constructExpr)) {
840 return true;
842 if (constructExpr->getConstructionKind() != CXXConstructExpr::CK_Complete) {
843 return true;
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")) {
850 report(
851 DiagnosticsEngine::Warning,
852 "Calling constructor of a VclReferenceBase-derived type directly; all such creation should go via VclPtr<>::Create",
853 constructExpr->getExprLoc());
856 return true;
859 loplugin::Plugin::Registration< VCLWidgets > X("vclwidgets");
863 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */