clang 24.0.0git
OSObjectCStyleCast.cpp
Go to the documentation of this file.
1//===- OSObjectCStyleCast.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 OSObjectCStyleCast checker, which checks for C-style casts
10// of OSObjects. Such casts almost always indicate a code smell,
11// as an explicit static or dynamic cast should be used instead.
12//===----------------------------------------------------------------------===//
13
20#include "llvm/Support/Debug.h"
21
22using namespace clang;
23using namespace ento;
24using namespace ast_matchers;
25
27
28namespace {
29static constexpr const char *const WarnAtNode = "WarnAtNode";
30static constexpr const char *const WarnRecordDecl = "WarnRecordDecl";
31
32class OSObjectCStyleCastChecker : public Checker<check::ASTCodeBody> {
33 // Building the matcher is expensive, so build it once per checker instead of
34 // once per function body.
35 const StatementMatcher CastsM = makeCastsMatcher();
36
37public:
38 void checkASTCodeBody(const Decl *D, AnalysisManager &AM,
39 BugReporter &BR) const;
40};
41} // namespace
42
43namespace clang {
44namespace ast_matchers {
45AST_MATCHER_P(StringLiteral, mentionsBoundType, std::string, BindingID) {
46 return Builder->removeBindings([this, &Node](const BoundNodesMap &Nodes) {
47 const DynTypedNode &BN = Nodes.getNode(this->BindingID);
48 if (const auto *ND = BN.get<NamedDecl>()) {
49 return ND->getName() != Node.getString();
50 }
51 return true;
52 });
53}
54} // end namespace ast_matchers
55} // end namespace clang
56
57static void emitDiagnostics(const BoundNodes &Nodes,
58 BugReporter &BR,
60 const OSObjectCStyleCastChecker *Checker) {
61 const auto *CE = Nodes.getNodeAs<CastExpr>(WarnAtNode);
62 const CXXRecordDecl *RD = Nodes.getNodeAs<CXXRecordDecl>(WarnRecordDecl);
63 assert(CE && RD);
64
65 std::string Diagnostics;
66 llvm::raw_string_ostream OS(Diagnostics);
67 OS << "C-style cast of an OSObject is prone to type confusion attacks; "
68 << "use 'OSRequiredCast' if the object is definitely of type '"
69 << RD->getNameAsString() << "', or 'OSDynamicCast' followed by "
70 << "a null check if unsure",
71
73 ADC->getDecl(),
74 Checker,
75 /*Name=*/"OSObject C-Style Cast",
77 Diagnostics,
79 CE->getSourceRange());
80}
81
82static decltype(auto) hasTypePointingTo(DeclarationMatcher DeclM) {
83 return hasType(pointerType(pointee(hasDeclaration(DeclM))));
84}
85
87 auto DynamicCastM = callExpr(callee(functionDecl(hasName("safeMetaCast"))));
88 // 'allocClassWithName' allocates an object with the given type.
89 // The type is actually provided as a string argument (type's name).
90 // This makes the following pattern possible:
91 //
92 // Foo *object = (Foo *)allocClassWithName("Foo");
93 //
94 // While OSRequiredCast can be used here, it is still not a useful warning.
95 auto AllocClassWithNameM = callExpr(
96 callee(functionDecl(hasName("allocClassWithName"))),
97 // Here we want to make sure that the string argument matches the
98 // type in the cast expression.
99 hasArgument(0, stringLiteral(mentionsBoundType(WarnRecordDecl))));
100
101 auto OSObjTypeM =
102 hasTypePointingTo(cxxRecordDecl(isDerivedFrom("OSMetaClassBase")));
103 auto OSObjSubclassM = hasTypePointingTo(
104 cxxRecordDecl(isDerivedFrom("OSObject")).bind(WarnRecordDecl));
105
106 auto CastM =
108 allOf(OSObjSubclassM,
109 hasSourceExpression(
110 allOf(OSObjTypeM,
111 unless(anyOf(DynamicCastM, AllocClassWithNameM))))))
112 .bind(WarnAtNode);
113
114 return stmt(forEachDescendant(CastM));
115}
116
117void OSObjectCStyleCastChecker::checkASTCodeBody(const Decl *D,
118 AnalysisManager &AM,
119 BugReporter &BR) const {
120 AnalysisDeclContext *ADC = AM.getAnalysisDeclContext(D);
121
122 auto Matches = match(CastsM, *D->getBody(), AM.getASTContext());
123 for (BoundNodes Match : Matches)
124 emitDiagnostics(Match, BR, ADC, this);
125}
126
127void ento::registerOSObjectCStyleCast(CheckerManager &Mgr) {
128 Mgr.registerChecker<OSObjectCStyleCastChecker>();
129}
130
131bool ento::shouldRegisterOSObjectCStyleCast(const CheckerManager &mgr) {
132 return true;
133}
#define AST_MATCHER_P(Type, DefineMatcher, ParamType, Param)
AST_MATCHER_P(Type, DefineMatcher, ParamType, Param) { ... } defines a single-parameter function name...
static decltype(auto) hasTypePointingTo(DeclarationMatcher DeclM)
static StatementMatcher makeCastsMatcher()
static void emitDiagnostics(const BoundNodes &Nodes, BugReporter &BR, AnalysisDeclContext *ADC, const OSObjectCStyleCastChecker *Checker)
static void emitDiagnostics(BoundNodes &Match, const Decl *D, BugReporter &BR, AnalysisManager &AM, const ObjCAutoreleaseWriteChecker *Checker)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
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:1105
A dynamically typed AST node container.
const T * get() const
Retrieve the stored node as type T.
This represents a decl that may have a name.
Definition Decl.h:276
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
Maps string IDs to AST nodes matched by parts of a matcher.
const T * getNodeAs(StringRef ID) const
Returns the AST node bound to ID.
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={})
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< Stmt, CStyleCastExpr > cStyleCastExpr
Matches a C-style cast expression.
const internal::VariadicOperatorMatcherFunc< 1, 1 > unless
Matches if the provided matcher does not match.
internal::Matcher< Decl > DeclarationMatcher
Types of matchers for the top-level classes in the AST class hierarchy.
const internal::VariadicDynCastAllOfMatcher< Stmt, StringLiteral > stringLiteral
Matches string literals (also matches wide string literals).
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.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
internal::Matcher< Stmt > StatementMatcher
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> allOf
Matches if all given matchers match.
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicDynCastAllOfMatcher< Decl, CXXRecordDecl > cxxRecordDecl
Matches C++ class declarations.
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 internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824