35#include "llvm/ADT/APSInt.h"
43class NumberObjectConversionChecker :
public Checker<check::ASTCodeBody> {
47 NumberObjectConversionChecker();
49 void checkASTCodeBody(
const Decl *D, AnalysisManager &AM,
50 BugReporter &BR)
const;
57 const NumberObjectConversionChecker *C;
59 AnalysisDeclContext *ADC;
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;
70 bool IsPedanticMatch =
71 (
Result.Nodes.getNodeAs<Stmt>(
"pedantic") !=
nullptr);
72 if (IsPedanticMatch && !
C->Pedantic)
77 if (
const Expr *CheckIfNull =
78 Result.Nodes.getNodeAs<Expr>(
"check_if_null")) {
83 bool MacroIndicatesWeShouldSkipTheCheck =
false;
84 SourceLocation Loc = CheckIfNull->getBeginLoc();
88 if (MacroName ==
"NULL" || MacroName ==
"nil")
90 if (MacroName ==
"YES" || MacroName ==
"NO")
91 MacroIndicatesWeShouldSkipTheCheck =
true;
93 if (!MacroIndicatesWeShouldSkipTheCheck) {
94 Expr::EvalResult EVResult;
95 if (CheckIfNull->IgnoreParenCasts()->EvaluateAsInt(
101 IsPedanticMatch =
true;
107 const Stmt *Conv =
Result.Nodes.getNodeAs<Stmt>(
"conv");
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
121 (
Result.Nodes.getNodeAs<Stmt>(
"comparison") !=
nullptr);
124 (
Result.Nodes.getNodeAs<
Decl>(
"osnumber") !=
nullptr);
127 (
Result.Nodes.getNodeAs<QualType>(
"int_type") !=
nullptr);
129 (
Result.Nodes.getNodeAs<QualType>(
"objc_bool_type") !=
nullptr);
131 (
Result.Nodes.getNodeAs<QualType>(
"cpp_bool_type") !=
nullptr);
133 llvm::SmallString<64> Msg;
134 llvm::raw_svector_ostream
OS(Msg);
151 OS <<
"a pointer value of type '" << ObjT <<
"' to a ";
153 std::string EuphemismForPlain =
"primitive";
154 std::string SuggestedApi = IsObjC ? (IsInteger ?
"" :
"-boolValue")
155 : IsCpp ? (IsOSNumber ?
"" :
"getValue()")
156 :
"CFNumberGetValue()";
157 if (SuggestedApi.empty()) {
161 "a method on '" + ObjT.getAsString() +
"' to get the scalar value";
166 EuphemismForPlain =
"scalar";
170 OS << EuphemismForPlain <<
" integer value";
172 OS << EuphemismForPlain <<
" BOOL value";
174 OS << EuphemismForPlain <<
" bool value";
176 OS << EuphemismForPlain <<
" boolean value";
180 OS <<
"; instead, either compare the pointer to "
181 << (IsObjC ?
"nil" : IsCpp ?
"nullptr" :
"NULL") <<
" or ";
183 OS <<
"; did you mean to ";
186 OS <<
"compare the result of calling " << SuggestedApi;
188 OS <<
"call " << SuggestedApi;
190 if (!IsPedanticMatch)
194 ADC->
getDecl(),
C,
"Suspicious number object conversion",
"Logic error",
202 auto CSuspiciousNumberObjectExprM =
expr(ignoringParenImpCasts(
209 auto CppSuspiciousNumberObjectExprM =
210 expr(ignoringParenImpCasts(
211 expr(hasType(hasCanonicalType(
217 .bind(
"osnumber"))))))))))
218 .bind(
"cpp_object")));
221 auto ObjCSuspiciousNumberObjectExprM =
222 expr(ignoringParenImpCasts(
223 expr(hasType(hasCanonicalType(
228 .bind(
"objc_object")));
230 auto SuspiciousNumberObjectExprM =
anyOf(
231 CSuspiciousNumberObjectExprM,
232 CppSuspiciousNumberObjectExprM,
233 ObjCSuspiciousNumberObjectExprM);
236 auto AnotherSuspiciousNumberObjectExprM =
238 equalsBoundNode(
"c_object"),
239 equalsBoundNode(
"objc_object"),
240 equalsBoundNode(
"cpp_object")));
243 auto ObjCSuspiciousScalarBooleanTypeM =
245 .bind(
"objc_bool_type");
248 auto SuspiciousScalarBooleanTypeM =
250 ObjCSuspiciousScalarBooleanTypeM));
255 auto SuspiciousScalarNumberTypeM =
256 qualType(hasCanonicalType(isInteger()),
261 auto SuspiciousScalarTypeM =
263 SuspiciousScalarNumberTypeM));
265 auto SuspiciousScalarExprM =
266 expr(ignoringParenImpCasts(
expr(hasType(SuspiciousScalarTypeM))));
268 auto ConversionThroughAssignmentM =
270 hasLHS(SuspiciousScalarExprM),
271 hasRHS(SuspiciousNumberObjectExprM)));
273 auto ConversionThroughBranchingM =
275 hasCondition(SuspiciousNumberObjectExprM),
277 ))).bind(
"pedantic");
279 auto ConversionThroughCallM =
280 callExpr(hasAnyArgument(
allOf(hasType(SuspiciousScalarTypeM),
281 ignoringParenImpCasts(
282 SuspiciousNumberObjectExprM))));
287 auto ConversionThroughEquivalenceM =
289 hasEitherOperand(SuspiciousNumberObjectExprM),
290 hasEitherOperand(SuspiciousScalarExprM
291 .bind(
"check_if_null"))))
294 auto ConversionThroughComparisonM =
296 hasOperatorName(
"<="), hasOperatorName(
"<")),
297 hasEitherOperand(SuspiciousNumberObjectExprM),
298 hasEitherOperand(SuspiciousScalarExprM)))
301 auto ConversionThroughConditionalOperatorM =
303 hasCondition(SuspiciousNumberObjectExprM),
306 unless(hasFalseExpression(
310 auto ConversionThroughExclamationMarkM =
312 has(
expr(SuspiciousNumberObjectExprM))))
315 auto ConversionThroughExplicitBooleanCastM =
317 has(
expr(SuspiciousNumberObjectExprM))));
319 auto ConversionThroughExplicitNumberCastM =
321 has(
expr(SuspiciousNumberObjectExprM))));
323 auto ConversionThroughInitializerM =
325 varDecl(hasType(SuspiciousScalarTypeM),
326 hasInitializer(SuspiciousNumberObjectExprM))));
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");
342NumberObjectConversionChecker::NumberObjectConversionChecker()
345void NumberObjectConversionChecker::checkASTCodeBody(
const Decl *D,
348 static constexpr llvm::StringLiteral Names[] = {
349 "CFNumberRef",
"CFBooleanRef",
"OSBoolean",
"OSNumber",
"NSNumber"};
351 auto IsDeclared = [&Idents](StringRef Name) {
352 return llvm::is_contained(Idents, Name);
354 if (llvm::none_of(Names, IsDeclared))
364void ento::registerNumberObjectConversionChecker(CheckerManager &Mgr) {
365 NumberObjectConversionChecker *Chk =
371bool ento::shouldRegisterNumberObjectConversionChecker(
const CheckerManager &mgr) {
Result
Implement __builtin_bit_cast and related operations.
static StatementMatcher buildMatcher()
SourceManager & getSourceManager()
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
const Decl * getDecl() const
ASTContext & getASTContext() const
Decl - This represents one declaration (or definition), e.g.
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
bool isPointerType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
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.
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.
Top level wrappers for InstallAPI frontend operations.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ TK_AsIs
Will traverse all child nodes.
@ Result
The result type of a method or function.
APValue Val
Val - This is the value the expression can be folded to.
Contains all information for a given match.