xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp (revision d174edffa06a8212b784dbecdb4939ff300793a7)
1 //=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Check that Objective C properties are set with the setter, not though a
11 //      direct assignment.
12 //
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")))
16 //
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.
21 //
22 //===----------------------------------------------------------------------===//
23 
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"
32 
33 using namespace clang;
34 using namespace ento;
35 
36 namespace {
37 
38 /// The default method filter, which is used to filter out the methods on which
39 /// the check should not be performed.
40 ///
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)
49     return true;
50   return false;
51 }
52 
53 class DirectIvarAssignment :
54   public Checker<check::ASTDecl<ObjCImplementationDecl> > {
55 
56   typedef llvm::DenseMap<const ObjCIvarDecl*,
57                          const ObjCPropertyDecl*> IvarToPropertyMapTy;
58 
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;
65     BugReporter &BR;
66     const CheckerBase *Checker;
67     LocationOrAnalysisDeclContext DCtx;
68 
69   public:
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) {}
75 
76     void VisitStmt(const Stmt *S) { VisitChildren(S); }
77 
78     void VisitBinaryOperator(const BinaryOperator *BO);
79 
80     void VisitChildren(const Stmt *S) {
81       for (Stmt::const_child_range I = S->children(); I; ++I)
82         if (*I)
83          this->Visit(*I);
84     }
85   };
86 
87 public:
88   bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
89 
90   DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
91 
92   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
93                     BugReporter &BR) const;
94 };
95 
96 static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
97                                                const ObjCInterfaceDecl *InterD,
98                                                ASTContext &Ctx) {
99   // Check for synthesized ivars.
100   ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
101   if (ID)
102     return ID;
103 
104   ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
105 
106   // Check for existing "_PropName".
107   ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
108   if (ID)
109     return ID;
110 
111   // Check for existing "PropName".
112   IdentifierInfo *PropIdent = PD->getIdentifier();
113   ID = NonConstInterD->lookupInstanceVariable(PropIdent);
114 
115   return ID;
116 }
117 
118 void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
119                                        AnalysisManager& Mgr,
120                                        BugReporter &BR) const {
121   const ObjCInterfaceDecl *InterD = D->getClassInterface();
122 
123 
124   IvarToPropertyMapTy IvarToPropMap;
125 
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());
131 
132     if (!ID)
133       continue;
134 
135     // Store the IVar to property mapping.
136     IvarToPropMap[ID] = PD;
137   }
138 
139   if (IvarToPropMap.empty())
140     return;
141 
142   for (ObjCImplementationDecl::instmeth_iterator I = D->instmeth_begin(),
143       E = D->instmeth_end(); I != E; ++I) {
144 
145     ObjCMethodDecl *M = *I;
146     AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
147 
148     if ((*ShouldSkipMethod)(M))
149       continue;
150 
151     const Stmt *Body = M->getBody();
152     assert(Body);
153 
154     MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
155                      DCtx);
156     MC.VisitStmt(Body);
157   }
158 }
159 
160 static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
161   for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
162     if (Ann->getAnnotation() ==
163         "objc_allow_direct_instance_variable_assignment")
164       return true;
165   return false;
166 }
167 
168 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
169                                                     const BinaryOperator *BO) {
170   if (!BO->isAssignmentOp())
171     return;
172 
173   const ObjCIvarRefExpr *IvarRef =
174           dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
175 
176   if (!IvarRef)
177     return;
178 
179   if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
180     IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
181 
182     if (I != IvarToPropMap.end()) {
183       const ObjCPropertyDecl *PD = I->second;
184       // Skip warnings on Ivars, annotated with
185       // objc_allow_direct_instance_variable_assignment. This annotation serves
186       // as a false positive suppression mechanism for the checker. The
187       // annotation is allowed on properties and ivars.
188       if (isAnnotatedToAllowDirectAssignment(PD) ||
189           isAnnotatedToAllowDirectAssignment(D))
190         return;
191 
192       ObjCMethodDecl *GetterMethod =
193           InterfD->getInstanceMethod(PD->getGetterName());
194       ObjCMethodDecl *SetterMethod =
195           InterfD->getInstanceMethod(PD->getSetterName());
196 
197       if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
198         return;
199 
200       if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
201         return;
202 
203       BR.EmitBasicReport(
204           MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
205           "Direct assignment to an instance variable backing a property; "
206           "use the setter instead",
207           PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
208     }
209   }
210 }
211 }
212 
213 // Register the checker that checks for direct accesses in all functions,
214 // except for the initialization and copy routines.
215 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
216   mgr.registerChecker<DirectIvarAssignment>();
217 }
218 
219 // Register the checker that checks for direct accesses in functions annotated
220 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
221 static bool AttrFilter(const ObjCMethodDecl *M) {
222   for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
223     if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
224       return false;
225   return true;
226 }
227 
228 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
229     CheckerManager &mgr) {
230   mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
231 }
232