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