clang-tools 22.0.0git
ProTypeVarargCheck.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
10#include "../utils/Matchers.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Basic/TargetInfo.h"
15#include "clang/Lex/PPCallbacks.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Lex/Token.h"
18
19using namespace clang::ast_matchers;
20
22
23const internal::VariadicDynCastAllOfMatcher<Stmt, VAArgExpr> VAArgExpr;
24
25static constexpr StringRef AllowedVariadics[] = {
26 // clang-format off
27 "__builtin_isgreater",
28 "__builtin_isgreaterequal",
29 "__builtin_isless",
30 "__builtin_islessequal",
31 "__builtin_islessgreater",
32 "__builtin_isunordered",
33 "__builtin_fpclassify",
34 "__builtin_isfinite",
35 "__builtin_isinf",
36 "__builtin_isinf_sign",
37 "__builtin_isnan",
38 "__builtin_isnormal",
39 "__builtin_signbit",
40 "__builtin_constant_p",
41 "__builtin_classify_type",
42 "__builtin_va_start",
43 "__builtin_assume_aligned", // Documented as variadic to support default
44 // parameters.
45 "__builtin_prefetch", // Documented as variadic to support default
46 // parameters.
47 "__builtin_shufflevector", // Documented as variadic but with a defined
48 // number of args based on vector size.
49 "__builtin_convertvector",
50 "__builtin_call_with_static_chain",
51 "__builtin_annotation",
52 "__builtin_add_overflow",
53 "__builtin_sub_overflow",
54 "__builtin_mul_overflow",
55 "__builtin_preserve_access_index",
56 "__builtin_nontemporal_store",
57 "__builtin_nontemporal_load",
58 "__builtin_ms_va_start",
59 // clang-format on
60};
61
62static constexpr StringRef VaArgWarningMessage =
63 "do not use va_arg to define c-style vararg functions; "
64 "use variadic templates instead";
65
66namespace {
67AST_MATCHER(QualType, isVAList) {
68 const ASTContext &Context = Finder->getASTContext();
69 const QualType Desugar = Node.getDesugaredType(Context);
70 const QualType NodeTy = Node.getUnqualifiedType();
71
72 auto CheckVaList = [](QualType NodeTy, QualType Expected,
73 const ASTContext &Context) {
74 if (NodeTy == Expected)
75 return true;
76 QualType Desugar = NodeTy;
77 QualType Ty;
78 do {
79 Ty = Desugar;
80 Desugar = Ty.getSingleStepDesugaredType(Context);
81 if (Desugar == Expected)
82 return true;
83 } while (Desugar != Ty);
84 return false;
85 };
86
87 // The internal implementation of __builtin_va_list depends on the target
88 // type. Some targets implements va_list as 'char *' or 'void *'.
89 // In these cases we need to remove all typedefs one by one to check this.
90 using BuiltinVaListKind = TargetInfo::BuiltinVaListKind;
91 const BuiltinVaListKind VaListKind =
92 Context.getTargetInfo().getBuiltinVaListKind();
93 if (VaListKind == BuiltinVaListKind::CharPtrBuiltinVaList ||
94 VaListKind == BuiltinVaListKind::VoidPtrBuiltinVaList) {
95 if (CheckVaList(NodeTy, Context.getBuiltinVaListType(), Context))
96 return true;
97 } else if (Desugar ==
98 Context.getBuiltinVaListType().getDesugaredType(Context)) {
99 return true;
100 }
101
102 // We also need to check the implementation of __builtin_ms_va_list in the
103 // same way, because it may differ from the va_list implementation.
104 if (Desugar == Context.getBuiltinMSVaListType().getDesugaredType(Context) &&
105 CheckVaList(NodeTy, Context.getBuiltinMSVaListType(), Context)) {
106 return true;
107 }
108
109 return false;
110}
111
112AST_MATCHER_P(AdjustedType, hasOriginalType,
113 ast_matchers::internal::Matcher<QualType>, InnerType) {
114 return InnerType.matches(Node.getOriginalType(), Finder, Builder);
115}
116
117class VaArgPPCallbacks : public PPCallbacks {
118public:
119 VaArgPPCallbacks(ProTypeVarargCheck *Check) : Check(Check) {}
120
121 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
122 SourceRange Range, const MacroArgs *Args) override {
123 if (MacroNameTok.getIdentifierInfo()->getName() == "va_arg") {
124 Check->diag(MacroNameTok.getLocation(), VaArgWarningMessage);
125 }
126 }
127
128private:
129 ProTypeVarargCheck *Check;
130};
131} // namespace
132
133void ProTypeVarargCheck::registerMatchers(MatchFinder *Finder) {
134 Finder->addMatcher(VAArgExpr().bind("va_use"), this);
135
136 Finder->addMatcher(
137 callExpr(callee(functionDecl(isVariadic(),
138 unless(hasAnyName(AllowedVariadics)))),
139 unless(hasAncestor(expr(matchers::hasUnevaluatedContext()))),
140 unless(hasAncestor(typeLoc())))
141 .bind("callvararg"),
142 this);
143
144 Finder->addMatcher(
145 varDecl(unless(parmVarDecl()),
146 hasType(qualType(
147 anyOf(isVAList(), decayedType(hasOriginalType(isVAList()))))))
148 .bind("va_list"),
149 this);
150}
151
152void ProTypeVarargCheck::registerPPCallbacks(const SourceManager &SM,
153 Preprocessor *PP,
154 Preprocessor *ModuleExpanderPP) {
155 PP->addPPCallbacks(std::make_unique<VaArgPPCallbacks>(this));
156}
157
158static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I) {
159 const auto *FDecl = dyn_cast<FunctionDecl>(C->getCalleeDecl());
160 if (!FDecl)
161 return false;
162
163 auto N = FDecl->getNumParams(); // Number of parameters without '...'
164 if (C->getNumArgs() != N + 1)
165 return false; // more/less than one argument passed to '...'
166
167 const auto *IntLit =
168 dyn_cast<IntegerLiteral>(C->getArg(N)->IgnoreParenImpCasts());
169 if (!IntLit)
170 return false;
171
172 if (IntLit->getValue() != I)
173 return false;
174
175 return true;
176}
177
178void ProTypeVarargCheck::check(const MatchFinder::MatchResult &Result) {
179 if (const auto *Matched = Result.Nodes.getNodeAs<CallExpr>("callvararg")) {
181 return;
182 diag(Matched->getExprLoc(), "do not call c-style vararg functions");
183 }
184
185 if (const auto *Matched = Result.Nodes.getNodeAs<Expr>("va_use")) {
186 diag(Matched->getExprLoc(), VaArgWarningMessage);
187 }
188
189 if (const auto *Matched = Result.Nodes.getNodeAs<VarDecl>("va_list")) {
190 auto SR = Matched->getSourceRange();
191 if (SR.isInvalid())
192 return; // some implicitly generated builtins take va_list
193 diag(SR.getBegin(), "do not declare variables of type va_list; "
194 "use variadic templates instead");
195 }
196}
197
198} // namespace clang::tidy::cppcoreguidelines
This check flags all calls to c-style variadic functions and all use of va_arg.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
const internal::VariadicDynCastAllOfMatcher< Stmt, VAArgExpr > VAArgExpr
static constexpr StringRef VaArgWarningMessage
static bool hasSingleVariadicArgumentWithValue(const CallExpr *C, uint64_t I)
static constexpr StringRef AllowedVariadics[]