clang-tools 22.0.0git
NoMallocCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 "NoMallocCheck.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14using namespace clang::ast_matchers::internal;
15
17
19 Options.store(Opts, "Allocations", AllocList);
20 Options.store(Opts, "Reallocations", ReallocList);
21 Options.store(Opts, "Deallocations", DeallocList);
22}
23
24void NoMallocCheck::registerMatchers(MatchFinder *Finder) {
25 // Registering malloc, will suggest RAII.
26 Finder->addMatcher(callExpr(callee(functionDecl(hasAnyName(
28 .bind("allocation"),
29 this);
30
31 // Registering realloc calls, suggest std::vector or std::string.
32 Finder->addMatcher(
33 callExpr(callee(functionDecl(
34 hasAnyName(utils::options::parseStringList((ReallocList))))))
35 .bind("realloc"),
36 this);
37
38 // Registering free calls, will suggest RAII instead.
39 Finder->addMatcher(
40 callExpr(callee(functionDecl(
41 hasAnyName(utils::options::parseStringList((DeallocList))))))
42 .bind("free"),
43 this);
44}
45
46void NoMallocCheck::check(const MatchFinder::MatchResult &Result) {
47 const CallExpr *Call = nullptr;
48 StringRef Recommendation;
49
50 if ((Call = Result.Nodes.getNodeAs<CallExpr>("allocation")))
51 Recommendation = "consider a container or a smart pointer";
52 else if ((Call = Result.Nodes.getNodeAs<CallExpr>("realloc")))
53 Recommendation = "consider std::vector or std::string";
54 else if ((Call = Result.Nodes.getNodeAs<CallExpr>("free")))
55 Recommendation = "use RAII";
56
57 assert(Call && "Unhandled binding in the Matcher");
58
59 diag(Call->getBeginLoc(), "do not manage memory manually; %0")
60 << Recommendation << SourceRange(Call->getBeginLoc(), Call->getEndLoc());
61}
62
63} // namespace clang::tidy::cppcoreguidelines
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Registering for malloc, calloc, realloc and free calls.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
Checks matched function calls and gives suggestion to modernize the code.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Make configuration of checker discoverable.
std::vector< StringRef > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
llvm::StringMap< ClangTidyValue > OptionMap