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.
DefaultMethodFilter(const ObjCMethodDecl * M)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:
MethodCrawler(const IvarToPropertyMapTy & InMap,const ObjCMethodDecl * InMD,const ObjCInterfaceDecl * InID,BugReporter & InBR,const CheckerBase * Checker,AnalysisDeclContext * InDCtx)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 
VisitStmt(const Stmt * S)76     void VisitStmt(const Stmt *S) { VisitChildren(S); }
77 
78     void VisitBinaryOperator(const BinaryOperator *BO);
79 
VisitChildren(const Stmt * S)80     void VisitChildren(const Stmt *S) {
81       for (const Stmt *Child : S->children())
82         if (Child)
83           this->Visit(Child);
84     }
85   };
86 
87 public:
88   bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
89 
DirectIvarAssignment()90   DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
91 
92   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
93                     BugReporter &BR) const;
94 };
95 
findPropertyBackingIvar(const ObjCPropertyDecl * PD,const ObjCInterfaceDecl * InterD,ASTContext & Ctx)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 
checkASTDecl(const ObjCImplementationDecl * D,AnalysisManager & Mgr,BugReporter & BR) const118 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 (const auto *M : D->instance_methods()) {
143     AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
144 
145     if ((*ShouldSkipMethod)(M))
146       continue;
147 
148     const Stmt *Body = M->getBody();
149     assert(Body);
150 
151     MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
152                      DCtx);
153     MC.VisitStmt(Body);
154   }
155 }
156 
isAnnotatedToAllowDirectAssignment(const Decl * D)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")
161       return true;
162   return false;
163 }
164 
VisitBinaryOperator(const BinaryOperator * BO)165 void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
166                                                     const BinaryOperator *BO) {
167   if (!BO->isAssignmentOp())
168     return;
169 
170   const ObjCIvarRefExpr *IvarRef =
171           dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
172 
173   if (!IvarRef)
174     return;
175 
176   if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
177     IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
178 
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))
187         return;
188 
189       ObjCMethodDecl *GetterMethod =
190           InterfD->getInstanceMethod(PD->getGetterName());
191       ObjCMethodDecl *SetterMethod =
192           InterfD->getInstanceMethod(PD->getSetterName());
193 
194       if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
195         return;
196 
197       if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
198         return;
199 
200       BR.EmitBasicReport(
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));
205     }
206   }
207 }
208 }
209 
210 // Register the checker that checks for direct accesses in all functions,
211 // except for the initialization and copy routines.
registerDirectIvarAssignment(CheckerManager & mgr)212 void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
213   mgr.registerChecker<DirectIvarAssignment>();
214 }
215 
216 // Register the checker that checks for direct accesses in functions annotated
217 // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
AttrFilter(const ObjCMethodDecl * M)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")
221       return false;
222   return true;
223 }
224 
registerDirectIvarAssignmentForAnnotatedFunctions(CheckerManager & mgr)225 void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
226     CheckerManager &mgr) {
227   mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
228 }
229