xref: /aosp_15_r20/external/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li //  Check that Objective C properties are set with the setter, not though a
11*67e74705SXin Li //      direct assignment.
12*67e74705SXin Li //
13*67e74705SXin Li //  Two versions of a checker exist: one that checks all methods and the other
14*67e74705SXin Li //      that only checks the methods annotated with
15*67e74705SXin Li //      __attribute__((annotate("objc_no_direct_instance_variable_assignment")))
16*67e74705SXin Li //
17*67e74705SXin Li //  The checker does not warn about assignments to Ivars, annotated with
18*67e74705SXin Li //       __attribute__((objc_allow_direct_instance_variable_assignment"))). This
19*67e74705SXin Li //      annotation serves as a false positive suppression mechanism for the
20*67e74705SXin Li //      checker. The annotation is allowed on properties and Ivars.
21*67e74705SXin Li //
22*67e74705SXin Li //===----------------------------------------------------------------------===//
23*67e74705SXin Li 
24*67e74705SXin Li #include "ClangSACheckers.h"
25*67e74705SXin Li #include "clang/AST/Attr.h"
26*67e74705SXin Li #include "clang/AST/DeclObjC.h"
27*67e74705SXin Li #include "clang/AST/StmtVisitor.h"
28*67e74705SXin Li #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
29*67e74705SXin Li #include "clang/StaticAnalyzer/Core/Checker.h"
30*67e74705SXin Li #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
31*67e74705SXin Li #include "llvm/ADT/DenseMap.h"
32*67e74705SXin Li 
33*67e74705SXin Li using namespace clang;
34*67e74705SXin Li using namespace ento;
35*67e74705SXin Li 
36*67e74705SXin Li namespace {
37*67e74705SXin Li 
38*67e74705SXin Li /// The default method filter, which is used to filter out the methods on which
39*67e74705SXin Li /// the check should not be performed.
40*67e74705SXin Li ///
41*67e74705SXin Li /// Checks for the init, dealloc, and any other functions that might be allowed
42*67e74705SXin Li /// to perform direct instance variable assignment based on their name.
DefaultMethodFilter(const ObjCMethodDecl * M)43*67e74705SXin Li static bool DefaultMethodFilter(const ObjCMethodDecl *M) {
44*67e74705SXin Li   return M->getMethodFamily() == OMF_init ||
45*67e74705SXin Li          M->getMethodFamily() == OMF_dealloc ||
46*67e74705SXin Li          M->getMethodFamily() == OMF_copy ||
47*67e74705SXin Li          M->getMethodFamily() == OMF_mutableCopy ||
48*67e74705SXin Li          M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
49*67e74705SXin Li          M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos;
50*67e74705SXin Li }
51*67e74705SXin Li 
52*67e74705SXin Li class DirectIvarAssignment :
53*67e74705SXin Li   public Checker<check::ASTDecl<ObjCImplementationDecl> > {
54*67e74705SXin Li 
55*67e74705SXin Li   typedef llvm::DenseMap<const ObjCIvarDecl*,
56*67e74705SXin Li                          const ObjCPropertyDecl*> IvarToPropertyMapTy;
57*67e74705SXin Li 
58*67e74705SXin Li   /// A helper class, which walks the AST and locates all assignments to ivars
59*67e74705SXin Li   /// in the given function.
60*67e74705SXin Li   class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
61*67e74705SXin Li     const IvarToPropertyMapTy &IvarToPropMap;
62*67e74705SXin Li     const ObjCMethodDecl *MD;
63*67e74705SXin Li     const ObjCInterfaceDecl *InterfD;
64*67e74705SXin Li     BugReporter &BR;
65*67e74705SXin Li     const CheckerBase *Checker;
66*67e74705SXin Li     LocationOrAnalysisDeclContext DCtx;
67*67e74705SXin Li 
68*67e74705SXin Li   public:
MethodCrawler(const IvarToPropertyMapTy & InMap,const ObjCMethodDecl * InMD,const ObjCInterfaceDecl * InID,BugReporter & InBR,const CheckerBase * Checker,AnalysisDeclContext * InDCtx)69*67e74705SXin Li     MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
70*67e74705SXin Li                   const ObjCInterfaceDecl *InID, BugReporter &InBR,
71*67e74705SXin Li                   const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
72*67e74705SXin Li         : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
73*67e74705SXin Li           Checker(Checker), DCtx(InDCtx) {}
74*67e74705SXin Li 
VisitStmt(const Stmt * S)75*67e74705SXin Li     void VisitStmt(const Stmt *S) { VisitChildren(S); }
76*67e74705SXin Li 
77*67e74705SXin Li     void VisitBinaryOperator(const BinaryOperator *BO);
78*67e74705SXin Li 
VisitChildren(const Stmt * S)79*67e74705SXin Li     void VisitChildren(const Stmt *S) {
80*67e74705SXin Li       for (const Stmt *Child : S->children())
81*67e74705SXin Li         if (Child)
82*67e74705SXin Li           this->Visit(Child);
83*67e74705SXin Li     }
84*67e74705SXin Li   };
85*67e74705SXin Li 
86*67e74705SXin Li public:
87*67e74705SXin Li   bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
88*67e74705SXin Li 
DirectIvarAssignment()89*67e74705SXin Li   DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
90*67e74705SXin Li 
91*67e74705SXin Li   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
92*67e74705SXin Li                     BugReporter &BR) const;
93*67e74705SXin Li };
94*67e74705SXin Li 
findPropertyBackingIvar(const ObjCPropertyDecl * PD,const ObjCInterfaceDecl * InterD,ASTContext & Ctx)95*67e74705SXin Li static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
96*67e74705SXin Li                                                const ObjCInterfaceDecl *InterD,
97*67e74705SXin Li                                                ASTContext &Ctx) {
98*67e74705SXin Li   // Check for synthesized ivars.
99*67e74705SXin Li   ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
100*67e74705SXin Li   if (ID)
101*67e74705SXin Li     return ID;
102*67e74705SXin Li 
103*67e74705SXin Li   ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
104*67e74705SXin Li 
105*67e74705SXin Li   // Check for existing "_PropName".
106*67e74705SXin Li   ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
107*67e74705SXin Li   if (ID)
108*67e74705SXin Li     return ID;
109*67e74705SXin Li 
110*67e74705SXin Li   // Check for existing "PropName".
111*67e74705SXin Li   IdentifierInfo *PropIdent = PD->getIdentifier();
112*67e74705SXin Li   ID = NonConstInterD->lookupInstanceVariable(PropIdent);
113*67e74705SXin Li 
114*67e74705SXin Li   return ID;
115*67e74705SXin Li }
116*67e74705SXin Li 
checkASTDecl(const ObjCImplementationDecl * D,AnalysisManager & Mgr,BugReporter & BR) const117*67e74705SXin Li void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
118*67e74705SXin Li                                        AnalysisManager& Mgr,
119*67e74705SXin Li                                        BugReporter &BR) const {
120*67e74705SXin Li   const ObjCInterfaceDecl *InterD = D->getClassInterface();
121*67e74705SXin Li 
122*67e74705SXin Li 
123*67e74705SXin Li   IvarToPropertyMapTy IvarToPropMap;
124*67e74705SXin Li 
125*67e74705SXin Li   // Find all properties for this class.
126*67e74705SXin Li   for (const auto *PD : InterD->instance_properties()) {
127*67e74705SXin Li     // Find the corresponding IVar.
128*67e74705SXin Li     const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
129*67e74705SXin Li                                                      Mgr.getASTContext());
130*67e74705SXin Li 
131*67e74705SXin Li     if (!ID)
132*67e74705SXin Li       continue;
133*67e74705SXin Li 
134*67e74705SXin Li     // Store the IVar to property mapping.
135*67e74705SXin Li     IvarToPropMap[ID] = PD;
136*67e74705SXin Li   }
137*67e74705SXin Li 
138*67e74705SXin Li   if (IvarToPropMap.empty())
139*67e74705SXin Li     return;
140*67e74705SXin Li 
141*67e74705SXin Li   for (const auto *M : D->instance_methods()) {
142*67e74705SXin Li     AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
143*67e74705SXin Li 
144*67e74705SXin Li     if ((*ShouldSkipMethod)(M))
145*67e74705SXin Li       continue;
146*67e74705SXin Li 
147*67e74705SXin Li     const Stmt *Body = M->getBody();
148*67e74705SXin Li     assert(Body);
149*67e74705SXin Li 
150*67e74705SXin Li     MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
151*67e74705SXin Li                      DCtx);
152*67e74705SXin Li     MC.VisitStmt(Body);
153*67e74705SXin Li   }
154*67e74705SXin Li }
155*67e74705SXin Li 
isAnnotatedToAllowDirectAssignment(const Decl * D)156*67e74705SXin Li static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
157*67e74705SXin Li   for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
158*67e74705SXin Li     if (Ann->getAnnotation() ==
159*67e74705SXin Li         "objc_allow_direct_instance_variable_assignment")
160*67e74705SXin Li       return true;
161*67e74705SXin Li   return false;
162*67e74705SXin Li }
163*67e74705SXin Li 
VisitBinaryOperator(const BinaryOperator * BO)164*67e74705SXin Li void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
165*67e74705SXin Li                                                     const BinaryOperator *BO) {
166*67e74705SXin Li   if (!BO->isAssignmentOp())
167*67e74705SXin Li     return;
168*67e74705SXin Li 
169*67e74705SXin Li   const ObjCIvarRefExpr *IvarRef =
170*67e74705SXin Li           dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
171*67e74705SXin Li 
172*67e74705SXin Li   if (!IvarRef)
173*67e74705SXin Li     return;
174*67e74705SXin Li 
175*67e74705SXin Li   if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
176*67e74705SXin Li     IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
177*67e74705SXin Li 
178*67e74705SXin Li     if (I != IvarToPropMap.end()) {
179*67e74705SXin Li       const ObjCPropertyDecl *PD = I->second;
180*67e74705SXin Li       // Skip warnings on Ivars, annotated with
181*67e74705SXin Li       // objc_allow_direct_instance_variable_assignment. This annotation serves
182*67e74705SXin Li       // as a false positive suppression mechanism for the checker. The
183*67e74705SXin Li       // annotation is allowed on properties and ivars.
184*67e74705SXin Li       if (isAnnotatedToAllowDirectAssignment(PD) ||
185*67e74705SXin Li           isAnnotatedToAllowDirectAssignment(D))
186*67e74705SXin Li         return;
187*67e74705SXin Li 
188*67e74705SXin Li       ObjCMethodDecl *GetterMethod =
189*67e74705SXin Li           InterfD->getInstanceMethod(PD->getGetterName());
190*67e74705SXin Li       ObjCMethodDecl *SetterMethod =
191*67e74705SXin Li           InterfD->getInstanceMethod(PD->getSetterName());
192*67e74705SXin Li 
193*67e74705SXin Li       if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
194*67e74705SXin Li         return;
195*67e74705SXin Li 
196*67e74705SXin Li       if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
197*67e74705SXin Li         return;
198*67e74705SXin Li 
199*67e74705SXin Li       BR.EmitBasicReport(
200*67e74705SXin Li           MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
201*67e74705SXin Li           "Direct assignment to an instance variable backing a property; "
202*67e74705SXin Li           "use the setter instead",
203*67e74705SXin Li           PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
204*67e74705SXin Li     }
205*67e74705SXin Li   }
206*67e74705SXin Li }
207*67e74705SXin Li }
208*67e74705SXin Li 
209*67e74705SXin Li // Register the checker that checks for direct accesses in all functions,
210*67e74705SXin Li // except for the initialization and copy routines.
registerDirectIvarAssignment(CheckerManager & mgr)211*67e74705SXin Li void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
212*67e74705SXin Li   mgr.registerChecker<DirectIvarAssignment>();
213*67e74705SXin Li }
214*67e74705SXin Li 
215*67e74705SXin Li // Register the checker that checks for direct accesses in functions annotated
216*67e74705SXin Li // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
AttrFilter(const ObjCMethodDecl * M)217*67e74705SXin Li static bool AttrFilter(const ObjCMethodDecl *M) {
218*67e74705SXin Li   for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
219*67e74705SXin Li     if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
220*67e74705SXin Li       return false;
221*67e74705SXin Li   return true;
222*67e74705SXin Li }
223*67e74705SXin Li 
registerDirectIvarAssignmentForAnnotatedFunctions(CheckerManager & mgr)224*67e74705SXin Li void ento::registerDirectIvarAssignmentForAnnotatedFunctions(
225*67e74705SXin Li     CheckerManager &mgr) {
226*67e74705SXin Li   mgr.registerChecker<DirectIvarAssignment>()->ShouldSkipMethod = &AttrFilter;
227*67e74705SXin Li }
228