1 //=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Check that Objective C properties are set with the setter, not though a
13 // Two versions of a checker exist: one that checks all methods and the other
14 // that only checks the methods annotated with
15 // __attribute__((annotate("objc_no_direct_instance_variable_assignment")))
17 // The checker does not warn about assignments to Ivars, annotated with
18 // __attribute__((objc_allow_direct_instance_variable_assignment"))). This
19 // annotation serves as a false positive suppression mechanism for the
20 // checker. The annotation is allowed on properties and Ivars.
22 //===----------------------------------------------------------------------===//
24 #include "ClangSACheckers.h"
25 #include "clang/AST/Attr.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
29 #include "clang/StaticAnalyzer/Core/Checker.h"
30 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
31 #include "llvm/ADT/DenseMap.h"
33 using namespace clang;
38 /// The default method filter, which is used to filter out the methods on which
39 /// the check should not be performed.
41 /// Checks for the init, dealloc, and any other functions that might be allowed
42 /// to perform direct instance variable assignment based on their name.
43 static bool DefaultMethodFilter(const ObjCMethodDecl *M) {
44 if (M->getMethodFamily() == OMF_init || M->getMethodFamily() == OMF_dealloc ||
45 M->getMethodFamily() == OMF_copy ||
46 M->getMethodFamily() == OMF_mutableCopy ||
47 M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
48 M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos)
53 class DirectIvarAssignment :
54 public Checker<check::ASTDecl<ObjCImplementationDecl> > {
56 typedef llvm::DenseMap<const ObjCIvarDecl*,
57 const ObjCPropertyDecl*> IvarToPropertyMapTy;
59 /// A helper class, which walks the AST and locates all assignments to ivars
60 /// in the given function.
61 class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
62 const IvarToPropertyMapTy &IvarToPropMap;
63 const ObjCMethodDecl *MD;
64 const ObjCInterfaceDecl *InterfD;
66 const CheckerBase *Checker;
67 LocationOrAnalysisDeclContext DCtx;
70 MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
71 const ObjCInterfaceDecl *InID, BugReporter &InBR,
72 const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
73 : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
74 Checker(Checker), DCtx(InDCtx) {}
76 void VisitStmt(const Stmt *S) { VisitChildren(S); }
78 void VisitBinaryOperator(const BinaryOperator *BO);
80 void VisitChildren(const Stmt *S) {
81 for (Stmt::const_child_range I = S->children(); I; ++I)
88 bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
90 DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
92 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
93 BugReporter &BR) const;
96 static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
97 const ObjCInterfaceDecl *InterD,
99 // Check for synthesized ivars.
100 ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
104 ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
106 // Check for existing "_PropName".
107 ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
111 // Check for existing "PropName".
112 IdentifierInfo *PropIdent = PD->getIdentifier();
113 ID = NonConstInterD->lookupInstanceVariable(PropIdent);
118 void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
119 AnalysisManager& Mgr,
120 BugReporter &BR) const {
121 const ObjCInterfaceDecl *InterD = D->getClassInterface();
124 IvarToPropertyMapTy IvarToPropMap;
126 // Find all properties for this class.
127 for (const auto *PD : InterD->properties()) {
128 // Find the corresponding IVar.
129 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
130 Mgr.getASTContext());
135 // Store the IVar to property mapping.
136 IvarToPropMap[ID] = PD;
139 if (IvarToPropMap.empty())
142 for (const auto *M : D->instance_methods()) {
143 AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
145 if ((*ShouldSkipMethod)(M))
148 const Stmt *Body = M->getBody();
151 MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
157 static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
158 for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
159 if (Ann->getAnnotation() ==
160 "objc_allow_direct_instance_variable_assignment")
165 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
166 const BinaryOperator *BO) {
167 if (!BO->isAssignmentOp())
170 const ObjCIvarRefExpr *IvarRef =
171 dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
176 if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
177 IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
179 if (I != IvarToPropMap.end()) {
180 const ObjCPropertyDecl *PD = I->second;
181 // Skip warnings on Ivars, annotated with
182 // objc_allow_direct_instance_variable_assignment. This annotation serves
183 // as a false positive suppression mechanism for the checker. The
184 // annotation is allowed on properties and ivars.
185 if (isAnnotatedToAllowDirectAssignment(PD) ||
186 isAnnotatedToAllowDirectAssignment(D))
189 ObjCMethodDecl *GetterMethod =
190 InterfD->getInstanceMethod(PD->getGetterName());
191 ObjCMethodDecl *SetterMethod =
192 InterfD->getInstanceMethod(PD->getSetterName());
194 if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
197 if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
201 MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
202 "Direct assignment to an instance variable backing a property; "
203 "use the setter instead",
204 PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
210 // Register the checker that checks for direct accesses in all functions,
211 // except for the initialization and copy routines.
212 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
213 mgr.registerChecker<DirectIvarAssignment>();
216 // Register the checker that checks for direct accesses in functions annotated
217 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
218 static bool AttrFilter(const ObjCMethodDecl *M) {
219 for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
220 if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
225 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
226 CheckerManager &mgr) {
227 mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;