Index: clang-tidy/cppcoreguidelines/CMakeLists.txt =================================================================== --- clang-tidy/cppcoreguidelines/CMakeLists.txt +++ clang-tidy/cppcoreguidelines/CMakeLists.txt @@ -4,6 +4,7 @@ CppCoreGuidelinesTidyModule.cpp InterfacesGlobalInitCheck.cpp NoMallocCheck.cpp + OwningMemoryCheck.cpp ProBoundsArrayToPointerDecayCheck.cpp ProBoundsConstantArrayIndexCheck.cpp ProBoundsPointerArithmeticCheck.cpp Index: clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp =================================================================== --- clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp +++ clang-tidy/cppcoreguidelines/CppCoreGuidelinesTidyModule.cpp @@ -13,6 +13,7 @@ #include "../misc/UnconventionalAssignOperatorCheck.h" #include "InterfacesGlobalInitCheck.h" #include "NoMallocCheck.h" +#include "OwningMemoryCheck.h" #include "ProBoundsArrayToPointerDecayCheck.h" #include "ProBoundsConstantArrayIndexCheck.h" #include "ProBoundsPointerArithmeticCheck.h" @@ -37,6 +38,8 @@ CheckFactories.registerCheck( "cppcoreguidelines-interfaces-global-init"); CheckFactories.registerCheck("cppcoreguidelines-no-malloc"); + CheckFactories.registerCheck( + "cppcoreguidelines-owning-memory"); CheckFactories.registerCheck( "cppcoreguidelines-pro-bounds-array-to-pointer-decay"); CheckFactories.registerCheck( Index: clang-tidy/cppcoreguidelines/OwningMemoryCheck.h =================================================================== --- /dev/null +++ clang-tidy/cppcoreguidelines/OwningMemoryCheck.h @@ -0,0 +1,45 @@ +//===--- OwningMemoryCheck.h - clang-tidy------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_OWNING_MEMORY_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_OWNING_MEMORY_H + +#include "../ClangTidy.h" + +namespace clang { +namespace tidy { +namespace cppcoreguidelines { + +/// Checks for common usecases for gsl::owner and enforces the unique owner +/// nature of it whenever possible. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/cppcoreguidelines-owning-memory.html +class OwningMemoryCheck : public ClangTidyCheck { +public: + OwningMemoryCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerMatchers(ast_matchers::MatchFinder *Finder) override; + void check(const ast_matchers::MatchFinder::MatchResult &Result) override; + +private: + bool handleDeletion(const ast_matchers::BoundNodes &Nodes); + bool handleExpectedOwner(const ast_matchers::BoundNodes &Nodes); + bool handleAssignmentAndInit(const ast_matchers::BoundNodes &Nodes); + bool handleBadAssignmentAndInit(const ast_matchers::BoundNodes &Nodes); + bool handleReturnValues(const ast_matchers::BoundNodes &Nodes); + bool handleOwnerMembers(const ast_matchers::BoundNodes &Nodes); + +}; + +} // namespace cppcoreguidelines +} // namespace tidy +} // namespace clang + +#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_CPPCOREGUIDELINES_OWNING_MEMORY_H Index: clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp =================================================================== --- /dev/null +++ clang-tidy/cppcoreguidelines/OwningMemoryCheck.cpp @@ -0,0 +1,299 @@ +//===--- OwningMemoryCheck.cpp - clang-tidy--------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "OwningMemoryCheck.h" +#include "../utils/Matchers.h" +#include "../utils/OptionsUtils.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include +#include +#include + +using namespace clang::ast_matchers; +using namespace clang::ast_matchers::internal; + +namespace clang { +namespace tidy { +namespace cppcoreguidelines { + +/// Match common cases, where the owner semantic is relevant, like function +/// calls, delete expressions and others. +void OwningMemoryCheck::registerMatchers(MatchFinder *Finder) { + if (!getLangOpts().CPlusPlus11) + return; + + const auto OwnerDecl = typeAliasTemplateDecl(hasName("::gsl::owner")); + const auto IsOwnerType = hasType(OwnerDecl); + const auto CreatesOwner = + anyOf(cxxNewExpr(), callExpr(callee(functionDecl( + returns(qualType(hasDeclaration(OwnerDecl))))))); + const auto ConsideredOwner = anyOf(IsOwnerType, CreatesOwner); + + // Find delete expressions that delete non-owners. + Finder->addMatcher( + cxxDeleteExpr( + hasDescendant( + declRefExpr(unless(ConsideredOwner)).bind("deleted_variable"))) + .bind("delete_expr"), + this); + + // Matching assignment to owners, with the rhs not being an owner nor creating + // one. + Finder->addMatcher(binaryOperator(allOf(matchers::isAssignmentOperator(), + hasLHS(IsOwnerType), + hasRHS(unless(ConsideredOwner)))) + .bind("owner_assignment"), + this); + + // Matching initialization of owners with non-owners, nor creating owners. + Finder->addMatcher( + namedDecl( + varDecl(allOf(hasInitializer(unless(ConsideredOwner)), IsOwnerType)) + .bind("owner_initialization")), + this); + + // Match class member initialization that expects owners, but does not get + // them. + Finder->addMatcher( + cxxRecordDecl(has(cxxConstructorDecl(forEachConstructorInitializer( + cxxCtorInitializer( + allOf( + isMemberInitializer(), forField(IsOwnerType), + withInitializer( + // Avoid templatesdeclaration with avoiding parenListExpr. + allOf(unless(ConsideredOwner), unless(parenListExpr()))))) + .bind("owner_member_initializer"))))), + this); + + // Matching on assignment operations where the RHS is a newly created owner, + // but the LHS is not an owner. + Finder->addMatcher( + binaryOperator(allOf(matchers::isAssignmentOperator(), + hasLHS(unless(IsOwnerType)), hasRHS(CreatesOwner))) + .bind("bad_owner_creation_assignment"), + this); + + // Matching on initialization operations where the initial value is a newly + // created owner, but the LHS is not an owner. + Finder->addMatcher( + namedDecl(varDecl(eachOf(allOf(hasInitializer(CreatesOwner), + unless(IsOwnerType)), + allOf(hasInitializer(ConsideredOwner), + hasType(autoType().bind("deduced_type"))))) + .bind("bad_owner_creation_variable")), + this); + + // Match on all function calls that expect owners as arguments, but didn't + // get them. + Finder->addMatcher( + callExpr(forEachArgumentWithParam( + expr(unless(ConsideredOwner)).bind("expected_owner_argument"), + parmVarDecl(IsOwnerType))), + this); + + // Matching for function calls where one argument is a created owner, but the + // parameter type is not an owner. + Finder->addMatcher(callExpr(forEachArgumentWithParam( + expr(CreatesOwner).bind("bad_owner_creation_argument"), + parmVarDecl(unless(IsOwnerType)))), + this); + + // Matching on functions, that return an owner/resource, but don't declare + // their return type as owner. + Finder->addMatcher( + functionDecl( + allOf(hasDescendant(returnStmt(hasReturnValue(ConsideredOwner)) + .bind("bad_owner_return")), + unless(returns(qualType(hasDeclaration(OwnerDecl)))))), + this); + + // Match on classes that have an owner as member, but don't declare a + // destructor to properly release the owner. + Finder->addMatcher( + cxxRecordDecl( + allOf(has(fieldDecl(IsOwnerType).bind("undestructed_owner_member")), + anyOf(unless(has(cxxDestructorDecl())), + has(cxxDestructorDecl(isDefaulted()))))) + .bind("non_destructor_class"), + this); +} + +void OwningMemoryCheck::check(const MatchFinder::MatchResult &Result) { + const auto &Nodes = Result.Nodes; + + bool CheckExecuted = false; + CheckExecuted |= handleDeletion(Nodes); + CheckExecuted |= handleExpectedOwner(Nodes); + CheckExecuted |= handleAssignmentAndInit(Nodes); + CheckExecuted |= handleBadAssignmentAndInit(Nodes); + CheckExecuted |= handleReturnValues(Nodes); + CheckExecuted |= handleOwnerMembers(Nodes); + + assert(CheckExecuted == true && + "Non of the subroutines did execute, logic error in matcher!"); +} + +bool OwningMemoryCheck::handleDeletion(const BoundNodes &Nodes) { + // Result of delete matchers. + const auto *DeleteStmt = Nodes.getNodeAs("delete_expr"); + const auto *DeletedVariable = + Nodes.getNodeAs("deleted_variable"); + + // Deletion of non-owners, with `delete variable;` + if (DeletedVariable != nullptr) { + assert(DeleteStmt != nullptr && + "Both the delete expression and the variable must be not null"); + diag(DeleteStmt->getLocStart(), + "deleting unowned memory; use RAII or gsl::owner") + << SourceRange(DeletedVariable->getLocStart(), + DeletedVariable->getLocEnd()); + return true; + } else + return false; +} + +bool OwningMemoryCheck::handleExpectedOwner(const BoundNodes &Nodes) { + // Result of function call matchers. + const auto *ExpectedOwner = Nodes.getNodeAs("expected_owner_argument"); + + // Expected function argument to be owner. + if (ExpectedOwner != nullptr) { + diag(ExpectedOwner->getLocStart(), + "expected this argument to be an owner or a recognized resource") + << SourceRange(ExpectedOwner->getLocStart(), + ExpectedOwner->getLocEnd()); + return true; + } else + return false; +} + +bool OwningMemoryCheck::handleAssignmentAndInit(const BoundNodes &Nodes) { + // Assignment and initialization of owner variables. + const auto *OwnerAssignment = + Nodes.getNodeAs("owner_assignment"); + const auto *OwnerInitialization = + Nodes.getNodeAs("owner_initialization"); + const auto *OwnerInitializer = + Nodes.getNodeAs("owner_member_initializer"); + + // Assignments to owners. + if (OwnerAssignment != nullptr) { + diag(OwnerAssignment->getLocStart(), + "assigning neither an owner nor a recognized resource") + << SourceRange(OwnerAssignment->getLocStart(), + OwnerAssignment->getLocEnd()); + return true; + } + // Initialization of owners. + else if (OwnerInitialization != nullptr) { + diag(OwnerInitialization->getLocStart(), + "initializing neither with an owner nor a recognized resource") + << SourceRange(OwnerInitialization->getLocStart(), + OwnerInitialization->getLocEnd()); + return true; + } + // Initializer of class constructors, that initialize owners. + else if (OwnerInitializer != nullptr) { + diag(OwnerInitializer->getSourceLocation(), + "initializing owner member variable neither with an " + "owner nor a recognized resource") + << OwnerInitializer->getSourceRange(); + return true; + } else + return false; +} + +bool OwningMemoryCheck::handleBadAssignmentAndInit(const BoundNodes &Nodes) { + // Problematic assignment and initializations, since the assigned value is a + // newly created owner. + const auto *BadOwnerAssignment = + Nodes.getNodeAs("bad_owner_creation_assignment"); + const auto *BadOwnerInitialization = + Nodes.getNodeAs("bad_owner_creation_variable"); + const auto *BadOwnerArgument = + Nodes.getNodeAs("bad_owner_creation_argument"); + + // Bad assignments to non-owners, where the RHS is a newly created owner. + if (BadOwnerAssignment != nullptr) { + diag(BadOwnerAssignment->getLocStart(), + "assigning newly created owner/resource to non-owner") + << SourceRange(BadOwnerAssignment->getLocStart(), + BadOwnerAssignment->getLocEnd()); + return true; + } + // Bad initialization of non-owners, where the RHS is a newly create owner. + else if (BadOwnerInitialization != nullptr) { + diag(BadOwnerInitialization->getLocStart(), + "initializing non owner with a newly created owner/resource") + << SourceRange(BadOwnerInitialization->getLocStart(), + BadOwnerInitialization->getLocEnd()); + // FIXME FixitHint to rewrite the type if possible + + // If the type of the variable was deduced, the wrapping owner typedef is + // eliminated, therefore the check emits a special note for that case. + if (Nodes.getNodeAs("deduced_type") != nullptr) { + diag(BadOwnerInitialization->getLocStart(), + "type deduction did not result in an owner", DiagnosticIDs::Note); + } + return true; + } + // Function call, where one arguments is a newly created owner + else if (BadOwnerArgument != nullptr) { + diag(BadOwnerArgument->getLocStart(), + "initializing non owner argument with a newly created owner/resource") + << SourceRange(BadOwnerArgument->getLocStart(), + BadOwnerArgument->getLocEnd()); + return true; + } else + return false; +} + +bool OwningMemoryCheck::handleReturnValues(const BoundNodes &Nodes) { + // Function return statements, that are owners/resources, but the function + // declaration does not declare its return value as owner. + const auto *BadReturnType = Nodes.getNodeAs("bad_owner_return"); + + // Function return values, that should be owners but aren't. + if (BadReturnType != nullptr) { + diag(BadReturnType->getLocStart(), + "returning an owner/resource from a function but not " + "declaring it as one") + << SourceRange(BadReturnType->getLocStart(), + BadReturnType->getLocEnd()); + return true; + } else + return false; +} + +bool OwningMemoryCheck::handleOwnerMembers(const BoundNodes &Nodes) { + // Classes, that have owners as member, but do not declare destructors + // accordingly. + const auto *BadClass = Nodes.getNodeAs("non_destructor_class"); + + // Classes, that contains owners, but do not declare destructors + if (BadClass != nullptr) { + const auto *DeclaredOwnerMember = + Nodes.getNodeAs("undestructed_owner_member"); + assert(DeclaredOwnerMember != nullptr && + "Match on class with bad destructor, but without an declared owner"); + + diag(BadClass->getLocStart(), + "class with an owner as member but without declared " + "destructor to release the owner"); + diag(DeclaredOwnerMember->getLocStart(), "declared owner as member here", + DiagnosticIDs::Note); + return true; + } else + return false; +} + +} // namespace cppcoreguidelines +} // namespace tidy +} // namespace clang Index: clang-tidy/utils/Matchers.h =================================================================== --- clang-tidy/utils/Matchers.h +++ clang-tidy/utils/Matchers.h @@ -17,6 +17,10 @@ namespace tidy { namespace matchers { +AST_MATCHER(BinaryOperator, isAssignmentOperator) { + return Node.isAssignmentOp(); +} + AST_MATCHER(BinaryOperator, isRelationalOperator) { return Node.isRelationalOp(); } Index: docs/ReleaseNotes.rst =================================================================== --- docs/ReleaseNotes.rst +++ docs/ReleaseNotes.rst @@ -77,6 +77,13 @@ Finds member expressions that access static members through instances and replaces them with uses of the appropriate qualified-id. + +- New `cppcoreguidelines-owning-memory `_ check + + This check implements the type-based semantic of ``gsl::owner``, but without + flow analysis. + + Improvements to include-fixer ----------------------------- Index: docs/clang-tidy/checks/cppcoreguidelines-c-copy-assignment-signature.rst =================================================================== --- docs/clang-tidy/checks/cppcoreguidelines-c-copy-assignment-signature.rst +++ docs/clang-tidy/checks/cppcoreguidelines-c-copy-assignment-signature.rst @@ -6,4 +6,5 @@ ============================================= The cppcoreguidelines-c-copy-assignment-signature check is an alias, please see -`misc-unconventional-assign-operator`_ for more information. +`misc-unconventional-assign-operator `_ +for more information. Index: docs/clang-tidy/checks/cppcoreguidelines-owning-memory.rst =================================================================== --- /dev/null +++ docs/clang-tidy/checks/cppcoreguidelines-owning-memory.rst @@ -0,0 +1,136 @@ +.. title:: clang-tidy - cppcoreguidelines-owning-memory + +cppcoreguidelines-owning-memory +=============================== + +This check implements the type-based semantics of ``gsl::owner``, which allows +static analysis on code, that uses raw pointers to handle resources like +dynamic memory, but won't introduce RAII concepts. + +The relevant sections in the `C++ Core Guidelines `_ are I.11, C.33, R.3 and GSL.Views +The definition of an ``gsl::owner`` is straight forward + +.. code-block:: c++ + + namespace gsl { template owner = T; } + +it is therefore simple to introduce the owner even without using an implementation of +the `Guideline Support Library `_. + +All checks are purely type based and not (yet) flow sensitive. + +The following examples will demonstrate the correct and incorrect initializations +of owners, assignment is handled the same way. + +.. code-block:: c++ + + // Creating an owner with factory functions is caught. + gsl::owner function_that_returns_owner() { return gsl::owner(new int(42)); } + + // Dynamic memory must be assigned to an owner + int* Something = new int(42); // BAD, will be caught + gsl::owner Owner = new int(42); // Good + gsl::owner Owner = new int[42]; // Good as well + + // Returned owner must be assigned to an owner + int* Something = function_that_returns_owner(); // Bad, factory function + gsl::owner Owner = function_that_returns_owner(); // Good, result lands in owner + + // Something not a resource or owner should not be assigned to owners + int Stack = 42; + gsl::owner Owned = &Stack; // Bad, not an resource assigned + +In the case of dynamic memory as resource, only ``gsl::owner`` variables are allowed +to be deleted. + +.. code-block:: c++ + + // Example Bad, non-owner as resource handle, will be caught. + int* NonOwner = new int(42); // First warning here, since new must land in an owner + delete NonOwner; // Second warning here, since only owners are allowed to be deleted + + // Example Good, Ownership correclty stated + gsl::owner Owner = new int(42); // Good + delete Owner; // Good as well, statically enforced, that only owners get deleted + +The check will furthermore ensure, that functions, that expect an ``gsl::owner`` as +argument get called with either an ``gsl::owner`` or a newly created resource. + +.. code-block:: c++ + + void expects_owner(gsl::owner o) { delete o; } + + // Bad Code + int NonOwner = 42; + expects_owner(&NonOwner); // Bad, will get caught + + // Good Code + gsl::owner Owner = new int(42); + expects_owner(Owner); // Good + expects_owner(new int(42)); // Good as well, recognized created resource + +Limitations +----------- + +The ``gsl::owner`` is declared as a templated type alias. +In template functions and classes, like in the example below, the information +of the type aliases gets lost. Therefore using ``gsl::owner`` in a heavy templated +code base might lead to false positives. + +.. code-block:: c++ + + // This template function works as expected. Type information doesn't get lost. + template + void delete_owner(gsl::owner owned_object) { + delete owned_object; // Everything alright + } + + gsl::owner function_that_returns_owner() { return gsl::owner(new int(42)); } + + // Type deduction does not work for auto variables. + // This is caught by the check and will be noted accordingly. + auto OwnedObject = function_that_returns_owner(); // Type of OwnedObject will be int* + + // Problematic function template that looses the typeinformation on owner + template + void bad_template_function(T some_object) { + // This line will trigger the warning, that an non-owner is assigned to an owner + gsl::owner new_owner = some_object; + } + + // Calling the function with an owner still yields a false positive. + bad_template_function(gsl::owner(new int(42))); + + + // The same issue occurs with templated classes like the following. + template + class OwnedValue { + public: + const T getValue() const { return _val; } + private: + T _val; + }; + + // Code, that yields a false positive. + OwnedValue> Owner(new int(42)); // Type deduction yield T -> int * + // False positive, getValue returns int* and not gsl::owner + gsl::owner OwnedInt = Owner.getValue(); + +Another limitation of the current implementation is only the type based checking. +Suppose you have code like the following: + +.. code-block:: c++ + + // Two owners with assigned resources + gsl::owner Owner1 = new int(42); + gsl::owner Owner2 = new int(42); + + Owner2 = Owner1; // Conceptual Leak of initial resource of Owner2! + Owner1 = nullptr; + +The semantic of an ``gsl::owner`` is mostly like a ``std::unique_ptr``, therefore +assignment of two ``gsl::owner`` is considered a move, but therefore the resource +``Owner2`` must have been released before the assignment. +This kind of condition could be catched in later improvements of this check with +flowsensitive analysis. Currently, the `Clang Static Analyzer` catches this bug +for dynamic memory, but not for general types of resources. Index: docs/clang-tidy/checks/hicpp-explicit-conversions.rst =================================================================== --- docs/clang-tidy/checks/hicpp-explicit-conversions.rst +++ docs/clang-tidy/checks/hicpp-explicit-conversions.rst @@ -1,9 +1,11 @@ .. title:: clang-tidy - hicpp-explicit-conversions +.. meta:: + :http-equiv=refresh: 5;URL=google-explicit-constructor.html hicpp-explicit-conversions ========================== -This check is an alias for `google-explicit-constructor `_. +This check is an alias for `google-explicit-constructor `_. Used to enforce parts of `rule 5.4.1 `_. This check will enforce that constructors and conversion operators are marked `explicit`. Other forms of casting checks are implemented in other places. Index: docs/clang-tidy/checks/hicpp-function-size.rst =================================================================== --- docs/clang-tidy/checks/hicpp-function-size.rst +++ docs/clang-tidy/checks/hicpp-function-size.rst @@ -1,9 +1,11 @@ .. title:: clang-tidy - hicpp-function-size +.. meta:: + :http-equiv=refresh: 5;URL=readability-function-size.html hicpp-function-size =================== -This check is an alias for `readability-function-size `_. +This check is an alias for `readability-function-size `_. Useful to enforce multiple sections on function complexity. - `rule 8.2.2 `_ Index: docs/clang-tidy/checks/hicpp-invalid-access-moved.rst =================================================================== --- docs/clang-tidy/checks/hicpp-invalid-access-moved.rst +++ docs/clang-tidy/checks/hicpp-invalid-access-moved.rst @@ -1,8 +1,10 @@ .. title:: clang-tidy - hicpp-invalid-access-moved +.. meta:: + :http-equiv=refresh: 5;URL=misc-use-after-move.html hicpp-invalid-access-moved ========================== -This check is an alias for `misc-use-after-move `_. +This check is an alias for `misc-use-after-move `_. Implements parts of the `rule 8.4.1 `_ to check if moved-from objects are accessed. Index: docs/clang-tidy/checks/hicpp-member-init.rst =================================================================== --- docs/clang-tidy/checks/hicpp-member-init.rst +++ docs/clang-tidy/checks/hicpp-member-init.rst @@ -1,9 +1,11 @@ .. title:: clang-tidy - hicpp-member-init +.. meta:: + :http-equiv=refresh: 5;URL=cppcoreguidelines-pro-type-member-init.html hicpp-member-init ================= -This check is an alias for `cppcoreguidelines-pro-type-member-init `_. +This check is an alias for `cppcoreguidelines-pro-type-member-init `_. Implements the check for `rule 12.4.2 `_ to initialize class members in the right order. Index: docs/clang-tidy/checks/hicpp-named-parameter.rst =================================================================== --- docs/clang-tidy/checks/hicpp-named-parameter.rst +++ docs/clang-tidy/checks/hicpp-named-parameter.rst @@ -1,8 +1,10 @@ .. title:: clang-tidy - hicpp-named-parameter +.. meta:: + :http-equiv=refresh: 5;URL=readability-named-parameter.html hicpp-named-parameter ===================== -This check is an alias for `readability-named-parameter `_. +This check is an alias for `readability-named-parameter `_. Implements `rule 8.2.1 `_. Index: docs/clang-tidy/checks/hicpp-new-delete-operators.rst =================================================================== --- docs/clang-tidy/checks/hicpp-new-delete-operators.rst +++ docs/clang-tidy/checks/hicpp-new-delete-operators.rst @@ -1,8 +1,10 @@ .. title:: clang-tidy - hicpp-new-delete-operators +.. meta:: + :http-equiv=refresh: 5;URL=misc-new-delete-overloads.html hicpp-new-delete-operators ========================== -This check is an alias for `misc-new-delete-overloads `_. +This check is an alias for `misc-new-delete-overloads `_. Implements `rule 12.3.1 `_ to ensure the `new` and `delete` operators have the correct signature. Index: docs/clang-tidy/checks/hicpp-noexcept-move.rst =================================================================== --- docs/clang-tidy/checks/hicpp-noexcept-move.rst +++ docs/clang-tidy/checks/hicpp-noexcept-move.rst @@ -1,7 +1,9 @@ .. title:: clang-tidy - hicpp-noexcept-move +.. meta:: + :http-equiv=refresh: 5;URL=misc-noexcept-moveconstructor.html hicpp-noexcept-move =================== -This check is an alias for `misc-noexcept-moveconstructor `_. +This check is an alias for `misc-noexcept-moveconstructor `_. Checks `rule 12.5.4 `_ to mark move assignment and move construction `noexcept`. Index: docs/clang-tidy/checks/hicpp-special-member-functions.rst =================================================================== --- docs/clang-tidy/checks/hicpp-special-member-functions.rst +++ docs/clang-tidy/checks/hicpp-special-member-functions.rst @@ -1,7 +1,9 @@ .. title:: clang-tidy - hicpp-special-member-functions +.. meta:: + :http-equiv=refresh: 5;URL=cppcoreguidelines-special-member-functions.html hicpp-special-member-functions ============================== -This check is an alias for `cppcoreguidelines-special-member-functions `_. +This check is an alias for `cppcoreguidelines-special-member-functions `_. Checks that special member functions have the correct signature, according to `rule 12.5.7 `_. Index: docs/clang-tidy/checks/hicpp-undelegated-constructor.rst =================================================================== --- docs/clang-tidy/checks/hicpp-undelegated-constructor.rst +++ docs/clang-tidy/checks/hicpp-undelegated-constructor.rst @@ -1,9 +1,11 @@ .. title:: clang-tidy - hicpp-undelegated-construtor +.. meta:: + :http-equiv=refresh: 5;URL=misc-undelegated-constructor.html hicpp-undelegated-constructor ============================= -This check is an alias for `misc-undelegated-constructor `_. +This check is an alias for `misc-undelegated-constructor `_. Partially implements `rule 12.4.5 `_ to find misplaced constructor calls inside a constructor. Index: docs/clang-tidy/checks/hicpp-use-equals-default.rst =================================================================== --- docs/clang-tidy/checks/hicpp-use-equals-default.rst +++ docs/clang-tidy/checks/hicpp-use-equals-default.rst @@ -1,7 +1,9 @@ .. title:: clang-tidy - hicpp-use-equals-defaults +.. meta:: + :http-equiv=refresh: 5;URL=modernize-use-equals-default.html hicpp-use-equals-default ======================== -This check is an alias for `modernize-use-equals-default `_. +This check is an alias for `modernize-use-equals-default `_. Implements `rule 12.5.1 `_ to explicitly default special member functions. Index: docs/clang-tidy/checks/hicpp-use-equals-delete.rst =================================================================== --- docs/clang-tidy/checks/hicpp-use-equals-delete.rst +++ docs/clang-tidy/checks/hicpp-use-equals-delete.rst @@ -1,8 +1,10 @@ .. title:: clang-tidy - hicpp-use-equals-delete +.. meta:: + :http-equiv=refresh: 5;URL=modernize-use-equals-delete.html hicpp-use-equals-delete ======================= -This check is an alias for `modernize-use-equals-delete `_. +This check is an alias for `modernize-use-equals-delete `_. Implements `rule 12.5.1 `_ to explicitly default or delete special member functions. Index: docs/clang-tidy/checks/hicpp-use-override.rst =================================================================== --- docs/clang-tidy/checks/hicpp-use-override.rst +++ docs/clang-tidy/checks/hicpp-use-override.rst @@ -1,8 +1,10 @@ .. title:: clang-tidy - hicpp-use-override +.. meta:: + :http-equiv=refresh: 5;URL=modernize-use-override.html hicpp-use-override ================== -This check is an alias for `modernize-use-override `_. +This check is an alias for `modernize-use-override `_. Implements `rule 10.2.1 `_ to declare a virtual function `override` when overriding. Index: docs/clang-tidy/checks/list.rst =================================================================== --- docs/clang-tidy/checks/list.rst +++ docs/clang-tidy/checks/list.rst @@ -32,6 +32,7 @@ cppcoreguidelines-c-copy-assignment-signature cppcoreguidelines-interfaces-global-init cppcoreguidelines-no-malloc + cppcoreguidelines-owning-memory cppcoreguidelines-pro-bounds-array-to-pointer-decay cppcoreguidelines-pro-bounds-constant-array-index cppcoreguidelines-pro-bounds-pointer-arithmetic @@ -60,19 +61,19 @@ google-runtime-member-string-references google-runtime-operator google-runtime-references - hicpp-explicit-conversions - hicpp-function-size - hicpp-invalid-access-moved - hicpp-member-init - hicpp-named-parameter - hicpp-new-delete-operators + hicpp-explicit-conversions (redirects to google-explicit-constructor) + hicpp-function-size (redirects to readability-function-size) + hicpp-invalid-access-moved (redirects to misc-use-after-move) + hicpp-member-init (redirects to cppcoreguidelines-pro-type-member-init) + hicpp-named-parameter (redirects to readability-named-parameter) + hicpp-new-delete-operators (redirects to misc-new-delete-overloads) hicpp-no-assembler - hicpp-noexcept-move - hicpp-special-member-functions - hicpp-undelegated-constructor - hicpp-use-equals-default - hicpp-use-equals-delete - hicpp-use-override + hicpp-noexcept-move (redirects to misc-noexcept-moveconstructor) + hicpp-special-member-functions (redirects to cppcoreguidelines-special-member-functions) + hicpp-undelegated-constructor (redirects to misc-undelegated-constructor) + hicpp-use-equals-default (redirects to modernize-use-equals-default) + hicpp-use-equals-delete (redirects to modernize-use-equals-delete) + hicpp-use-override (redirects to modernize-use-override) llvm-header-guard llvm-include-order llvm-namespace-comment Index: test/clang-tidy/cppcoreguidelines-owning-memory.cpp =================================================================== --- /dev/null +++ test/clang-tidy/cppcoreguidelines-owning-memory.cpp @@ -0,0 +1,347 @@ +// RUN: %check_clang_tidy %s cppcoreguidelines-owning-memory %t + +namespace gsl { +template +using owner = T; +} // namespace gsl + +template +class unique_ptr { +public: + unique_ptr(gsl::owner resource) : memory(resource) {} + unique_ptr(const unique_ptr &) = default; + + ~unique_ptr() { delete memory; } + +private: + gsl::owner memory; +}; + +void takes_owner(gsl::owner owned_int) { +} + +void takes_pointer(int *unowned_int) { +} + +void takes_owner_and_more(int some_int, gsl::owner owned_int, float f) { +} + +template +void takes_templated_owner(gsl::owner owned_T) { +} + +gsl::owner returns_owner1() { return gsl::owner(new int(42)); } // Ok +gsl::owner returns_owner2() { return new int(42); } // Ok + +int *returns_no_owner1() { return nullptr; } +int *returns_no_owner2() { + return new int(42); + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning an owner/resource from a function but not declaring it as one +} +int *returns_no_owner3() { + int *should_be_owner = new int(42); + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + return should_be_owner; +} +int *returns_no_owner4() { + gsl::owner owner = new int(42); + return owner; + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: returning an owner/resource from a function but not declaring it as one +} + +unique_ptr returns_no_owner5() { + return unique_ptr(new int(42)); // Ok +} + +/// FIXME CSA finds it, but the report is misleading. +void csa_not_finding_leak() { + gsl::owner o1 = new int(42); // Ok + + gsl::owner o2 = o1; // Ok + o2 = new int(45); // conceptual leak, the memory from o1 is now leaked, since its considered moved in the guideLINEs + + delete o2; + // actual leak occurs here, its found, but mixed + delete o1; +} + +void test_assignment_and_initialization() { + int stack_int1 = 15; + int stack_int2; + + gsl::owner owned_int1 = &stack_int1; // BAD + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource + + gsl::owner owned_int2; + owned_int2 = &stack_int2; // BAD since no owner, bad since uninitialized + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning neither an owner nor a recognized resource + + gsl::owner owned_int3 = new int(42); // Good + owned_int3 = nullptr; // Good + + gsl::owner owned_int4(nullptr); // Ok + owned_int4 = new int(42); // Good + + gsl::owner owned_int5 = owned_int3; // Good + + gsl::owner owned_int6{nullptr}; // Ok + owned_int6 = owned_int4; // Good + + // FIXME, flow analysis for the case of reassignment. Value must be released before + owned_int6 = owned_int3; // BAD, because reassignment without resource release + + auto owned_int7 = returns_owner1(); // Bad, since typededuction eliminates the owner wrapper + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner + + const auto owned_int8 = returns_owner2(); // Bad, since typededuction eliminates the owner wrapper + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner + + gsl::owner owned_int9 = returns_owner1(); // Ok + int *unowned_int3 = returns_owner1(); // Bad + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + + gsl::owner owned_int10; + owned_int10 = returns_owner1(); // Ok + + int *unowned_int4; + unowned_int4 = returns_owner1(); // Bad + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning newly created owner/resource to non-owner + + gsl::owner owned_int11 = returns_no_owner1(); // Bad since no owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource + + gsl::owner owned_int12; + owned_int12 = returns_no_owner1(); // Bad since no owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning neither an owner nor a recognized resource + + int *unowned_int5 = returns_no_owner1(); // Ok + int *unowned_int6; + unowned_int6 = returns_no_owner1(); // Ok + + int *unowned_int7 = new int(42); // Bad, since resource not assigned to an owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + + int *unowned_int8; + unowned_int8 = new int(42); + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning newly created owner/resource to non-owner + + gsl::owner owned_int13 = nullptr; // Ok +} + +void test_deletion() { + gsl::owner owned_int1 = new int(42); + delete owned_int1; // Good + + gsl::owner owned_int2 = new int[42]; + delete[] owned_int2; // Good + + int *unowned_int1 = new int(42); // BAD, since new creates and owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + delete unowned_int1; // BAD, since no owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: deleting unowned memory; use RAII or gsl::owner + + int *unowned_int2 = new int[42]; // BAD, since new creates and owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + delete[] unowned_int2; // BAD since no owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: deleting unowned memory; use RAII or gsl::owner + + delete new int(42); // Technically ok, but stupid + delete[] new int[42]; // Technically ok, but stupid +} + +void test_owner_function_calls() { + int stack_int = 42; + int *unowned_int1 = &stack_int; + takes_owner(&stack_int); // BAD + // CHECK-MESSAGES: [[@LINE-1]]:15: warning: expected this argument to be an owner or a recognized resource + takes_owner(unowned_int1); // BAD + // CHECK-MESSAGES: [[@LINE-1]]:15: warning: expected this argument to be an owner or a recognized resource + + gsl::owner owned_int1 = new int(42); + takes_owner(owned_int1); // Ok + + takes_owner_and_more(42, &stack_int, 42.0f); // BAD + // CHECK-MESSAGES: [[@LINE-1]]:28: warning: expected this argument to be an owner or a recognized resource + takes_owner_and_more(42, unowned_int1, 42.0f); // BAD + // CHECK-MESSAGES: [[@LINE-1]]:28: warning: expected this argument to be an owner or a recognized resource + + takes_owner_and_more(42, new int(42), 42.0f); // Ok, since new is consumed by owner + takes_owner_and_more(42, owned_int1, 42.0f); // Ok, since owner as argument + + takes_templated_owner(owned_int1); // Ok + takes_templated_owner(new int(42)); // Ok + takes_templated_owner(unowned_int1); // Bad + // CHECK-MESSAGES: [[@LINE-1]]:25: warning: expected this argument to be an owner or a recognized resource + + takes_owner(returns_owner1()); // Ok + takes_owner(returns_no_owner1()); // BAD + // CHECK-MESSAGES: [[@LINE-1]]:15: warning: expected this argument to be an owner or a recognized resource +} + +void test_unowned_function_calls() { + int stack_int = 42; + int *unowned_int1 = &stack_int; + gsl::owner owned_int1 = new int(42); + + takes_pointer(&stack_int); // Ok + takes_pointer(unowned_int1); // Ok + takes_pointer(owned_int1); // Ok + takes_pointer(new int(42)); // Bad, since new creates and owner + // CHECK-MESSAGES: [[@LINE-1]]:17: warning: initializing non owner argument with a newly created owner/resource + + takes_pointer(returns_owner1()); // Bad + // CHECK-MESSAGES: [[@LINE-1]]:17: warning: initializing non owner argument with a newly created owner/resource + + takes_pointer(returns_no_owner1()); // Ok +} + +struct ArbitrayClass {}; +struct ClassWithOwner { // Does not define destructor, necessary with owner + // CHECK-MESSAGES: [[@LINE-1]]:1: warning: class with an owner as member but without declared destructor to release the owner + // CHECK-MESSAGES: [[@LINE+28]]:3: note: declared owner as member here + ClassWithOwner() : owner_var(nullptr) {} // Ok + + ClassWithOwner(ArbitrayClass &other) : owner_var(&other) {} + // CHECK-MESSAGES: [[@LINE-1]]:42: warning: initializing owner member variable neither with an owner nor a recognized resource + + ClassWithOwner(gsl::owner other) : owner_var(other) {} // Ok + + ClassWithOwner(gsl::owner data, int /* unused */) { // Ok + owner_var = data; // Ok + } + + ClassWithOwner(ArbitrayClass *bad_data, int /* unused */, int /* unused */) { + owner_var = bad_data; + // CHECK-MESSAGES: [[@LINE-1]]:5: warning: assigning neither an owner nor a recognized resource + } + + ClassWithOwner(ClassWithOwner &&other) : owner_var{other.owner_var} {} // Ok + + ClassWithOwner &operator=(ClassWithOwner &&other) { + owner_var = other.owner_var; // Ok + return *this; + } + + // Returning means, that the owner is "moved", so the class should not access this + // variable anymore after this method gets called. + gsl::owner buggy_but_returns_owner() { return owner_var; } + + gsl::owner owner_var; +}; + +void test_class_with_owner() { + ArbitrayClass A; + ClassWithOwner C1; // Ok + ClassWithOwner C2{A}; // Bad, since the owner would be initialized with an nonowner, but catched in the class + ClassWithOwner C3{gsl::owner(new ArbitrayClass)}; // Ok + + const auto Owner1 = C3.buggy_but_returns_owner(); // BAD, deduces Owner1 to ArbitrayClass *const + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner + + auto Owner2 = C2.buggy_but_returns_owner(); // BAD, deduces Owner2 to ArbitrayClass * + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing non owner with a newly created owner/resource + // CHECK-MESSAGES: [[@LINE-2]]:3: note: type deduction did not result in an owner + + Owner2 = &A; // Ok, since type deduction did NOT result in owner + + gsl::owner Owner3 = C1.buggy_but_returns_owner(); // Ok, still an owner + Owner3 = &A; // Bad, since assignment of nonowner to owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: assigning neither an owner nor a recognized resource +} + +template +struct HeapArray { // Ok, since destructor with owner + HeapArray() : _data(nullptr), size(0) {} // Ok + HeapArray(int size) : _data(new int[size]), size(size) {} // Ok + HeapArray(int size, T val) { + _data = new int[size]; // Ok + size = size; + for (auto i = 0u; i < size; ++i) + _data[i] = val; // Ok + } + HeapArray(int size, T val, int *problematic) : _data{problematic}, size(size) {} // Bad + // CHECK-MESSAGES: [[@LINE-1]]:50: warning: initializing owner member variable neither with an owner nor a recognized resource + + HeapArray(HeapArray &&other) : _data(other._data), size(other.size) { // Ok + other._data = nullptr; // Ok + other.size = 0; + } + + HeapArray &operator=(HeapArray &&other) { + _data = other._data; // Ok, NOLINT warning here about bad types, why? + size = other.size; + return *this; + } + + ~HeapArray() { delete[] _data; } // Ok + + T *data() { return _data; } // Ok NOLINT, because it "looks" like a factory + + gsl::owner _data; + unsigned int size; +}; + +void test_inner_template() { + HeapArray Array1; + HeapArray Array2(100); + HeapArray Array3(100, 0); + + Array1 = static_cast &&>(Array2); + HeapArray Array4(static_cast &&>(Array3)); + + int *NonOwningPtr = Array1.data(); // Ok + gsl::owner OwningPtr = Array1.data(); // Bad, since it does not return the owner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource +} + +class DefaultedDestructor { // Bad since default constructor with owner + // CHECK-MESSAGES: [[@LINE-1]]:1: warning: class with an owner as member but without declared destructor to release the owner + // CHECK-MESSAGES: [[@LINE+2]]:3: note: declared owner as member here + ~DefaultedDestructor() = default; // Bad, since will not destroy the owner + gsl::owner Owner; +}; + +// FIXME Typededuction removes the owner - wrapper, therefore gsl::owner can not be used +// with Template classes like this. Is there a walkaround? +template +struct TemplateValue { + TemplateValue() = default; + TemplateValue(T t) : val{t} {} + + void setVal(const T &t) { val = t; } + const T getVal() const { return val; } + + T val; +}; + +// FIXME Same typededcution problems +template +void template_function(T t) { + gsl::owner owner_t = t; // Probably bad, since typededuction still wrong + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource +} + +// FIXME Same typededcution problems +void test_templates() { + int stack_int = 42; + int *stack_ptr1 = &stack_int; + + TemplateValue> Owner0; // Ok, T should be owner, but is int* + + TemplateValue> Owner1(new int(42)); // Ok, T should be owner, but is int* + Owner1.setVal(&stack_int); // Bad since non owner assignment + Owner1.setVal(stack_ptr1); // Bad since non owner assignment + //Owner1.setVal(new int(42)); // Ok, but since typededuction is wrong, this one is considered harmfull + + int *stack_ptr2 = Owner1.getVal(); // Bad, initializing nonowner with owner + + TemplateValue NonOwner1(new int(42)); // Bad, T is int *, hence dynamic memory to non owner + gsl::owner IntOwner1 = NonOwner1.getVal(); // Bad, since owner initialized with nonowner + // CHECK-MESSAGES: [[@LINE-1]]:3: warning: initializing neither with an owner nor a recognized resource + + template_function(IntOwner1); // Ok, but not actually ok, since typededuction removes owner + template_function(stack_ptr1); // Bad, but typededuction gets it wrong +}