1 //===- ObjCAutoreleaseWriteChecker.cpp ----------------------------*- C++ -*-==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines ObjCAutoreleaseWriteChecker which warns against writes
10 // into autoreleased out parameters which cause crashes.
11 // An example of a problematic write is a write to {@code error} in the example
12 // below:
13 //
14 // - (BOOL) mymethod:(NSError *__autoreleasing *)error list:(NSArray*) list {
15 //     [list enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
16 //       NSString *myString = obj;
17 //       if ([myString isEqualToString:@"error"] && error)
18 //         *error = [NSError errorWithDomain:@"MyDomain" code:-1];
19 //     }];
20 //     return false;
21 // }
22 //
23 // Such code will crash on read from `*error` due to the autorelease pool
24 // in `enumerateObjectsUsingBlock` implementation freeing the error object
25 // on exit from the function.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
30 #include "clang/ASTMatchers/ASTMatchFinder.h"
31 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
32 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
33 #include "clang/StaticAnalyzer/Core/Checker.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
35 #include "llvm/ADT/Twine.h"
36 
37 using namespace clang;
38 using namespace ento;
39 using namespace ast_matchers;
40 
41 namespace {
42 
43 const char *ProblematicWriteBind = "problematicwrite";
44 const char *CapturedBind = "capturedbind";
45 const char *ParamBind = "parambind";
46 const char *IsMethodBind = "ismethodbind";
47 
48 class ObjCAutoreleaseWriteChecker : public Checker<check::ASTCodeBody> {
49 public:
50   void checkASTCodeBody(const Decl *D,
51                         AnalysisManager &AM,
52                         BugReporter &BR) const;
53 private:
54   std::vector<std::string> SelectorsWithAutoreleasingPool = {
55       // Common to NSArray,  NSSet, NSOrderedSet
56       "enumerateObjectsUsingBlock:",
57       "enumerateObjectsWithOptions:usingBlock:",
58 
59       // Common to NSArray and NSOrderedSet
60       "enumerateObjectsAtIndexes:options:usingBlock:",
61       "indexOfObjectAtIndexes:options:passingTest:",
62       "indexesOfObjectsAtIndexes:options:passingTest:",
63       "indexOfObjectPassingTest:",
64       "indexOfObjectWithOptions:passingTest:",
65       "indexesOfObjectsPassingTest:",
66       "indexesOfObjectsWithOptions:passingTest:",
67 
68       // NSDictionary
69       "enumerateKeysAndObjectsUsingBlock:",
70       "enumerateKeysAndObjectsWithOptions:usingBlock:",
71       "keysOfEntriesPassingTest:",
72       "keysOfEntriesWithOptions:passingTest:",
73 
74       // NSSet
75       "objectsPassingTest:",
76       "objectsWithOptions:passingTest:",
77       "enumerateIndexPathsWithOptions:usingBlock:",
78 
79       // NSIndexSet
80       "enumerateIndexesWithOptions:usingBlock:",
81       "enumerateIndexesUsingBlock:",
82       "enumerateIndexesInRange:options:usingBlock:",
83       "enumerateRangesUsingBlock:",
84       "enumerateRangesWithOptions:usingBlock:",
85       "enumerateRangesInRange:options:usingBlock:",
86       "indexPassingTest:",
87       "indexesPassingTest:",
88       "indexWithOptions:passingTest:",
89       "indexesWithOptions:passingTest:",
90       "indexInRange:options:passingTest:",
91       "indexesInRange:options:passingTest:"
92   };
93 
94   std::vector<std::string> FunctionsWithAutoreleasingPool = {
95       "dispatch_async", "dispatch_group_async", "dispatch_barrier_async"};
96 };
97 }
98 
99 static inline std::vector<llvm::StringRef> toRefs(std::vector<std::string> V) {
100   return std::vector<llvm::StringRef>(V.begin(), V.end());
101 }
102 
103 static decltype(auto) callsNames(std::vector<std::string> FunctionNames) {
104   return callee(functionDecl(hasAnyName(toRefs(FunctionNames))));
105 }
106 
107 static void emitDiagnostics(BoundNodes &Match, const Decl *D, BugReporter &BR,
108                             AnalysisManager &AM,
109                             const ObjCAutoreleaseWriteChecker *Checker) {
110   AnalysisDeclContext *ADC = AM.getAnalysisDeclContext(D);
111 
112   const auto *PVD = Match.getNodeAs<ParmVarDecl>(ParamBind);
113   QualType Ty = PVD->getType();
114   if (Ty->getPointeeType().getObjCLifetime() != Qualifiers::OCL_Autoreleasing)
115     return;
116   const char *ActionMsg = "Write to";
117   const auto *MarkedStmt = Match.getNodeAs<Expr>(ProblematicWriteBind);
118   bool IsCapture = false;
119 
120   // Prefer to warn on write, but if not available, warn on capture.
121   if (!MarkedStmt) {
122     MarkedStmt = Match.getNodeAs<Expr>(CapturedBind);
123     assert(MarkedStmt);
124     ActionMsg = "Capture of";
125     IsCapture = true;
126   }
127 
128   SourceRange Range = MarkedStmt->getSourceRange();
129   PathDiagnosticLocation Location = PathDiagnosticLocation::createBegin(
130       MarkedStmt, BR.getSourceManager(), ADC);
131   bool IsMethod = Match.getNodeAs<ObjCMethodDecl>(IsMethodBind) != nullptr;
132   const char *Name = IsMethod ? "method" : "function";
133 
134   BR.EmitBasicReport(
135       ADC->getDecl(), Checker,
136       /*Name=*/(llvm::Twine(ActionMsg)
137                 + " autoreleasing out parameter inside autorelease pool").str(),
138       /*BugCategory=*/"Memory",
139       (llvm::Twine(ActionMsg) + " autoreleasing out parameter " +
140        (IsCapture ? "'" + PVD->getName() + "'" + " " : "") + "inside " +
141        "autorelease pool that may exit before " + Name + " returns; consider "
142        "writing first to a strong local variable declared outside of the block")
143           .str(),
144       Location,
145       Range);
146 }
147 
148 void ObjCAutoreleaseWriteChecker::checkASTCodeBody(const Decl *D,
149                                                   AnalysisManager &AM,
150                                                   BugReporter &BR) const {
151 
152   auto DoublePointerParamM =
153       parmVarDecl(hasType(hasCanonicalType(pointerType(
154                       pointee(hasCanonicalType(objcObjectPointerType()))))))
155           .bind(ParamBind);
156 
157   auto ReferencedParamM =
158       declRefExpr(to(parmVarDecl(DoublePointerParamM))).bind(CapturedBind);
159 
160   // Write into a binded object, e.g. *ParamBind = X.
161   auto WritesIntoM = binaryOperator(
162     hasLHS(unaryOperator(
163         hasOperatorName("*"),
164         hasUnaryOperand(
165           ignoringParenImpCasts(ReferencedParamM))
166     )),
167     hasOperatorName("=")
168   ).bind(ProblematicWriteBind);
169 
170   auto ArgumentCaptureM = hasAnyArgument(
171     ignoringParenImpCasts(ReferencedParamM));
172   auto CapturedInParamM = stmt(anyOf(
173       callExpr(ArgumentCaptureM),
174       objcMessageExpr(ArgumentCaptureM)));
175 
176   // WritesIntoM happens inside a block passed as an argument.
177   auto WritesOrCapturesInBlockM = hasAnyArgument(allOf(
178       hasType(hasCanonicalType(blockPointerType())),
179       forEachDescendant(
180         stmt(anyOf(WritesIntoM, CapturedInParamM))
181       )));
182 
183   auto BlockPassedToMarkedFuncM = stmt(anyOf(
184     callExpr(allOf(
185       callsNames(FunctionsWithAutoreleasingPool), WritesOrCapturesInBlockM)),
186     objcMessageExpr(allOf(
187        hasAnySelector(toRefs(SelectorsWithAutoreleasingPool)),
188        WritesOrCapturesInBlockM))
189   ));
190 
191   auto HasParamAndWritesInMarkedFuncM = allOf(
192       hasAnyParameter(DoublePointerParamM),
193       forEachDescendant(BlockPassedToMarkedFuncM));
194 
195   auto MatcherM = decl(anyOf(
196       objcMethodDecl(HasParamAndWritesInMarkedFuncM).bind(IsMethodBind),
197       functionDecl(HasParamAndWritesInMarkedFuncM),
198       blockDecl(HasParamAndWritesInMarkedFuncM)));
199 
200   auto Matches = match(MatcherM, *D, AM.getASTContext());
201   for (BoundNodes Match : Matches)
202     emitDiagnostics(Match, D, BR, AM, this);
203 }
204 
205 void ento::registerAutoreleaseWriteChecker(CheckerManager &Mgr) {
206   Mgr.registerChecker<ObjCAutoreleaseWriteChecker>();
207 }
208 
209 bool ento::shouldRegisterAutoreleaseWriteChecker(const LangOptions &LO) {
210   return true;
211 }
212