Remove exec bits from docx
[LibreOffice.git] / compilerplugins / clang / refcounting.cxx
blob801173ce6488d9ce8eb8502575cdd802f087a1e6
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 return;
383 const CXXRecordDecl* pRecordDecl = qt->getAsCXXRecordDecl();
384 const ClassTemplateSpecializationDecl* pTemplate = dyn_cast<ClassTemplateSpecializationDecl>(pRecordDecl);
385 const TemplateArgument& rArg = pTemplate->getTemplateArgs()[0];
386 const CXXRecordDecl* templateParam = rArg.getAsType()->getAsCXXRecordDecl()->getDefinition();
387 if (!templateParam)
388 return;
389 // SwXText is a special case. It is a mixin class that does not inherit from OWeakObject, so
390 // we cannot use rtl::Reference.
391 if (loplugin::DeclCheck(templateParam).Class("SwXText"))
392 return;
393 if (containsStaticTypeMethod(templateParam))
394 return;
395 report(
396 DiagnosticsEngine::Warning,
397 ("uno::Reference %0 with template parameter that does not"
398 " contain ::static_type() %1%select{|, parent is %3,}2 should"
399 " probably be using rtl::Reference instead"),
400 decl->getLocation())
401 << rDeclName << qt << (parent != nullptr)
402 << (parent != nullptr
403 ? parent->getQualifiedNameAsString() : std::string())
404 << decl->getSourceRange();
407 bool RefCounting::visitTemporaryObjectExpr(Expr const * expr) {
408 if (ignoreLocation(expr)) {
409 return true;
411 auto t = expr->getType();
412 if (containsSvRefBaseSubclass(t.getTypePtr())) {
413 report(
414 DiagnosticsEngine::Warning,
415 ("Temporary object of SvRefBase subclass %0 being directly stack"
416 " managed, should be managed via tools::SvRef"),
417 expr->getBeginLoc())
418 << t.getUnqualifiedType() << expr->getSourceRange();
419 } else if (containsSalhelperReferenceObjectSubclass(t.getTypePtr())) {
420 report(
421 DiagnosticsEngine::Warning,
422 ("Temporary object of salhelper::SimpleReferenceObject subclass %0"
423 " being directly stack managed, should be managed via"
424 " rtl::Reference"),
425 expr->getBeginLoc())
426 << t.getUnqualifiedType() << expr->getSourceRange();
427 } else if (containsXInterfaceSubclass(t)) {
428 report(
429 DiagnosticsEngine::Warning,
430 ("Temporary object of css::uno::XInterface subclass %0 being"
431 " directly stack managed, should be managed via"
432 " css::uno::Reference"),
433 expr->getBeginLoc())
434 << t.getUnqualifiedType() << expr->getSourceRange();
435 } else if (containsOWeakObjectSubclass(t)) {
436 report(
437 DiagnosticsEngine::Warning,
438 ("Temporary object of cppu::OWeakObject subclass %0 being"
439 " directly stack managed, should be managed via"
440 " css::uno::Reference"),
441 expr->getBeginLoc())
442 << t.getUnqualifiedType() << expr->getSourceRange();
444 return true;
447 // check for dodgy code managing ref-counted stuff with shared_ptr or unique_ptr or similar stuff
448 bool RefCounting::VisitTypeLoc(clang::TypeLoc typeLoc)
450 QualType firstTemplateParamType;
451 if (auto recordType = typeLoc.getType()->getUnqualifiedDesugaredType()->getAs<RecordType>()) {
452 auto const tc = loplugin::TypeCheck(recordType);
453 if (tc.ClassOrStruct("unique_ptr").StdNamespace()
454 || tc.ClassOrStruct("weak_ptr").StdNamespace()
455 || tc.ClassOrStruct("shared_ptr").StdNamespace()
456 || tc.ClassOrStruct("intrusive_ptr").Namespace("boost").GlobalNamespace())
458 auto templateDecl = dyn_cast<ClassTemplateSpecializationDecl>(recordType->getDecl());
459 if (templateDecl && templateDecl->getTemplateArgs().size() > 0)
460 firstTemplateParamType = templateDecl->getTemplateArgs()[0].getAsType();
463 if (firstTemplateParamType.isNull())
464 return true;
465 if (containsSvRefBaseSubclass(firstTemplateParamType.getTypePtr()))
467 report(
468 DiagnosticsEngine::Warning,
469 "SvRefBase subclass %0 being managed via smart pointer, should be managed via tools::SvRef",
470 typeLoc.getBeginLoc())
471 << firstTemplateParamType
472 << typeLoc.getSourceRange();
474 if (containsSalhelperReferenceObjectSubclass(firstTemplateParamType.getTypePtr()))
476 report(
477 DiagnosticsEngine::Warning,
478 "salhelper::SimpleReferenceObject subclass %0 being managed via smart pointer, should be managed via rtl::Reference",
479 typeLoc.getBeginLoc())
480 << firstTemplateParamType
481 << typeLoc.getSourceRange();
483 // Not in general (dbaccess::DocumentEvents, dbaccess/source/core/dataaccess/databasedocument.hxx):
484 #if 0
485 if (containsXInterfaceSubclass(firstTemplateParamType))
487 report(
488 DiagnosticsEngine::Warning,
489 "XInterface subclass %0 being managed via smart pointer, should be managed via uno::Reference",
490 typeLoc.getBeginLoc())
491 << firstTemplateParamType
492 << typeLoc.getSourceRange();
494 #endif
495 if (containsOWeakObjectSubclass(firstTemplateParamType.getTypePtr()))
497 report(
498 DiagnosticsEngine::Warning,
499 "cppu::OWeakObject subclass %0 being managed via smart pointer, should be managed via rtl::Reference",
500 typeLoc.getBeginLoc())
501 << firstTemplateParamType
502 << typeLoc.getSourceRange();
504 return true;
507 bool RefCounting::VisitCXXDeleteExpr(const CXXDeleteExpr * cxxDeleteExpr)
509 if (ignoreLocation(cxxDeleteExpr))
510 return true;
511 StringRef aFileName = getFilenameOfLocation(
512 compiler.getSourceManager().getSpellingLoc(cxxDeleteExpr->getBeginLoc()));
513 if (loplugin::isSamePathname(aFileName, SRCDIR "/cppuhelper/source/weak.cxx"))
514 return true;
515 if (loplugin::isSamePathname(aFileName, SRCDIR "/include/svx/svdobj.hxx"))
516 return true;
517 if (loplugin::isSamePathname(aFileName, SRCDIR "/svx/source/svdraw/svdobj.cxx"))
518 return true;
520 if (!cxxDeleteExpr->getArgument())
521 return true;
522 auto argType = cxxDeleteExpr->getArgument()->getType();
523 if (argType.isNull() || !argType->isPointerType())
524 return true;
525 auto pointeeType = argType->getPointeeType();
526 if (containsOWeakObjectSubclass(pointeeType))
528 report(
529 DiagnosticsEngine::Warning,
530 "cppu::OWeakObject subclass %0 being deleted via delete, should be managed via rtl::Reference",
531 cxxDeleteExpr->getBeginLoc())
532 << pointeeType
533 << cxxDeleteExpr->getSourceRange();
535 return true;
538 bool RefCounting::VisitFieldDecl(const FieldDecl * fieldDecl) {
539 if (ignoreLocation(fieldDecl)) {
540 return true;
542 if (fieldDecl->isBitField()) {
543 return true;
546 // We can't call FieldDecl::getParent, which triggers an assertion at least with
547 // current trunk towards Clang 3.7 when the FieldDecl is actually an
548 // ObjCIvarDecl.
549 if (isa<ObjCIvarDecl>(fieldDecl)) {
550 return true;
553 if (containsSvRefBaseSubclass(fieldDecl->getType().getTypePtr())) {
554 report(
555 DiagnosticsEngine::Warning,
556 "SvRefBase subclass %0 being directly heap managed, should be managed via tools::SvRef, "
557 ", parent is %1",
558 fieldDecl->getLocation())
559 << fieldDecl->getType()
560 << fieldDecl->getParent()
561 << fieldDecl->getSourceRange();
564 if (containsSalhelperReferenceObjectSubclass(fieldDecl->getType().getTypePtr())) {
565 report(
566 DiagnosticsEngine::Warning,
567 "salhelper::SimpleReferenceObject subclass %0 being directly heap managed, should be managed via rtl::Reference, "
568 "parent is %1",
569 fieldDecl->getLocation())
570 << fieldDecl->getType()
571 << fieldDecl->getParent()
572 << fieldDecl->getSourceRange();
575 auto const dc = loplugin::DeclCheck(fieldDecl->getParent());
576 if ( (dc.Class("BaseReference").Namespace("uno").Namespace("star")
577 .Namespace("sun").Namespace("com").GlobalNamespace())
578 || (dc.Class("Reference").Namespace("rtl").GlobalNamespace())
579 || (dc.Union("element_alias").Namespace("detail").Namespace("cppu")
580 .GlobalNamespace())
581 // this is playing some kind of game to avoid circular references
582 || (dc.Class("ResultSetDataSupplier").Namespace("ucbhelper")
583 .GlobalNamespace()))
585 return true;
588 if (containsXInterfaceSubclass(fieldDecl->getType())) {
589 report(
590 DiagnosticsEngine::Warning,
591 "XInterface subclass %0 being directly heap managed, should be managed via uno::Reference, "
592 "parent is %1",
593 fieldDecl->getLocation())
594 << fieldDecl->getType()
595 << fieldDecl->getParent()
596 << fieldDecl->getSourceRange();
599 if (containsOWeakObjectSubclass(fieldDecl->getType())) {
600 report(
601 DiagnosticsEngine::Warning,
602 "cppu::OWeakObject subclass %0 being directly heap managed, should be managed via rtl::Reference, "
603 "parent is %1",
604 fieldDecl->getLocation())
605 << fieldDecl->getType()
606 << fieldDecl->getParent()
607 << fieldDecl->getSourceRange();
610 checkUnoReference(
611 fieldDecl->getType(), fieldDecl,
612 fieldDecl->getParent(), "field");
614 return true;
617 bool RefCounting::VisitReturnStmt(const ReturnStmt * returnStmt) {
618 if (ignoreLocation(returnStmt)) {
619 return true;
622 if (!returnStmt->getRetValue())
623 return true;
624 auto cxxNewExpr = dyn_cast<CXXNewExpr>(returnStmt->getRetValue()->IgnoreImplicit());
625 if (!cxxNewExpr)
626 return true;
628 auto qt = returnStmt->getRetValue()->getType();
629 if (!qt->isPointerType())
630 return false;
631 qt = qt->getPointeeType();
633 if (containsOWeakObjectSubclass(qt)) {
634 report(
635 DiagnosticsEngine::Warning,
636 "new object of cppu::OWeakObject subclass %0 being returned via raw pointer, should be returned by via rtl::Reference",
637 returnStmt->getBeginLoc())
638 << qt
639 << returnStmt->getSourceRange();
642 return true;
645 bool RefCounting::VisitVarDecl(const VarDecl * varDecl) {
646 if (ignoreLocation(varDecl))
647 return true;
649 checkUnoReference(varDecl->getType(), varDecl, nullptr, "var");
651 if (isa<ParmVarDecl>(varDecl))
652 return true;
654 if (containsSvRefBaseSubclass(varDecl->getType().getTypePtr())) {
655 report(
656 DiagnosticsEngine::Warning,
657 "SvRefBase subclass being directly stack managed, should be managed via tools::SvRef, "
658 + varDecl->getType().getAsString(),
659 varDecl->getLocation())
660 << varDecl->getSourceRange();
662 if (containsSalhelperReferenceObjectSubclass(varDecl->getType().getTypePtr())) {
663 StringRef name { getFilenameOfLocation(
664 compiler.getSourceManager().getSpellingLoc(varDecl->getLocation())) };
665 // this is playing games that it believes is safe
666 if (loplugin::isSamePathname(name, SRCDIR "/stoc/source/security/permissions.cxx"))
667 return true;
668 report(
669 DiagnosticsEngine::Warning,
670 "salhelper::SimpleReferenceObject subclass being directly stack managed, should be managed via rtl::Reference, "
671 + varDecl->getType().getAsString(),
672 varDecl->getLocation())
673 << varDecl->getSourceRange();
675 if (containsXInterfaceSubclass(varDecl->getType())) {
676 report(
677 DiagnosticsEngine::Warning,
678 "XInterface subclass being directly stack managed, should be managed via uno::Reference, "
679 + varDecl->getType().getAsString(),
680 varDecl->getLocation())
681 << varDecl->getSourceRange();
683 if (containsOWeakObjectSubclass(varDecl->getType())) {
684 report(
685 DiagnosticsEngine::Warning,
686 "cppu::OWeakObject subclass being directly stack managed, should be managed via uno::Reference, "
687 + varDecl->getType().getAsString(),
688 varDecl->getLocation())
689 << varDecl->getSourceRange();
692 if (varDecl->getType()->isPointerType() && varDecl->getInit())
694 auto newExpr = dyn_cast<CXXNewExpr>(varDecl->getInit()->IgnoreImplicit());
695 if (newExpr)
697 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(varDecl->getBeginLoc()));
698 if (loplugin::isSamePathname(fileName, SRCDIR "/cppuhelper/source/component_context.cxx"))
699 return true;
700 auto pointeeType = varDecl->getType()->getPointeeType();
701 if (containsOWeakObjectSubclass(pointeeType))
702 report(
703 DiagnosticsEngine::Warning,
704 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
705 varDecl->getLocation())
706 << pointeeType
707 << varDecl->getSourceRange();
709 if (isCastingReference(varDecl->getInit()))
711 // TODO false+ code
712 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(varDecl->getBeginLoc()));
713 if (loplugin::isSamePathname(fileName, SRCDIR "/sw/source/core/unocore/unotbl.cxx"))
714 return true;
715 auto pointeeType = varDecl->getType()->getPointeeType();
716 if (containsOWeakObjectSubclass(pointeeType))
717 report(
718 DiagnosticsEngine::Warning,
719 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
720 varDecl->getLocation())
721 << pointeeType
722 << varDecl->getSourceRange();
724 if (isCallingGetOnWeakRef(varDecl->getInit()))
726 auto pointeeType = varDecl->getType()->getPointeeType();
727 if (containsOWeakObjectSubclass(pointeeType))
728 report(
729 DiagnosticsEngine::Warning,
730 "weak object being converted to strong, and then the reference dropped, and managed via raw pointer, should be managed via rtl::Reference",
731 varDecl->getLocation())
732 << pointeeType
733 << varDecl->getSourceRange();
736 return true;
740 Look for code like
741 static_cast<FooChild*>(makeFoo().get());
742 where makeFoo() returns a Reference<Foo>
744 bool RefCounting::isCastingReference(const Expr* expr)
746 expr = expr->IgnoreImplicit();
747 auto castExpr = dyn_cast<CastExpr>(expr);
748 if (!castExpr)
749 return false;
750 auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(castExpr->getSubExpr());
751 if (!memberCallExpr)
752 return false;
753 if (!memberCallExpr->getMethodDecl()->getIdentifier() || memberCallExpr->getMethodDecl()->getName() != "get")
754 return false;
755 QualType objectType = memberCallExpr->getImplicitObjectArgument()->getType();
756 if (!loplugin::TypeCheck(objectType).Class("Reference"))
757 return false;
758 // ignore "x.get()" where x is a var
759 auto obj = memberCallExpr->getImplicitObjectArgument()->IgnoreImplicit();
760 if (isa<DeclRefExpr>(obj) || isa<MemberExpr>(obj))
761 return false;
762 // if the foo in foo().get() returns "rtl::Reference<T>&" then the variable
763 // we are assigning to does not __have__ to be Reference, since the method called
764 // must already be holding a reference.
765 if (auto callExpr = dyn_cast<CallExpr>(obj))
767 if (auto callMethod = callExpr->getDirectCallee())
768 if (callMethod->getReturnType()->isReferenceType())
769 return false;
771 // Ignore
772 // WeakReference x;
773 // if (x.get.get())
774 // and similar stuff
775 if (auto memberCall2 = dyn_cast<CXXMemberCallExpr>(obj))
777 if (loplugin::TypeCheck(memberCall2->getImplicitObjectArgument()->getType()).Class("WeakReference"))
778 return false;
780 return true;
784 Look for code like
785 makeFoo().get();
787 cast<T*>(makeFoo().get().get());
789 foo.get();
790 where makeFoo() returns a unotools::WeakReference<Foo>
791 and foo is a unotools::WeakReference<Foo> var.
793 bool RefCounting::isCallingGetOnWeakRef(const Expr* expr)
795 expr = expr->IgnoreImplicit();
796 // unwrap the cast (if any)
797 if (auto castExpr = dyn_cast<CastExpr>(expr))
798 expr = castExpr->getSubExpr()->IgnoreImplicit();
799 // unwrap outer get (if any)
800 if (auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(expr))
802 auto methodDecl = memberCallExpr->getMethodDecl();
803 if (methodDecl && methodDecl->getIdentifier() && methodDecl->getName() == "get")
805 QualType objectType = memberCallExpr->getImplicitObjectArgument()->getType();
806 if (loplugin::TypeCheck(objectType).Class("Reference").Namespace("rtl"))
807 expr = memberCallExpr->getImplicitObjectArgument()->IgnoreImplicit();
810 // check for converting a WeakReference to a strong reference via get()
811 if (auto memberCallExpr = dyn_cast<CXXMemberCallExpr>(expr))
813 auto methodDecl = memberCallExpr->getMethodDecl();
814 if (methodDecl && methodDecl->getIdentifier() && methodDecl->getName() == "get")
816 QualType objectType = memberCallExpr->getImplicitObjectArgument()->getType();
817 if (loplugin::TypeCheck(objectType).Class("WeakReference").Namespace("unotools"))
818 return true;
821 return false;
824 bool RefCounting::VisitBinaryOperator(const BinaryOperator * binaryOperator)
826 if (ignoreLocation(binaryOperator))
827 return true;
828 if (binaryOperator->getOpcode() != BO_Assign)
829 return true;
830 if (!binaryOperator->getLHS()->getType()->isPointerType())
831 return true;
833 auto newExpr = dyn_cast<CXXNewExpr>(binaryOperator->getRHS()->IgnoreImplicit());
834 if (newExpr)
836 // deliberately does not want to keep track at the allocation site
837 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(binaryOperator->getBeginLoc()));
838 if (loplugin::isSamePathname(fileName, SRCDIR "/vcl/unx/generic/dtrans/X11_selection.cxx"))
839 return true;
841 auto pointeeType = binaryOperator->getLHS()->getType()->getPointeeType();
842 if (containsOWeakObjectSubclass(pointeeType))
844 report(
845 DiagnosticsEngine::Warning,
846 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
847 binaryOperator->getBeginLoc())
848 << pointeeType
849 << binaryOperator->getSourceRange();
852 if (isCastingReference(binaryOperator->getRHS()))
854 auto pointeeType = binaryOperator->getLHS()->getType()->getPointeeType();
855 if (containsOWeakObjectSubclass(pointeeType))
856 report(
857 DiagnosticsEngine::Warning,
858 "cppu::OWeakObject subclass %0 being managed via raw pointer, should be managed via rtl::Reference",
859 binaryOperator->getBeginLoc())
860 << pointeeType
861 << binaryOperator->getSourceRange();
863 if (isCallingGetOnWeakRef(binaryOperator->getRHS()))
865 // TODO Very dodgy code, but I see no simple way of fixing it
866 StringRef fileName = getFilenameOfLocation(compiler.getSourceManager().getSpellingLoc(binaryOperator->getBeginLoc()));
867 if (loplugin::isSamePathname(fileName, SRCDIR "/sd/source/ui/view/Outliner.cxx"))
868 return true;
869 auto pointeeType = binaryOperator->getLHS()->getType()->getPointeeType();
870 if (containsOWeakObjectSubclass(pointeeType))
871 report(
872 DiagnosticsEngine::Warning,
873 "weak object being converted to strong, and then the reference dropped, and managed via raw pointer, should be managed via rtl::Reference",
874 binaryOperator->getBeginLoc())
875 << pointeeType
876 << binaryOperator->getSourceRange();
878 return true;
881 bool RefCounting::VisitFunctionDecl(const FunctionDecl * functionDecl) {
882 if (ignoreLocation(functionDecl)) {
883 return true;
885 // only consider base declarations, not overridden ones, or we warn on methods that
886 // are overriding stuff from external libraries
887 const CXXMethodDecl * methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
888 if (methodDecl && methodDecl->size_overridden_methods() > 0) {
889 return true;
891 checkUnoReference(functionDecl->getReturnType(), functionDecl, nullptr, "return");
892 return true;
895 loplugin::Plugin::Registration< RefCounting > refcounting("refcounting");
899 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */