Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/bugprone/UndefinedMemoryManipulationCheck.cpp

raw
1 //===--- UndefinedMemoryManipulationCheck.cpp - clang-tidy-----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "UndefinedMemoryManipulationCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12
13 using namespace clang::ast_matchers;
14
15 namespace clang::tidy::bugprone {
16
17 namespace {
18 AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
19 // For incomplete types, assume they are TriviallyCopyable.
20 return Node.hasDefinition() ? !Node.isTriviallyCopyable() : false;
21 }
22 } // namespace
23
24 void UndefinedMemoryManipulationCheck::registerMatchers(MatchFinder *Finder) {
25 const auto NotTriviallyCopyableObject =
26 hasType(ast_matchers::hasCanonicalType(
27 pointsTo(cxxRecordDecl(isNotTriviallyCopyable()))));
28
29 // Check whether destination object is not TriviallyCopyable.
30 // Applicable to all three memory manipulation functions.
31 Finder->addMatcher(callExpr(callee(functionDecl(hasAnyName(
32 "::memset", "::memcpy", "::memmove"))),
33 hasArgument(0, NotTriviallyCopyableObject))
34 .bind("dest"),
35 this);
36
37 // Check whether source object is not TriviallyCopyable.
38 // Only applicable to memcpy() and memmove().
39 Finder->addMatcher(
40 callExpr(callee(functionDecl(hasAnyName("::memcpy", "::memmove"))),
41 hasArgument(1, NotTriviallyCopyableObject))
42 .bind("src"),
43 this);
44 }
45
46 void UndefinedMemoryManipulationCheck::check(
47 const MatchFinder::MatchResult &Result) {
48 if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("dest")) {
49 QualType DestType = Call->getArg(0)->IgnoreImplicit()->getType();
50 if (!DestType->getPointeeType().isNull())
51 DestType = DestType->getPointeeType();
52 diag(Call->getBeginLoc(), "undefined behavior, destination object type %0 "
53 "is not TriviallyCopyable")
54 << DestType;
55 }
56 if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("src")) {
57 QualType SourceType = Call->getArg(1)->IgnoreImplicit()->getType();
58 if (!SourceType->getPointeeType().isNull())
59 SourceType = SourceType->getPointeeType();
60 diag(Call->getBeginLoc(),
61 "undefined behavior, source object type %0 is not TriviallyCopyable")
62 << SourceType;
63 }
64 }
65
66 } // namespace clang::tidy::bugprone