clang-tools 10.0.0

UndefinedMemoryManipulationCheck.cpp
Go to the documentation of this file.
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 {
16 namespace tidy {
17 namespace bugprone {
18
19 namespace {
20 AST_MATCHER(CXXRecordDecl, isNotTriviallyCopyable) {
21 // For incomplete types, assume they are TriviallyCopyable.
22 return Node.hasDefinition() ? !Node.isTriviallyCopyable() : false;
23 }
24 } // namespace
25
26 void UndefinedMemoryManipulationCheck::registerMatchers(MatchFinder *Finder) {
27 const auto NotTriviallyCopyableObject =
28 hasType(ast_matchers::hasCanonicalType(
29 pointsTo(cxxRecordDecl(isNotTriviallyCopyable()))));
30
31 // Check whether destination object is not TriviallyCopyable.
32 // Applicable to all three memory manipulation functions.
33 Finder->addMatcher(callExpr(callee(functionDecl(hasAnyName(
34 "::memset", "::memcpy", "::memmove"))),
35 hasArgument(0, NotTriviallyCopyableObject))
36 .bind("dest"),
37 this);
38
39 // Check whether source object is not TriviallyCopyable.
40 // Only applicable to memcpy() and memmove().
41 Finder->addMatcher(
42 callExpr(callee(functionDecl(hasAnyName("::memcpy", "::memmove"))),
43 hasArgument(1, NotTriviallyCopyableObject))
44 .bind("src"),
45 this);
46 }
47
48 void UndefinedMemoryManipulationCheck::check(
49 const MatchFinder::MatchResult &Result) {
50 if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("dest")) {
51 QualType DestType = Call->getArg(0)->IgnoreImplicit()->getType();
52 if (!DestType->getPointeeType().isNull())
53 DestType = DestType->getPointeeType();
54 diag(Call->getBeginLoc(), "undefined behavior, destination object type %0 "
55 "is not TriviallyCopyable")
56 << DestType;
57 }
58 if (const auto *Call = Result.Nodes.getNodeAs<CallExpr>("src")) {
59 QualType SourceType = Call->getArg(1)->IgnoreImplicit()->getType();
60 if (!SourceType->getPointeeType().isNull())
61 SourceType = SourceType->getPointeeType();
62 diag(Call->getBeginLoc(),
63 "undefined behavior, source object type %0 is not TriviallyCopyable")
64 << SourceType;
65 }
66 }
67
68 } // namespace bugprone
69 } // namespace tidy
70 } // namespace clang
clang::ast_matchers
Definition: AbseilMatcher.h:14
clang::ast_matchers::AST_MATCHER
AST_MATCHER(Expr, isMacroID)
Definition: PreferIsaOrDynCastInConditionalsCheck.cpp:18
UndefinedMemoryManipulationCheck.h
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27