xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/StaticAnalyzer/Checkers/DirectIvarAssignment.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //=- DirectIvarAssignment.cpp - Check rules on ObjC properties -*- C++ ----*-==//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg //  Check that Objective C properties are set with the setter, not though a
107330f729Sjoerg //      direct assignment.
117330f729Sjoerg //
127330f729Sjoerg //  Two versions of a checker exist: one that checks all methods and the other
137330f729Sjoerg //      that only checks the methods annotated with
147330f729Sjoerg //      __attribute__((annotate("objc_no_direct_instance_variable_assignment")))
157330f729Sjoerg //
167330f729Sjoerg //  The checker does not warn about assignments to Ivars, annotated with
177330f729Sjoerg //       __attribute__((objc_allow_direct_instance_variable_assignment"))). This
187330f729Sjoerg //      annotation serves as a false positive suppression mechanism for the
197330f729Sjoerg //      checker. The annotation is allowed on properties and Ivars.
207330f729Sjoerg //
217330f729Sjoerg //===----------------------------------------------------------------------===//
227330f729Sjoerg 
237330f729Sjoerg #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
247330f729Sjoerg #include "clang/AST/Attr.h"
257330f729Sjoerg #include "clang/AST/DeclObjC.h"
267330f729Sjoerg #include "clang/AST/StmtVisitor.h"
277330f729Sjoerg #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
287330f729Sjoerg #include "clang/StaticAnalyzer/Core/Checker.h"
297330f729Sjoerg #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
307330f729Sjoerg #include "llvm/ADT/DenseMap.h"
317330f729Sjoerg 
327330f729Sjoerg using namespace clang;
337330f729Sjoerg using namespace ento;
347330f729Sjoerg 
357330f729Sjoerg namespace {
367330f729Sjoerg 
377330f729Sjoerg /// The default method filter, which is used to filter out the methods on which
387330f729Sjoerg /// the check should not be performed.
397330f729Sjoerg ///
407330f729Sjoerg /// Checks for the init, dealloc, and any other functions that might be allowed
417330f729Sjoerg /// to perform direct instance variable assignment based on their name.
DefaultMethodFilter(const ObjCMethodDecl * M)427330f729Sjoerg static bool DefaultMethodFilter(const ObjCMethodDecl *M) {
437330f729Sjoerg   return M->getMethodFamily() == OMF_init ||
447330f729Sjoerg          M->getMethodFamily() == OMF_dealloc ||
457330f729Sjoerg          M->getMethodFamily() == OMF_copy ||
467330f729Sjoerg          M->getMethodFamily() == OMF_mutableCopy ||
477330f729Sjoerg          M->getSelector().getNameForSlot(0).find("init") != StringRef::npos ||
487330f729Sjoerg          M->getSelector().getNameForSlot(0).find("Init") != StringRef::npos;
497330f729Sjoerg }
507330f729Sjoerg 
517330f729Sjoerg class DirectIvarAssignment :
527330f729Sjoerg   public Checker<check::ASTDecl<ObjCImplementationDecl> > {
537330f729Sjoerg 
547330f729Sjoerg   typedef llvm::DenseMap<const ObjCIvarDecl*,
557330f729Sjoerg                          const ObjCPropertyDecl*> IvarToPropertyMapTy;
567330f729Sjoerg 
577330f729Sjoerg   /// A helper class, which walks the AST and locates all assignments to ivars
587330f729Sjoerg   /// in the given function.
597330f729Sjoerg   class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
607330f729Sjoerg     const IvarToPropertyMapTy &IvarToPropMap;
617330f729Sjoerg     const ObjCMethodDecl *MD;
627330f729Sjoerg     const ObjCInterfaceDecl *InterfD;
637330f729Sjoerg     BugReporter &BR;
647330f729Sjoerg     const CheckerBase *Checker;
657330f729Sjoerg     LocationOrAnalysisDeclContext DCtx;
667330f729Sjoerg 
677330f729Sjoerg   public:
MethodCrawler(const IvarToPropertyMapTy & InMap,const ObjCMethodDecl * InMD,const ObjCInterfaceDecl * InID,BugReporter & InBR,const CheckerBase * Checker,AnalysisDeclContext * InDCtx)687330f729Sjoerg     MethodCrawler(const IvarToPropertyMapTy &InMap, const ObjCMethodDecl *InMD,
697330f729Sjoerg                   const ObjCInterfaceDecl *InID, BugReporter &InBR,
707330f729Sjoerg                   const CheckerBase *Checker, AnalysisDeclContext *InDCtx)
717330f729Sjoerg         : IvarToPropMap(InMap), MD(InMD), InterfD(InID), BR(InBR),
727330f729Sjoerg           Checker(Checker), DCtx(InDCtx) {}
737330f729Sjoerg 
VisitStmt(const Stmt * S)747330f729Sjoerg     void VisitStmt(const Stmt *S) { VisitChildren(S); }
757330f729Sjoerg 
767330f729Sjoerg     void VisitBinaryOperator(const BinaryOperator *BO);
777330f729Sjoerg 
VisitChildren(const Stmt * S)787330f729Sjoerg     void VisitChildren(const Stmt *S) {
797330f729Sjoerg       for (const Stmt *Child : S->children())
807330f729Sjoerg         if (Child)
817330f729Sjoerg           this->Visit(Child);
827330f729Sjoerg     }
837330f729Sjoerg   };
847330f729Sjoerg 
857330f729Sjoerg public:
867330f729Sjoerg   bool (*ShouldSkipMethod)(const ObjCMethodDecl *);
877330f729Sjoerg 
DirectIvarAssignment()887330f729Sjoerg   DirectIvarAssignment() : ShouldSkipMethod(&DefaultMethodFilter) {}
897330f729Sjoerg 
907330f729Sjoerg   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
917330f729Sjoerg                     BugReporter &BR) const;
927330f729Sjoerg };
937330f729Sjoerg 
findPropertyBackingIvar(const ObjCPropertyDecl * PD,const ObjCInterfaceDecl * InterD,ASTContext & Ctx)947330f729Sjoerg static const ObjCIvarDecl *findPropertyBackingIvar(const ObjCPropertyDecl *PD,
957330f729Sjoerg                                                const ObjCInterfaceDecl *InterD,
967330f729Sjoerg                                                ASTContext &Ctx) {
977330f729Sjoerg   // Check for synthesized ivars.
987330f729Sjoerg   ObjCIvarDecl *ID = PD->getPropertyIvarDecl();
997330f729Sjoerg   if (ID)
1007330f729Sjoerg     return ID;
1017330f729Sjoerg 
1027330f729Sjoerg   ObjCInterfaceDecl *NonConstInterD = const_cast<ObjCInterfaceDecl*>(InterD);
1037330f729Sjoerg 
1047330f729Sjoerg   // Check for existing "_PropName".
1057330f729Sjoerg   ID = NonConstInterD->lookupInstanceVariable(PD->getDefaultSynthIvarName(Ctx));
1067330f729Sjoerg   if (ID)
1077330f729Sjoerg     return ID;
1087330f729Sjoerg 
1097330f729Sjoerg   // Check for existing "PropName".
1107330f729Sjoerg   IdentifierInfo *PropIdent = PD->getIdentifier();
1117330f729Sjoerg   ID = NonConstInterD->lookupInstanceVariable(PropIdent);
1127330f729Sjoerg 
1137330f729Sjoerg   return ID;
1147330f729Sjoerg }
1157330f729Sjoerg 
checkASTDecl(const ObjCImplementationDecl * D,AnalysisManager & Mgr,BugReporter & BR) const1167330f729Sjoerg void DirectIvarAssignment::checkASTDecl(const ObjCImplementationDecl *D,
1177330f729Sjoerg                                        AnalysisManager& Mgr,
1187330f729Sjoerg                                        BugReporter &BR) const {
1197330f729Sjoerg   const ObjCInterfaceDecl *InterD = D->getClassInterface();
1207330f729Sjoerg 
1217330f729Sjoerg 
1227330f729Sjoerg   IvarToPropertyMapTy IvarToPropMap;
1237330f729Sjoerg 
1247330f729Sjoerg   // Find all properties for this class.
1257330f729Sjoerg   for (const auto *PD : InterD->instance_properties()) {
1267330f729Sjoerg     // Find the corresponding IVar.
1277330f729Sjoerg     const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterD,
1287330f729Sjoerg                                                      Mgr.getASTContext());
1297330f729Sjoerg 
1307330f729Sjoerg     if (!ID)
1317330f729Sjoerg       continue;
1327330f729Sjoerg 
1337330f729Sjoerg     // Store the IVar to property mapping.
1347330f729Sjoerg     IvarToPropMap[ID] = PD;
1357330f729Sjoerg   }
1367330f729Sjoerg 
1377330f729Sjoerg   if (IvarToPropMap.empty())
1387330f729Sjoerg     return;
1397330f729Sjoerg 
1407330f729Sjoerg   for (const auto *M : D->instance_methods()) {
1417330f729Sjoerg     AnalysisDeclContext *DCtx = Mgr.getAnalysisDeclContext(M);
1427330f729Sjoerg 
1437330f729Sjoerg     if ((*ShouldSkipMethod)(M))
1447330f729Sjoerg       continue;
1457330f729Sjoerg 
1467330f729Sjoerg     const Stmt *Body = M->getBody();
147*e038c9c4Sjoerg     if (M->isSynthesizedAccessorStub())
148*e038c9c4Sjoerg       continue;
1497330f729Sjoerg     assert(Body);
1507330f729Sjoerg 
1517330f729Sjoerg     MethodCrawler MC(IvarToPropMap, M->getCanonicalDecl(), InterD, BR, this,
1527330f729Sjoerg                      DCtx);
1537330f729Sjoerg     MC.VisitStmt(Body);
1547330f729Sjoerg   }
1557330f729Sjoerg }
1567330f729Sjoerg 
isAnnotatedToAllowDirectAssignment(const Decl * D)1577330f729Sjoerg static bool isAnnotatedToAllowDirectAssignment(const Decl *D) {
1587330f729Sjoerg   for (const auto *Ann : D->specific_attrs<AnnotateAttr>())
1597330f729Sjoerg     if (Ann->getAnnotation() ==
1607330f729Sjoerg         "objc_allow_direct_instance_variable_assignment")
1617330f729Sjoerg       return true;
1627330f729Sjoerg   return false;
1637330f729Sjoerg }
1647330f729Sjoerg 
VisitBinaryOperator(const BinaryOperator * BO)1657330f729Sjoerg void DirectIvarAssignment::MethodCrawler::VisitBinaryOperator(
1667330f729Sjoerg                                                     const BinaryOperator *BO) {
1677330f729Sjoerg   if (!BO->isAssignmentOp())
1687330f729Sjoerg     return;
1697330f729Sjoerg 
1707330f729Sjoerg   const ObjCIvarRefExpr *IvarRef =
1717330f729Sjoerg           dyn_cast<ObjCIvarRefExpr>(BO->getLHS()->IgnoreParenCasts());
1727330f729Sjoerg 
1737330f729Sjoerg   if (!IvarRef)
1747330f729Sjoerg     return;
1757330f729Sjoerg 
1767330f729Sjoerg   if (const ObjCIvarDecl *D = IvarRef->getDecl()) {
1777330f729Sjoerg     IvarToPropertyMapTy::const_iterator I = IvarToPropMap.find(D);
1787330f729Sjoerg 
1797330f729Sjoerg     if (I != IvarToPropMap.end()) {
1807330f729Sjoerg       const ObjCPropertyDecl *PD = I->second;
1817330f729Sjoerg       // Skip warnings on Ivars, annotated with
1827330f729Sjoerg       // objc_allow_direct_instance_variable_assignment. This annotation serves
1837330f729Sjoerg       // as a false positive suppression mechanism for the checker. The
1847330f729Sjoerg       // annotation is allowed on properties and ivars.
1857330f729Sjoerg       if (isAnnotatedToAllowDirectAssignment(PD) ||
1867330f729Sjoerg           isAnnotatedToAllowDirectAssignment(D))
1877330f729Sjoerg         return;
1887330f729Sjoerg 
1897330f729Sjoerg       ObjCMethodDecl *GetterMethod =
1907330f729Sjoerg           InterfD->getInstanceMethod(PD->getGetterName());
1917330f729Sjoerg       ObjCMethodDecl *SetterMethod =
1927330f729Sjoerg           InterfD->getInstanceMethod(PD->getSetterName());
1937330f729Sjoerg 
1947330f729Sjoerg       if (SetterMethod && SetterMethod->getCanonicalDecl() == MD)
1957330f729Sjoerg         return;
1967330f729Sjoerg 
1977330f729Sjoerg       if (GetterMethod && GetterMethod->getCanonicalDecl() == MD)
1987330f729Sjoerg         return;
1997330f729Sjoerg 
2007330f729Sjoerg       BR.EmitBasicReport(
2017330f729Sjoerg           MD, Checker, "Property access", categories::CoreFoundationObjectiveC,
2027330f729Sjoerg           "Direct assignment to an instance variable backing a property; "
2037330f729Sjoerg           "use the setter instead",
2047330f729Sjoerg           PathDiagnosticLocation(IvarRef, BR.getSourceManager(), DCtx));
2057330f729Sjoerg     }
2067330f729Sjoerg   }
2077330f729Sjoerg }
2087330f729Sjoerg }
2097330f729Sjoerg 
2107330f729Sjoerg // Register the checker that checks for direct accesses in functions annotated
2117330f729Sjoerg // with __attribute__((annotate("objc_no_direct_instance_variable_assignment"))).
AttrFilter(const ObjCMethodDecl * M)2127330f729Sjoerg static bool AttrFilter(const ObjCMethodDecl *M) {
2137330f729Sjoerg   for (const auto *Ann : M->specific_attrs<AnnotateAttr>())
2147330f729Sjoerg     if (Ann->getAnnotation() == "objc_no_direct_instance_variable_assignment")
2157330f729Sjoerg       return false;
2167330f729Sjoerg   return true;
2177330f729Sjoerg }
2187330f729Sjoerg 
2197330f729Sjoerg // Register the checker that checks for direct accesses in all functions,
2207330f729Sjoerg // except for the initialization and copy routines.
registerDirectIvarAssignment(CheckerManager & mgr)2217330f729Sjoerg void ento::registerDirectIvarAssignment(CheckerManager &mgr) {
222*e038c9c4Sjoerg   auto Chk = mgr.registerChecker<DirectIvarAssignment>();
223*e038c9c4Sjoerg   if (mgr.getAnalyzerOptions().getCheckerBooleanOption(Chk,
224*e038c9c4Sjoerg                                                        "AnnotatedFunctions"))
225*e038c9c4Sjoerg     Chk->ShouldSkipMethod = &AttrFilter;
2267330f729Sjoerg }
2277330f729Sjoerg 
shouldRegisterDirectIvarAssignment(const CheckerManager & mgr)228*e038c9c4Sjoerg bool ento::shouldRegisterDirectIvarAssignment(const CheckerManager &mgr) {
2297330f729Sjoerg   return true;
2307330f729Sjoerg }
231