clang 24.0.0git
NumberObjectConversionChecker.cpp
Go to the documentation of this file.
1//===- NumberObjectConversionChecker.cpp -------------------------*- C++ -*-==//
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// This file defines NumberObjectConversionChecker, which checks for a
10// particular common mistake when dealing with numbers represented as objects
11// passed around by pointers. Namely, the language allows to reinterpret the
12// pointer as a number directly, often without throwing any warnings,
13// but in most cases the result of such conversion is clearly unexpected,
14// as pointer value, rather than number value represented by the pointee object,
15// becomes the result of such operation.
16//
17// Currently the checker supports the Objective-C NSNumber class,
18// and the OSBoolean class found in macOS low-level code; the latter
19// can only hold boolean values.
20//
21// This checker has an option "Pedantic" (boolean), which enables detection of
22// more conversion patterns (which are most likely more harmless, and therefore
23// are more likely to produce false positives) - disabled by default,
24// enabled with `-analyzer-config osx.NumberObjectConversion:Pedantic=true'.
25//
26//===----------------------------------------------------------------------===//
27
34#include "clang/Lex/Lexer.h"
35#include "llvm/ADT/APSInt.h"
36
37using namespace clang;
38using namespace ento;
39using namespace ast_matchers;
40
41namespace {
42
43class NumberObjectConversionChecker : public Checker<check::ASTCodeBody> {
44public:
45 bool Pedantic;
46
47 NumberObjectConversionChecker();
48
49 void checkASTCodeBody(const Decl *D, AnalysisManager &AM,
50 BugReporter &BR) const;
51
52private:
53 StatementMatcher Matcher;
54};
55
56class Callback : public MatchFinder::MatchCallback {
57 const NumberObjectConversionChecker *C;
58 BugReporter &BR;
59 AnalysisDeclContext *ADC;
60
61public:
62 Callback(const NumberObjectConversionChecker *C,
63 BugReporter &BR, AnalysisDeclContext *ADC)
64 : C(C), BR(BR), ADC(ADC) {}
65 void run(const MatchFinder::MatchResult &Result) override;
66};
67} // end of anonymous namespace
68
69void Callback::run(const MatchFinder::MatchResult &Result) {
70 bool IsPedanticMatch =
71 (Result.Nodes.getNodeAs<Stmt>("pedantic") != nullptr);
72 if (IsPedanticMatch && !C->Pedantic)
73 return;
74
75 ASTContext &ACtx = ADC->getASTContext();
76
77 if (const Expr *CheckIfNull =
78 Result.Nodes.getNodeAs<Expr>("check_if_null")) {
79 // Unless the macro indicates that the intended type is clearly not
80 // a pointer type, we should avoid warning on comparing pointers
81 // to zero literals in non-pedantic mode.
82 // FIXME: Introduce an AST matcher to implement the macro-related logic?
83 bool MacroIndicatesWeShouldSkipTheCheck = false;
84 SourceLocation Loc = CheckIfNull->getBeginLoc();
85 if (Loc.isMacroID()) {
86 StringRef MacroName = Lexer::getImmediateMacroName(
87 Loc, ACtx.getSourceManager(), ACtx.getLangOpts());
88 if (MacroName == "NULL" || MacroName == "nil")
89 return;
90 if (MacroName == "YES" || MacroName == "NO")
91 MacroIndicatesWeShouldSkipTheCheck = true;
92 }
93 if (!MacroIndicatesWeShouldSkipTheCheck) {
94 Expr::EvalResult EVResult;
95 if (CheckIfNull->IgnoreParenCasts()->EvaluateAsInt(
96 EVResult, ACtx, Expr::SE_AllowSideEffects)) {
97 llvm::APSInt Result = EVResult.Val.getInt();
98 if (Result == 0) {
99 if (!C->Pedantic)
100 return;
101 IsPedanticMatch = true;
102 }
103 }
104 }
105 }
106
107 const Stmt *Conv = Result.Nodes.getNodeAs<Stmt>("conv");
108 assert(Conv);
109
110 const Expr *ConvertedCObject = Result.Nodes.getNodeAs<Expr>("c_object");
111 const Expr *ConvertedCppObject = Result.Nodes.getNodeAs<Expr>("cpp_object");
112 const Expr *ConvertedObjCObject = Result.Nodes.getNodeAs<Expr>("objc_object");
113 bool IsCpp = (ConvertedCppObject != nullptr);
114 bool IsObjC = (ConvertedObjCObject != nullptr);
115 const Expr *Obj = IsObjC ? ConvertedObjCObject
116 : IsCpp ? ConvertedCppObject
117 : ConvertedCObject;
118 assert(Obj);
119
120 bool IsComparison =
121 (Result.Nodes.getNodeAs<Stmt>("comparison") != nullptr);
122
123 bool IsOSNumber =
124 (Result.Nodes.getNodeAs<Decl>("osnumber") != nullptr);
125
126 bool IsInteger =
127 (Result.Nodes.getNodeAs<QualType>("int_type") != nullptr);
128 bool IsObjCBool =
129 (Result.Nodes.getNodeAs<QualType>("objc_bool_type") != nullptr);
130 bool IsCppBool =
131 (Result.Nodes.getNodeAs<QualType>("cpp_bool_type") != nullptr);
132
133 llvm::SmallString<64> Msg;
134 llvm::raw_svector_ostream OS(Msg);
135
136 // Remove ObjC ARC qualifiers.
137 QualType ObjT = Obj->getType().getUnqualifiedType();
138
139 // Remove consts from pointers.
140 if (IsCpp) {
141 assert(ObjT.getCanonicalType()->isPointerType());
142 ObjT = ACtx.getPointerType(
144 }
145
146 if (IsComparison)
147 OS << "Comparing ";
148 else
149 OS << "Converting ";
150
151 OS << "a pointer value of type '" << ObjT << "' to a ";
152
153 std::string EuphemismForPlain = "primitive";
154 std::string SuggestedApi = IsObjC ? (IsInteger ? "" : "-boolValue")
155 : IsCpp ? (IsOSNumber ? "" : "getValue()")
156 : "CFNumberGetValue()";
157 if (SuggestedApi.empty()) {
158 // A generic message if we're not sure what API should be called.
159 // FIXME: Pattern-match the integer type to make a better guess?
160 SuggestedApi =
161 "a method on '" + ObjT.getAsString() + "' to get the scalar value";
162 // "scalar" is not quite correct or common, but some documentation uses it
163 // when describing object methods we suggest. For consistency, we use
164 // "scalar" in the whole sentence when we need to use this word in at least
165 // one place, otherwise we use "primitive".
166 EuphemismForPlain = "scalar";
167 }
168
169 if (IsInteger)
170 OS << EuphemismForPlain << " integer value";
171 else if (IsObjCBool)
172 OS << EuphemismForPlain << " BOOL value";
173 else if (IsCppBool)
174 OS << EuphemismForPlain << " bool value";
175 else // Branch condition?
176 OS << EuphemismForPlain << " boolean value";
177
178
179 if (IsPedanticMatch)
180 OS << "; instead, either compare the pointer to "
181 << (IsObjC ? "nil" : IsCpp ? "nullptr" : "NULL") << " or ";
182 else
183 OS << "; did you mean to ";
184
185 if (IsComparison)
186 OS << "compare the result of calling " << SuggestedApi;
187 else
188 OS << "call " << SuggestedApi;
189
190 if (!IsPedanticMatch)
191 OS << "?";
192
194 ADC->getDecl(), C, "Suspicious number object conversion", "Logic error",
195 OS.str(),
197 Conv->getSourceRange());
198}
199
201 // Currently this matches CoreFoundation opaque pointer typedefs.
202 auto CSuspiciousNumberObjectExprM = expr(ignoringParenImpCasts(
203 expr(hasType(typedefType(
204 hasDeclaration(anyOf(typedefDecl(hasName("CFNumberRef")),
205 typedefDecl(hasName("CFBooleanRef")))))))
206 .bind("c_object")));
207
208 // Currently this matches XNU kernel number-object pointers.
209 auto CppSuspiciousNumberObjectExprM =
210 expr(ignoringParenImpCasts(
211 expr(hasType(hasCanonicalType(
212 pointerType(pointee(hasCanonicalType(
214 anyOf(
215 cxxRecordDecl(hasName("OSBoolean")),
216 cxxRecordDecl(hasName("OSNumber"))
217 .bind("osnumber"))))))))))
218 .bind("cpp_object")));
219
220 // Currently this matches NeXTSTEP number objects.
221 auto ObjCSuspiciousNumberObjectExprM =
222 expr(ignoringParenImpCasts(
223 expr(hasType(hasCanonicalType(
224 objcObjectPointerType(pointee(
225 qualType(hasCanonicalType(
227 objcInterfaceDecl(hasName("NSNumber")))))))))))
228 .bind("objc_object")));
229
230 auto SuspiciousNumberObjectExprM = anyOf(
231 CSuspiciousNumberObjectExprM,
232 CppSuspiciousNumberObjectExprM,
233 ObjCSuspiciousNumberObjectExprM);
234
235 // Useful for predicates like "Unless we've seen the same object elsewhere".
236 auto AnotherSuspiciousNumberObjectExprM =
237 expr(anyOf(
238 equalsBoundNode("c_object"),
239 equalsBoundNode("objc_object"),
240 equalsBoundNode("cpp_object")));
241
242 // The .bind here is in order to compose the error message more accurately.
243 auto ObjCSuspiciousScalarBooleanTypeM =
245 .bind("objc_bool_type");
246
247 // The .bind here is in order to compose the error message more accurately.
248 auto SuspiciousScalarBooleanTypeM =
249 qualType(anyOf(qualType(booleanType()).bind("cpp_bool_type"),
250 ObjCSuspiciousScalarBooleanTypeM));
251
252 // The .bind here is in order to compose the error message more accurately.
253 // Also avoid intptr_t and uintptr_t because they were specifically created
254 // for storing pointers.
255 auto SuspiciousScalarNumberTypeM =
256 qualType(hasCanonicalType(isInteger()),
258 hasDeclaration(typedefDecl(matchesName("^::u?intptr_t$"))))))
259 .bind("int_type");
260
261 auto SuspiciousScalarTypeM =
262 qualType(anyOf(SuspiciousScalarBooleanTypeM,
263 SuspiciousScalarNumberTypeM));
264
265 auto SuspiciousScalarExprM =
266 expr(ignoringParenImpCasts(expr(hasType(SuspiciousScalarTypeM))));
267
268 auto ConversionThroughAssignmentM =
269 binaryOperator(allOf(hasOperatorName("="),
270 hasLHS(SuspiciousScalarExprM),
271 hasRHS(SuspiciousNumberObjectExprM)));
272
273 auto ConversionThroughBranchingM =
275 hasCondition(SuspiciousNumberObjectExprM),
276 unless(hasConditionVariableStatement(declStmt())
277 ))).bind("pedantic");
278
279 auto ConversionThroughCallM =
280 callExpr(hasAnyArgument(allOf(hasType(SuspiciousScalarTypeM),
281 ignoringParenImpCasts(
282 SuspiciousNumberObjectExprM))));
283
284 // We bind "check_if_null" to modify the warning message
285 // in case it was intended to compare a pointer to 0 with a relatively-ok
286 // construct "x == 0" or "x != 0".
287 auto ConversionThroughEquivalenceM =
288 binaryOperator(allOf(anyOf(hasOperatorName("=="), hasOperatorName("!=")),
289 hasEitherOperand(SuspiciousNumberObjectExprM),
290 hasEitherOperand(SuspiciousScalarExprM
291 .bind("check_if_null"))))
292 .bind("comparison");
293
294 auto ConversionThroughComparisonM =
295 binaryOperator(allOf(anyOf(hasOperatorName(">="), hasOperatorName(">"),
296 hasOperatorName("<="), hasOperatorName("<")),
297 hasEitherOperand(SuspiciousNumberObjectExprM),
298 hasEitherOperand(SuspiciousScalarExprM)))
299 .bind("comparison");
300
301 auto ConversionThroughConditionalOperatorM =
303 hasCondition(SuspiciousNumberObjectExprM),
304 unless(hasTrueExpression(
305 hasDescendant(AnotherSuspiciousNumberObjectExprM))),
306 unless(hasFalseExpression(
307 hasDescendant(AnotherSuspiciousNumberObjectExprM)))))
308 .bind("pedantic");
309
310 auto ConversionThroughExclamationMarkM =
311 unaryOperator(allOf(hasOperatorName("!"),
312 has(expr(SuspiciousNumberObjectExprM))))
313 .bind("pedantic");
314
315 auto ConversionThroughExplicitBooleanCastM =
316 explicitCastExpr(allOf(hasType(SuspiciousScalarBooleanTypeM),
317 has(expr(SuspiciousNumberObjectExprM))));
318
319 auto ConversionThroughExplicitNumberCastM =
320 explicitCastExpr(allOf(hasType(SuspiciousScalarNumberTypeM),
321 has(expr(SuspiciousNumberObjectExprM))));
322
323 auto ConversionThroughInitializerM =
324 declStmt(hasSingleDecl(
325 varDecl(hasType(SuspiciousScalarTypeM),
326 hasInitializer(SuspiciousNumberObjectExprM))));
327
328 auto FinalM = stmt(anyOf(ConversionThroughAssignmentM,
329 ConversionThroughBranchingM,
330 ConversionThroughCallM,
331 ConversionThroughComparisonM,
332 ConversionThroughConditionalOperatorM,
333 ConversionThroughEquivalenceM,
334 ConversionThroughExclamationMarkM,
335 ConversionThroughExplicitBooleanCastM,
336 ConversionThroughExplicitNumberCastM,
337 ConversionThroughInitializerM)).bind("conv");
338
339 return traverse(TK_AsIs, stmt(forEachDescendant(FinalM)));
340}
341
342NumberObjectConversionChecker::NumberObjectConversionChecker()
343 : Matcher(buildMatcher()) {}
344
345void NumberObjectConversionChecker::checkASTCodeBody(const Decl *D,
346 AnalysisManager &AM,
347 BugReporter &BR) const {
348 static constexpr llvm::StringLiteral Names[] = {
349 "CFNumberRef", "CFBooleanRef", "OSBoolean", "OSNumber", "NSNumber"};
350 const IdentifierTable &Idents = AM.getASTContext().Idents;
351 auto IsDeclared = [&Idents](StringRef Name) {
352 return llvm::is_contained(Idents, Name);
353 };
354 if (llvm::none_of(Names, IsDeclared))
355 return;
356
357 MatchFinder F;
358 Callback CB(this, BR, AM.getAnalysisDeclContext(D));
359
360 F.addMatcher(Matcher, &CB);
361 F.match(*D->getBody(), AM.getASTContext());
362}
363
364void ento::registerNumberObjectConversionChecker(CheckerManager &Mgr) {
365 NumberObjectConversionChecker *Chk =
366 Mgr.registerChecker<NumberObjectConversionChecker>();
367 Chk->Pedantic =
368 Mgr.getAnalyzerOptions().getCheckerBooleanOption(Chk, "Pedantic");
369}
370
371bool ento::shouldRegisterNumberObjectConversionChecker(const CheckerManager &mgr) {
372 return true;
373}
Result
Implement __builtin_bit_cast and related operations.
static StatementMatcher buildMatcher()
APSInt & getInt()
Definition APValue.h:577
SourceManager & getSourceManager()
Definition ASTContext.h:923
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
IdentifierTable & Idents
Definition ASTContext.h:862
const LangOptions & getLangOpts() const
ASTContext & getASTContext() const
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1106
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:703
QualType getType() const
Definition Expr.h:146
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1111
QualType getCanonicalType() const
Definition TypeBase.h:8732
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8774
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
bool isPointerType() const
Definition TypeBase.h:8917
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
Called when the Match registered for it was successfully found in the AST.
void addMatcher(const DeclarationMatcher &NodeMatch, MatchCallback *Action)
Adds a matcher to execute when running over the AST.
void match(const T &Node, ASTContext &Context)
Calls the registered callbacks on all matches on the given Node.
ASTContext & getASTContext() override
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
const SourceManager & getSourceManager()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
const AnalyzerOptions & getAnalyzerOptions() const
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicOperatorMatcherFunc< 1, 1 > unless
Matches if the provided matcher does not match.
const AstTypeMatcher< ObjCObjectPointerType > objcObjectPointerType
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::ArgumentAdaptingMatcherFunc< internal::ForEachDescendantMatcher > forEachDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, UnaryOperator > unaryOperator
Matches unary operator expressions.
internal::Matcher< Stmt > StatementMatcher
const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator > binaryOperator
Matches binary operator expressions.
const internal::ArgumentAdaptingMatcherFunc< internal::HasMatcher > has
Matches AST nodes that have child AST nodes that match the provided matcher.
const internal::VariadicDynCastAllOfMatcher< Stmt, ExplicitCastExpr > explicitCastExpr
Matches explicit cast expressions.
const internal::VariadicDynCastAllOfMatcher< Decl, ObjCInterfaceDecl > objcInterfaceDecl
Matches Objective-C interface declarations.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> allOf
Matches if all given matchers match.
const AstTypeMatcher< RecordType > recordType
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
internal::Matcher< T > traverse(TraversalKind TK, const internal::Matcher< T > &InnerMatcher)
Causes all nested matchers to be matched with the specified traversal kind.
internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher< Decl > > hasDeclaration(const internal::Matcher< Decl > &InnerMatcher)
Matches a node if the declaration associated with that node matches the given matcher.
const AstTypeMatcher< TypedefType > typedefType
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclStmt > declStmt
Matches declaration statements.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, ConditionalOperator > conditionalOperator
Matches conditional operator expressions.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
const internal::VariadicAllOfMatcher< QualType > qualType
Matches QualTypes in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, IfStmt > ifStmt
Matches if statements.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Stencil run(MatchConsumer< std::string > C)
Wraps a MatchConsumer in a Stencil, so that it can be used in a Stencil.
Definition Stencil.cpp:489
Top level wrappers for InstallAPI frontend operations.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
Stmt Stmt * Callback
Definition StmtOpenMP.h:930
@ TK_AsIs
Will traverse all child nodes.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
Contains all information for a given match.