Version 7.6.3.2-android, tag libreoffice-7.6.3.2-android
[LibreOffice.git] / compilerplugins / clang / refcounting.cxx
blobca6c0d97d9f0816038e8328fb9949f61117a5b55
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 <string>
11 #include <iostream>
13 #include "check.hxx"
14 #include "plugin.hxx"
15 #include "config_clang.h"
16 #include "clang/AST/CXXInheritance.h"
18 /**
20 If you have:
22 class Foo : public css::foo::XBaa {
25 Then XBaa has acquire and release methods inherited from XInterface.
26 These are hard lifecycle controls.
28 If you see another class:
30 class Baz {
31 Foo aFooMember;
34 this is a bug =) since aFooMember assumes heap allocated lifecycle and
35 not delete on last 'release'.
39 namespace {
41 class RefCounting:
42 public loplugin::FilteringPlugin<RefCounting>
44 public:
45 explicit RefCounting(loplugin::InstantiationData const & data): FilteringPlugin(data)
48 virtual bool preRun() override { return true; }
50 virtual void run() override
52 if (preRun())
53 TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
56 bool VisitFieldDecl(const FieldDecl *);
57 bool VisitVarDecl(const VarDecl *);
58 bool VisitFunctionDecl(const FunctionDecl *);
59 bool VisitTypeLoc(clang::TypeLoc typeLoc);
60 bool VisitCXXDeleteExpr(const CXXDeleteExpr *);
61 bool VisitBinaryOperator(const BinaryOperator *);
62 bool VisitReturnStmt(const ReturnStmt *);
64 // Creation of temporaries with one argument are represented by
65 // CXXFunctionalCastExpr, while any other number of arguments are
66 // represented by CXXTemporaryObjectExpr:
67 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr const * expr)
68 { return visitTemporaryObjectExpr(expr); }
69 bool VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr const * expr)
70 { return visitTemporaryObjectExpr(expr); }
72 private:
73 void checkUnoReference(QualType qt, const Decl* decl,
74 const RecordDecl* parent, const std::string& rDeclName);
76 bool visitTemporaryObjectExpr(Expr const * expr);
77 bool isCastingReference(const Expr* expr);
78 bool isCallingGetOnWeakRef(const Expr* expr);
81 bool containsXInterfaceSubclass(const clang::Type* pType0);
83 bool containsXInterfaceSubclass(const QualType& qType) {
84 return containsXInterfaceSubclass(qType.getTypePtr());
87 bool containsXInterfaceSubclass(const clang::Type* pType0) {
88 if (!pType0)
89 return false;
90 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
91 if (!pType)
92 return false;
93 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
94 if (pRecordDecl) {
95 pRecordDecl = pRecordDecl->getCanonicalDecl();
96 // these classes override acquire/release and forwards to its parent
97 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("ListenerMultiplexerBase").GlobalNamespace()); })) { // module UnoTools
98 return false;
100 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("GridEventForwarder").Namespace("toolkit").GlobalNamespace()); })) { // module toolkit
101 return false;
103 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("OWeakSubObject").GlobalNamespace()); })) { // module svx
104 return false;
106 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("OSbaWeakSubObject").Namespace("dbaui").GlobalNamespace()); })) { // module dbaccess
107 return false;
109 // FIXME This class has private operator new, and I cannot figure out how it can be dynamically instantiated
110 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("XPropertyList").GlobalNamespace()); })) { // module svx
111 return false;
113 // tdf#114596
114 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("OBookmarkContainer").Namespace("dbaccess").GlobalNamespace()); })) { // module dbaccess
115 return false;
118 // tdf#114596
119 if (loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("OCollection").Namespace("dbaccess").GlobalNamespace()); })) { // module dbaccess
120 return false;
123 if (pRecordDecl) {
124 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
125 if (pTemplate) {
126 // Probably good templates:
127 loplugin::DeclCheck dc(pTemplate);
128 if ((dc.Struct("FindUnoInstanceHint").AnonymousNamespace()
129 .GlobalNamespace())
130 || (dc.Class("OMultiInstanceAutoRegistration").Namespace("abp")
131 .GlobalNamespace())
132 || (dc.Class("Reference").Namespace("uno").Namespace("star")
133 .Namespace("sun").Namespace("com").GlobalNamespace())
134 || (dc.Class("WeakReference").Namespace("uno").Namespace("star")
135 .Namespace("sun").Namespace("com").GlobalNamespace())
136 || (dc.Class("Sequence").Namespace("uno").Namespace("star")
137 .Namespace("sun").Namespace("com").GlobalNamespace())
138 || (dc.Class("WeakCppRef").Namespace("accessibility")
139 .GlobalNamespace())
140 || (dc.Class("OAutoRegistration").Namespace("dba")
141 .GlobalNamespace())
142 || (dc.Class("OMultiInstanceAutoRegistration").Namespace("dbp")
143 .GlobalNamespace())
144 || (dc.Class("OMultiInstanceAutoRegistration")
145 .Namespace("dbaui").GlobalNamespace())
146 || (dc.Class("OMultiInstanceAutoRegistration")
147 .Namespace("dbaxml").GlobalNamespace())
148 || (dc.Struct("ReferenceEqual").Namespace("io_acceptor")
149 .GlobalNamespace())
150 || (dc.Struct("ReferenceHash").Namespace("io_acceptor")
151 .GlobalNamespace())
152 || (dc.Class("OAutoRegistration").Namespace("comphelper")
153 .GlobalNamespace())
154 || dc.Class("WeakBag").Namespace("comphelper").GlobalNamespace()
155 || (dc.Struct("class_").Namespace("service_decl")
156 .Namespace("comphelper").GlobalNamespace())
157 || (dc.Struct("vba_service_class_").Namespace("service_decl")
158 .Namespace("comphelper").GlobalNamespace())
159 || (dc.Struct("inheritingClass_").Namespace("service_decl")
160 .Namespace("comphelper").GlobalNamespace())
161 || (dc.Class("OAutoRegistration").Namespace("module")
162 .Namespace("comphelper").GlobalNamespace())
163 || (dc.Class("mem_fun1_t").Namespace("comphelper")
164 .GlobalNamespace())
165 || (dc.Class("OSimpleListenerContainer").Namespace("comphelper")
166 .GlobalNamespace())
167 || (dc.Class("OAutoRegistration").Namespace("dbmm")
168 .GlobalNamespace())
169 || (dc.Class("OAutoRegistration").Namespace("pcr")
170 .GlobalNamespace())
171 || (dc.Class("ComponentMethodGuard").Namespace("logging")
172 .GlobalNamespace())
173 || (dc.Class("OAutoRegistration").Namespace("logging")
174 .GlobalNamespace())
175 || dc.Class("Reference").Namespace("rtl").GlobalNamespace()
176 || (dc.Class("OAutoRegistration").Namespace("sdbtools")
177 .GlobalNamespace())
178 || (dc.Struct("ReferenceEqual").Namespace("stoc_connector")
179 .GlobalNamespace())
180 || (dc.Struct("ReferenceHash").Namespace("stoc_connector")
181 .GlobalNamespace())
182 || dc.Class("mem_fun_t").StdNamespace()
183 || dc.Class("mem_fun1_t").StdNamespace()
184 || dc.Class("SwIterator").GlobalNamespace()
185 || (dc.Class("SharedUNOComponent").Namespace("utl")
186 .GlobalNamespace())
187 || (dc.Class("OAutoRegistration").Namespace("utl")
188 .GlobalNamespace())
189 || (dc.Class("DeleteUnoReferenceOnDeinit").Namespace("vcl")
190 .GlobalNamespace())
191 || (dc.Struct("OInterfaceCompare").Namespace("xmloff")
192 .GlobalNamespace()))
194 return false;
198 if (pType->isPointerType()) {
199 // ignore
200 return false;
201 } else if (pType->isArrayType()) {
202 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
203 QualType elementType = pArrayType->getElementType();
204 return containsXInterfaceSubclass(elementType);
205 } else {
206 return loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("XInterface").Namespace("uno").Namespace("star").Namespace("sun").Namespace("com").GlobalNamespace()); });
210 bool containsOWeakObjectSubclass(const clang::Type* pType0);
212 bool containsOWeakObjectSubclass(const QualType& qType) {
213 return containsOWeakObjectSubclass(qType.getTypePtr());
216 bool containsOWeakObjectSubclass(const clang::Type* pType0) {
217 if (!pType0)
218 return false;
219 if (pType0->isDependentType()) {
220 return false;
222 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
223 if (!pType)
224 return false;
225 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
226 if (pRecordDecl) {
227 // because dbaccess just has to be special...
228 loplugin::DeclCheck dc(pRecordDecl);
229 if (dc.Class("DocumentEvents").Namespace("dbaccess")
230 .GlobalNamespace() ||
231 dc.Class("OBookmarkContainer").Namespace("dbaccess")
232 .GlobalNamespace())
233 return false;
234 // TODO not sure about these ones, just avoiding dbaccess in general for now
235 if (dc.Class("SbaXPropertiesChangeMultiplexer").Namespace("dbaui").GlobalNamespace() ||
236 dc.Class("SbaXSubmitMultiplexer").Namespace("dbaui").GlobalNamespace() ||
237 dc.Class("SbaXResetMultiplexer").Namespace("dbaui").GlobalNamespace() ||
238 dc.Class("SbaXPropertyChangeMultiplexer").Namespace("dbaui").GlobalNamespace() ||
239 dc.Class("SbaXSQLErrorMultiplexer").Namespace("dbaui").GlobalNamespace() ||
240 dc.Class("SbaXParameterMultiplexer").Namespace("dbaui").GlobalNamespace() ||
241 dc.Class("SbaXRowSetApproveMultiplexer").Namespace("dbaui").GlobalNamespace() ||
242 dc.Class("SbaXRowSetMultiplexer").Namespace("dbaui").GlobalNamespace() ||
243 dc.Class("SbaXLoadMultiplexer").Namespace("dbaui").GlobalNamespace() ||
244 dc.Class("SbaXVetoableChangeMultiplexer").Namespace("dbaui").GlobalNamespace())
245 return false;
246 // slideshow playing games here
247 if (dc.Class("SlideView").AnonymousNamespace().Namespace("internal").Namespace("slideshow").GlobalNamespace())
248 return false;
249 // svx playing acquire/release games here in OWeakSubObject
250 if (dc.Class("FmXUpdateMultiplexer").GlobalNamespace() ||
251 dc.Class("FmXContainerMultiplexer").GlobalNamespace() ||
252 dc.Class("FmXSelectionMultiplexer").GlobalNamespace() ||
253 dc.Class("FmXGridControlMultiplexer").GlobalNamespace() ||
254 dc.Class("FmXModifyMultiplexer").GlobalNamespace())
255 return false;
257 if (pType->isPointerType()) {
258 // ignore
259 return false;
260 } else if (pType->isArrayType()) {
261 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
262 QualType elementType = pArrayType->getElementType();
263 return containsOWeakObjectSubclass(elementType);
264 } else {
265 return loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("OWeakObject").Namespace("cppu").GlobalNamespace()); });
269 bool containsSvRefBaseSubclass(const clang::Type* pType0) {
270 if (!pType0)
271 return false;
272 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
273 if (!pType)
274 return false;
275 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
276 if (pRecordDecl) {
277 pRecordDecl = pRecordDecl->getCanonicalDecl();
279 if (pRecordDecl) {
280 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
281 if (pTemplate) {
282 if (loplugin::DeclCheck(pTemplate).Class("SvRef")
283 .Namespace("tools").GlobalNamespace())
285 return false;
287 for(unsigned i=0; i<pTemplate->getTemplateArgs().size(); ++i) {
288 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[i];
289 if (rArg.getKind() == TemplateArgument::ArgKind::Type &&
290 containsSvRefBaseSubclass(rArg.getAsType().getTypePtr()))
292 return true;
297 if (pType->isPointerType()) {
298 // ignore
299 return false;
300 } else if (pType->isArrayType()) {
301 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
302 QualType elementType = pArrayType->getElementType();
303 return containsSvRefBaseSubclass(elementType.getTypePtr());
304 } else {
305 return loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("SvRefBase").Namespace("tools").GlobalNamespace()); });
309 bool containsSalhelperReferenceObjectSubclass(const clang::Type* pType0) {
310 if (!pType0)
311 return false;
312 const clang::Type* pType = pType0->getUnqualifiedDesugaredType();
313 if (!pType)
314 return false;
315 const CXXRecordDecl* pRecordDecl = pType->getAsCXXRecordDecl();
316 if (pRecordDecl) {
317 pRecordDecl = pRecordDecl->getCanonicalDecl();
319 if (pRecordDecl) {
320 // for performance reasons we sometimes allocate temporaries on the stack
321 if (loplugin::DeclCheck(pRecordDecl).Struct("ScSheetLimits").GlobalNamespace())
322 return false;
324 // the calc excel filter likes storing lots of classes either by reference or by value
325 if (loplugin::isDerivedFrom(pRecordDecl,
326 [](Decl const * decl) -> bool
328 return
329 bool(loplugin::DeclCheck(decl).Class("XclExpRecordBase").GlobalNamespace())
330 || bool(loplugin::DeclCheck(decl).Class("XclImpChLineFormat").GlobalNamespace());
332 return false;
334 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
335 if (pTemplate) {
336 auto const dc = loplugin::DeclCheck(pTemplate);
337 if (dc.Class("Reference").Namespace("rtl").GlobalNamespace()
338 || (dc.Class("OStoreHandle").AnonymousNamespace().Namespace("store")
339 .GlobalNamespace()))
341 return false;
343 for(unsigned i=0; i<pTemplate->getTemplateArgs().size(); ++i) {
344 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[i];
345 if (rArg.getKind() == TemplateArgument::ArgKind::Type &&
346 containsSalhelperReferenceObjectSubclass(rArg.getAsType().getTypePtr()))
348 return true;
353 if (pType->isPointerType()) {
354 // ignore
355 return false;
356 } else if (pType->isArrayType()) {
357 const clang::ArrayType* pArrayType = dyn_cast<clang::ArrayType>(pType);
358 QualType elementType = pArrayType->getElementType();
359 return containsSalhelperReferenceObjectSubclass(elementType.getTypePtr());
360 } else {
361 return loplugin::isDerivedFrom(pRecordDecl, [](Decl const * decl) -> bool { return bool(loplugin::DeclCheck(decl).Class("SimpleReferenceObject").Namespace("salhelper").GlobalNamespace()); });
365 static bool containsStaticTypeMethod(const CXXRecordDecl* x)
367 for (auto it = x->method_begin(); it != x->method_end(); ++it) {
368 auto i = *it;
369 if ( !i->isStatic() )
370 continue;
371 auto ident = i->getIdentifier();
372 if ( ident && ident->isStr("static_type") ) {
373 return true;
376 return false;
379 void RefCounting::checkUnoReference(QualType qt, const Decl* decl, const RecordDecl* parent, const std::string& rDeclName)
381 if (loplugin::TypeCheck(qt).Class("Reference").Namespace("uno").Namespace("star").Namespace("sun").Namespace("com").GlobalNamespace()) {
382 const CXXRecordDecl* pRecordDecl = qt->getAsCXXRecordDecl();
383 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
384 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[0];
385 const CXXRecordDecl* templateParam = rArg.getAsType()->getAsCXXRecordDecl()->getDefinition();
386 if (templateParam && !containsStaticTypeMethod(templateParam)) {
387 report(
388 DiagnosticsEngine::Warning,
389 ("uno::Reference %0 with template parameter that does not"
390 " contain ::static_type() %1%select{|, parent is %3,}2 should"
391 " probably be using rtl::Reference instead"),
392 decl->getLocation())
393 << rDeclName << qt << (parent != nullptr)
394 << (parent != nullptr
395 ? parent->getQualifiedNameAsString() : std::string())
396 << decl->getSourceRange();
401 bool RefCounting::visitTemporaryObjectExpr(Expr const * expr) {
402 if (ignoreLocation(expr)) {
403 return true;
405 auto t = expr->getType();
406 if (containsSvRefBaseSubclass(t.getTypePtr())) {
407 report(
408 DiagnosticsEngine::Warning,
409 ("Temporary object of SvRefBase subclass %0 being directly stack"
410 " managed, should be managed via tools::SvRef"),
411 expr->getBeginLoc())
412 << t.getUnqualifiedType() << expr->getSourceRange();
413 } else if (containsSalhelperReferenceObjectSubclass(t.getTypePtr())) {
414 report(
415 DiagnosticsEngine::Warning,
416 ("Temporary object of salhelper::SimpleReferenceObject subclass %0"
417 " being directly stack managed, should be managed via"
418 " rtl::Reference"),
419 expr->getBeginLoc())
420 << t.getUnqualifiedType() << expr->getSourceRange();
421 } else if (containsXInterfaceSubclass(t)) {
422 report(
423 DiagnosticsEngine::Warning,
424 ("Temporary object of css::uno::XInterface subclass %0 being"
425 " directly stack managed, should be managed via"
426 " css::uno::Reference"),
427 expr->getBeginLoc())
428 << t.getUnqualifiedType() << expr->getSourceRange();
429 } else if (containsOWeakObjectSubclass(t)) {
430 report(
431 DiagnosticsEngine::Warning,
432 ("Temporary object of cppu::OWeakObject subclass %0 being"
433 " directly stack managed, should be managed via"
434 " css::uno::Reference"),
435 expr->getBeginLoc())
436 << t.getUnqualifiedType() << expr->getSourceRange();
438 return true;
441 // check for dodgy code managing ref-counted stuff with shared_ptr or unique_ptr or similar stuff
442 bool RefCounting::VisitTypeLoc(clang::TypeLoc typeLoc)
444 QualType firstTemplateParamType;
445 if (auto recordType = typeLoc.getType()->getUnqualifiedDesugaredType()->getAs<RecordType>()) {
446 auto const tc = loplugin::TypeCheck(recordType);
447 if (tc.ClassOrStruct("unique_ptr").StdNamespace()
448 || tc.ClassOrStruct("weak_ptr").StdNamespace()
449 || tc.ClassOrStruct("shared_ptr").StdNamespace()
450 || tc.ClassOrStruct("intrusive_ptr").Namespace("boost").GlobalNamespace())
452 auto templateDecl = dyn_cast<ClassTemplateSpecializationDecl>(recordType->getDecl());
453 if (templateDecl && templateDecl->getTemplateArgs().size() > 0)
454 firstTemplateParamType = templateDecl->getTemplateArgs()[0].getAsType();
457 if (firstTemplateParamType.isNull())
458 return true;
459 if (containsSvRefBaseSubclass(firstTemplateParamType.getTypePtr()))
461 report(
462 DiagnosticsEngine::Warning,
463 "SvRefBase subclass %0 being managed via smart pointer, should be managed via tools::SvRef",
464 typeLoc.getBeginLoc())
465 << firstTemplateParamType
466 << typeLoc.getSourceRange();
468 if (containsSalhelperReferenceObjectSubclass(firstTemplateParamType.getTypePtr()))
470 report(
471 DiagnosticsEngine::Warning,
472 "salhelper::SimpleReferenceObject subclass %0 being managed via smart pointer, should be managed via rtl::Reference",
473 typeLoc.getBeginLoc())
474 << firstTemplateParamType
475 << typeLoc.getSourceRange();
477 // Not in general (dbaccess::DocumentEvents, dbaccess/source/core/dataaccess/databasedocument.hxx):
478 #if 0
479 if (containsXInterfaceSubclass(firstTemplateParamType))
481 report(
482 DiagnosticsEngine::Warning,
483 "XInterface subclass %0 being managed via smart pointer, should be managed via uno::Reference",
484 typeLoc.getBeginLoc())
485 << firstTemplateParamType
486 << typeLoc.getSourceRange();
488 #endif
489 if (containsOWeakObjectSubclass(firstTemplateParamType.getTypePtr()))
491 report(
492 DiagnosticsEngine::Warning,
493 "cppu::OWeakObject subclass %0 being managed via smart pointer, should be managed via rtl::Reference",
494 typeLoc.getBeginLoc())
495 << firstTemplateParamType
496 << typeLoc.getSourceRange();
498 return true;
501 bool RefCounting::VisitCXXDeleteExpr(const CXXDeleteExpr * cxxDeleteExpr)
503 if (ignoreLocation(cxxDeleteExpr))
504 return true;
505 StringRef aFileName = getFilenameOfLocation(
506 compiler.getSourceManager().getSpellingLoc(cxxDeleteExpr->getBeginLoc()));
507 if (loplugin::isSamePathname(aFileName, SRCDIR "/cppuhelper/source/weak.cxx"))
508 return true;
509 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/svx/svdobj.hxx"))
510 return true;
511 if (loplugin::isSamePathname(aFileName, SRCDIR "/svx/source/svdraw/svdobj.cxx"))
512 return true;
514 if (!cxxDeleteExpr->getArgument())
515 return true;
516 auto argType = cxxDeleteExpr->getArgument()->getType();
517 if (argType.isNull() || !argType->isPointerType())
518 return true;
519 auto pointeeType = argType->getPointeeType();
520 if (containsOWeakObjectSubclass(pointeeType))
522 report(
523 DiagnosticsEngine::Warning,
524 "cppu::OWeakObject subclass %0 being deleted via delete, should be managed via rtl::Reference",
525 cxxDeleteExpr->getBeginLoc())
526 << pointeeType
527 << cxxDeleteExpr->getSourceRange();
529 return true;
532 bool RefCounting::VisitFieldDecl(const FieldDecl * fieldDecl) {
533 if (ignoreLocation(fieldDecl)) {
534 return true;
536 if (fieldDecl->isBitField()) {
537 return true;
540 // We can't call FieldDecl::getParent, which triggers an assertion at least with
541 // current trunk towards Clang 3.7 when the FieldDecl is actually an
542 // ObjCIvarDecl.
543 if (isa<ObjCIvarDecl>(fieldDecl)) {
544 return true;
547 if (containsSvRefBaseSubclass(fieldDecl->getType().getTypePtr())) {
548 report(
549 DiagnosticsEngine::Warning,
550 "SvRefBase subclass %0 being directly heap managed, should be managed via tools::SvRef, "
551 ", parent is %1",
552 fieldDecl->getLocation())
553 << fieldDecl->getType()
554 << fieldDecl->getParent()
555 << fieldDecl->getSourceRange();
558 if (containsSalhelperReferenceObjectSubclass(fieldDecl->getType().getTypePtr())) {
559 report(
560 DiagnosticsEngine::Warning,
561 "salhelper::SimpleReferenceObject subclass %0 being directly heap managed, should be managed via rtl::Reference, "
562 "parent is %1",
563 fieldDecl->getLocation())
564 << fieldDecl->getType()
565 << fieldDecl->getParent()
566 << fieldDecl->getSourceRange();
569 auto const dc = loplugin::DeclCheck(fieldDecl->getParent());
570 if ( (dc.Class("BaseReference").Namespace("uno").Namespace("star")
571 .Namespace("sun").Namespace("com").GlobalNamespace())
572 || (dc.Class("Reference").Namespace("rtl").GlobalNamespace())
573 || (dc.Union("element_alias").Namespace("detail").Namespace("cppu")
574 .GlobalNamespace())
575 // this is playing some kind of game to avoid circular references
576 || (dc.Class("ResultSetDataSupplier").Namespace("ucbhelper")
577 .GlobalNamespace()))
579 return true;
582 if (containsXInterfaceSubclass(fieldDecl->getType())) {
583 report(
584 DiagnosticsEngine::Warning,
585 "XInterface subclass %0 being directly heap managed, should be managed via uno::Reference, "
586 "parent is %1",
587 fieldDecl->getLocation())
588 << fieldDecl->getType()
589 << fieldDecl->getParent()
590 << fieldDecl->getSourceRange();
593 if (containsOWeakObjectSubclass(fieldDecl->getType())) {
594 report(
595 DiagnosticsEngine::Warning,
596 "cppu::OWeakObject subclass %0 being directly heap managed, should be managed via rtl::Reference, "
597 "parent is %1",
598 fieldDecl->getLocation())
599 << fieldDecl->getType()
600 << fieldDecl->getParent()
601 << fieldDecl->getSourceRange();
604 checkUnoReference(
605 fieldDecl->getType(), fieldDecl,
606 fieldDecl->getParent(), "field");
608 return true;
611 bool RefCounting::VisitReturnStmt(const ReturnStmt * returnStmt) {
612 if (ignoreLocation(returnStmt)) {
613 return true;
616 if (!returnStmt->getRetValue())
617 return true;
618 auto cxxNewExpr = dyn_cast<CXXNewExpr>(returnStmt->getRetValue()->IgnoreImplicit());
619 if (!cxxNewExpr)
620 return true;
622 auto qt = returnStmt->getRetValue()->getType();
623 if (!qt->isPointerType())
624 return false;
625 qt = qt->getPointeeType();
627 if (containsOWeakObjectSubclass(qt)) {
628 report(
629 DiagnosticsEngine::Warning,
630 "new object of cppu::OWeakObject subclass %0 being returned via raw pointer, should be returned by via rtl::Reference",
631 returnStmt->getBeginLoc())
632 << qt
633 << returnStmt->getSourceRange();
636 return true;
639 bool RefCounting::VisitVarDecl(const VarDecl * varDecl) {
640 if (ignoreLocation(varDecl))
641 return true;
643 checkUnoReference(varDecl->getType(), varDecl, nullptr, "var");
645 if (isa<ParmVarDecl>(varDecl))
646 return true;
648 if (containsSvRefBaseSubclass(varDecl->getType().getTypePtr())) {
649 report(
650 DiagnosticsEngine::Warning,
651 "SvRefBase subclass being directly stack managed, should be managed via tools::SvRef, "
652 + varDecl->getType().getAsString(),
653 varDecl->getLocation())
654 << varDecl->getSourceRange();
656 if (containsSalhelperReferenceObjectSubclass(varDecl->getType().getTypePtr())) {
657 StringRef name { getFilenameOfLocation(
658 compiler.getSourceManager().getSpellingLoc(varDecl->getLocation())) };
659 // this is playing games that it believes is safe
660 if (loplugin::isSamePathname(name, SRCDIR "/stoc/source/security/permissions.cxx"))
661 return true;
662 report(
663 DiagnosticsEngine::Warning,
664 "salhelper::SimpleReferenceObject subclass being directly stack managed, should be managed via rtl::Reference, "
665 + varDecl->getType().getAsString(),
666 varDecl->getLocation())
667 << varDecl->getSourceRange();
669 if (containsXInterfaceSubclass(varDecl->getType())) {
670 report(
671 DiagnosticsEngine::Warning,
672 "XInterface subclass being directly stack managed, should be managed via uno::Reference, "
673 + varDecl->getType().getAsString(),
674 varDecl->getLocation())
675 << varDecl->getSourceRange();
677 if (containsOWeakObjectSubclass(varDecl->getType())) {
678 report(
679 DiagnosticsEngine::Warning,
680 "cppu::OWeakObject subclass being directly stack managed, should be managed via uno::Reference, "
681 + varDecl->getType().getAsString(),
682 varDecl->getLocation())
683 << varDecl->getSourceRange();
686 if (varDecl->getType()->isPointerType() && varDecl->getInit())
688 auto newExpr = dyn_cast<CXXNewExpr>(varDecl->getInit()->IgnoreImplicit());
689 if (newExpr)
691 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(varDecl->getBeginLoc()));
692 if (loplugin::isSamePathname(fileName, SRCDIR "/cppuhelper/source/component_context.cxx"))
693 return true;
694 auto pointeeType = varDecl->getType()->getPointeeType();
695 if (containsOWeakObjectSubclass(pointeeType))
696 report(
697 DiagnosticsEngine::Warning,
698 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
699 varDecl->getLocation())
700 << pointeeType
701 << varDecl->getSourceRange();
703 if (isCastingReference(varDecl->getInit()))
705 // TODO false+ code
706 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(varDecl->getBeginLoc()));
707 if (loplugin::isSamePathname(fileName, SRCDIR "/sw/source/core/unocore/unotbl.cxx"))
708 return true;
709 auto pointeeType = varDecl->getType()->getPointeeType();
710 if (containsOWeakObjectSubclass(pointeeType))
711 report(
712 DiagnosticsEngine::Warning,
713 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
714 varDecl->getLocation())
715 << pointeeType
716 << varDecl->getSourceRange();
718 if (isCallingGetOnWeakRef(varDecl->getInit()))
720 auto pointeeType = varDecl->getType()->getPointeeType();
721 if (containsOWeakObjectSubclass(pointeeType))
722 report(
723 DiagnosticsEngine::Warning,
724 "weak object being converted to strong, and then the reference dropped, and managed via raw pointer, should be managed via rtl::Reference",
725 varDecl->getLocation())
726 << pointeeType
727 << varDecl->getSourceRange();
730 return true;
734 Look for code like
735 static_cast<FooChild*>(makeFoo().get());
736 where makeFoo() returns a Reference<Foo>
738 bool RefCounting::isCastingReference(const Expr* expr)
740 expr = expr->IgnoreImplicit();
741 auto castExpr = dyn_cast<CastExpr>(expr);
742 if (!castExpr)
743 return false;
744 auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(castExpr->getSubExpr());
745 if (!memberCallExpr)
746 return false;
747 if (!memberCallExpr->getMethodDecl()->getIdentifier() || memberCallExpr->getMethodDecl()->getName() != "get")
748 return false;
749 QualType objectType = memberCallExpr->getImplicitObjectArgument()->getType();
750 if (!loplugin::TypeCheck(objectType).Class("Reference"))
751 return false;
752 // ignore "x.get()" where x is a var
753 auto obj = memberCallExpr->getImplicitObjectArgument()->IgnoreImplicit();
754 if (isa<DeclRefExpr>(obj) || isa<MemberExpr>(obj))
755 return false;
756 // if the foo in foo().get() returns "rtl::Reference<T>&" then the variable
757 // we are assigning to does not __have__ to be Reference, since the method called
758 // must already be holding a reference.
759 if (auto callExpr = dyn_cast<CallExpr>(obj))
761 if (auto callMethod = callExpr->getDirectCallee())
762 if (callMethod->getReturnType()->isReferenceType())
763 return false;
765 // Ignore
766 // WeakReference x;
767 // if (x.get.get())
768 // and similar stuff
769 if (auto memberCall2 = dyn_cast<CXXMemberCallExpr>(obj))
771 if (loplugin::TypeCheck(memberCall2->getImplicitObjectArgument()->getType()).Class("WeakReference"))
772 return false;
774 return true;
778 Look for code like
779 makeFoo().get();
781 cast<T*>(makeFoo().get().get());
783 foo.get();
784 where makeFoo() returns a unotools::WeakReference<Foo>
785 and foo is a unotools::WeakReference<Foo> var.
787 bool RefCounting::isCallingGetOnWeakRef(const Expr* expr)
789 expr = expr->IgnoreImplicit();
790 // unwrap the cast (if any)
791 if (auto castExpr = dyn_cast<CastExpr>(expr))
792 expr = castExpr->getSubExpr()->IgnoreImplicit();
793 // unwrap outer get (if any)
794 if (auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(expr))
796 auto methodDecl = memberCallExpr->getMethodDecl();
797 if (methodDecl && methodDecl->getIdentifier() && methodDecl->getName() == "get")
799 QualType objectType = memberCallExpr->getImplicitObjectArgument()->getType();
800 if (loplugin::TypeCheck(objectType).Class("Reference").Namespace("rtl"))
801 expr = memberCallExpr->getImplicitObjectArgument()->IgnoreImplicit();
804 // check for converting a WeakReference to a strong reference via get()
805 if (auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(expr))
807 auto methodDecl = memberCallExpr->getMethodDecl();
808 if (methodDecl && methodDecl->getIdentifier() && methodDecl->getName() == "get")
810 QualType objectType = memberCallExpr->getImplicitObjectArgument()->getType();
811 if (loplugin::TypeCheck(objectType).Class("WeakReference").Namespace("unotools"))
812 return true;
815 return false;
818 bool RefCounting::VisitBinaryOperator(const BinaryOperator * binaryOperator)
820 if (ignoreLocation(binaryOperator))
821 return true;
822 if (binaryOperator->getOpcode() != BO_Assign)
823 return true;
824 if (!binaryOperator->getLHS()->getType()->isPointerType())
825 return true;
827 auto newExpr = dyn_cast<CXXNewExpr>(binaryOperator->getRHS()->IgnoreImplicit());
828 if (newExpr)
830 // deliberately does not want to keep track at the allocation site
831 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(binaryOperator->getBeginLoc()));
832 if (loplugin::isSamePathname(fileName, SRCDIR "/vcl/unx/generic/dtrans/X11_selection.cxx"))
833 return true;
835 auto pointeeType = binaryOperator->getLHS()->getType()->getPointeeType();
836 if (containsOWeakObjectSubclass(pointeeType))
838 report(
839 DiagnosticsEngine::Warning,
840 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
841 binaryOperator->getBeginLoc())
842 << pointeeType
843 << binaryOperator->getSourceRange();
846 if (isCastingReference(binaryOperator->getRHS()))
848 auto pointeeType = binaryOperator->getLHS()->getType()->getPointeeType();
849 if (containsOWeakObjectSubclass(pointeeType))
850 report(
851 DiagnosticsEngine::Warning,
852 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
853 binaryOperator->getBeginLoc())
854 << pointeeType
855 << binaryOperator->getSourceRange();
857 if (isCallingGetOnWeakRef(binaryOperator->getRHS()))
859 // TODO Very dodgy code, but I see no simple way of fixing it
860 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(binaryOperator->getBeginLoc()));
861 if (loplugin::isSamePathname(fileName, SRCDIR "/sd/source/ui/view/Outliner.cxx"))
862 return true;
863 auto pointeeType = binaryOperator->getLHS()->getType()->getPointeeType();
864 if (containsOWeakObjectSubclass(pointeeType))
865 report(
866 DiagnosticsEngine::Warning,
867 "weak object being converted to strong, and then the reference dropped, and managed via raw pointer, should be managed via rtl::Reference",
868 binaryOperator->getBeginLoc())
869 << pointeeType
870 << binaryOperator->getSourceRange();
872 return true;
875 bool RefCounting::VisitFunctionDecl(const FunctionDecl * functionDecl) {
876 if (ignoreLocation(functionDecl)) {
877 return true;
879 // only consider base declarations, not overridden ones, or we warn on methods that
880 // are overriding stuff from external libraries
881 const CXXMethodDecl * methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
882 if (methodDecl && methodDecl->size_overridden_methods() > 0) {
883 return true;
885 checkUnoReference(functionDecl->getReturnType(), functionDecl, nullptr, "return");
886 return true;
889 loplugin::Plugin::Registration< RefCounting > refcounting("refcounting");
893 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */