1 //===- ObjCAutoreleaseWriteChecker.cpp ----------------------------*- C++ -*-==//
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
7 //===----------------------------------------------------------------------===//
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
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];
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.
27 //===----------------------------------------------------------------------===//
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/BugReporter/CommonBugCategories.h"
34 #include "clang/StaticAnalyzer/Core/Checker.h"
35 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
36 #include "llvm/ADT/Twine.h"
38 using namespace clang;
40 using namespace ast_matchers;
44 const char *ProblematicWriteBind = "problematicwrite";
45 const char *CapturedBind = "capturedbind";
46 const char *ParamBind = "parambind";
47 const char *IsMethodBind = "ismethodbind";
48 const char *IsARPBind = "isautoreleasepoolbind";
50 class ObjCAutoreleaseWriteChecker : public Checker<check::ASTCodeBody> {
52 void checkASTCodeBody(const Decl *D,
54 BugReporter &BR) const;
56 std::vector<std::string> SelectorsWithAutoreleasingPool = {
57 // Common to NSArray, NSSet, NSOrderedSet
58 "enumerateObjectsUsingBlock:",
59 "enumerateObjectsWithOptions:usingBlock:",
61 // Common to NSArray and NSOrderedSet
62 "enumerateObjectsAtIndexes:options:usingBlock:",
63 "indexOfObjectAtIndexes:options:passingTest:",
64 "indexesOfObjectsAtIndexes:options:passingTest:",
65 "indexOfObjectPassingTest:",
66 "indexOfObjectWithOptions:passingTest:",
67 "indexesOfObjectsPassingTest:",
68 "indexesOfObjectsWithOptions:passingTest:",
71 "enumerateKeysAndObjectsUsingBlock:",
72 "enumerateKeysAndObjectsWithOptions:usingBlock:",
73 "keysOfEntriesPassingTest:",
74 "keysOfEntriesWithOptions:passingTest:",
77 "objectsPassingTest:",
78 "objectsWithOptions:passingTest:",
79 "enumerateIndexPathsWithOptions:usingBlock:",
82 "enumerateIndexesWithOptions:usingBlock:",
83 "enumerateIndexesUsingBlock:",
84 "enumerateIndexesInRange:options:usingBlock:",
85 "enumerateRangesUsingBlock:",
86 "enumerateRangesWithOptions:usingBlock:",
87 "enumerateRangesInRange:options:usingBlock:",
89 "indexesPassingTest:",
90 "indexWithOptions:passingTest:",
91 "indexesWithOptions:passingTest:",
92 "indexInRange:options:passingTest:",
93 "indexesInRange:options:passingTest:"
96 std::vector<std::string> FunctionsWithAutoreleasingPool = {
97 "dispatch_async", "dispatch_group_async", "dispatch_barrier_async"};
101 static inline std::vector<llvm::StringRef> toRefs(std::vector<std::string> V) {
102 return std::vector<llvm::StringRef>(V.begin(), V.end());
105 static decltype(auto) callsNames(std::vector<std::string> FunctionNames) {
106 return callee(functionDecl(hasAnyName(toRefs(FunctionNames))));
109 static void emitDiagnostics(BoundNodes &Match, const Decl *D, BugReporter &BR,
111 const ObjCAutoreleaseWriteChecker *Checker) {
112 AnalysisDeclContext *ADC = AM.getAnalysisDeclContext(D);
114 const auto *PVD = Match.getNodeAs<ParmVarDecl>(ParamBind);
115 QualType Ty = PVD->getType();
116 if (Ty->getPointeeType().getObjCLifetime() != Qualifiers::OCL_Autoreleasing)
118 const char *ActionMsg = "Write to";
119 const auto *MarkedStmt = Match.getNodeAs<Expr>(ProblematicWriteBind);
120 bool IsCapture = false;
122 // Prefer to warn on write, but if not available, warn on capture.
124 MarkedStmt = Match.getNodeAs<Expr>(CapturedBind);
126 ActionMsg = "Capture of";
130 SourceRange Range = MarkedStmt->getSourceRange();
131 PathDiagnosticLocation Location = PathDiagnosticLocation::createBegin(
132 MarkedStmt, BR.getSourceManager(), ADC);
134 bool IsMethod = Match.getNodeAs<ObjCMethodDecl>(IsMethodBind) != nullptr;
135 const char *FunctionDescription = IsMethod ? "method" : "function";
136 bool IsARP = Match.getNodeAs<ObjCAutoreleasePoolStmt>(IsARPBind) != nullptr;
138 llvm::SmallString<128> BugNameBuf;
139 llvm::raw_svector_ostream BugName(BugNameBuf);
141 << " autoreleasing out parameter inside autorelease pool";
143 llvm::SmallString<128> BugMessageBuf;
144 llvm::raw_svector_ostream BugMessage(BugMessageBuf);
145 BugMessage << ActionMsg << " autoreleasing out parameter ";
147 BugMessage << "'" + PVD->getName() + "' ";
149 BugMessage << "inside ";
151 BugMessage << "locally-scoped autorelease pool;";
153 BugMessage << "autorelease pool that may exit before "
154 << FunctionDescription << " returns;";
156 BugMessage << " consider writing first to a strong local variable"
157 " declared outside ";
159 BugMessage << "of the autorelease pool";
161 BugMessage << "of the block";
163 BR.EmitBasicReport(ADC->getDecl(), Checker, BugName.str(),
164 categories::MemoryRefCount, BugMessage.str(), Location,
168 void ObjCAutoreleaseWriteChecker::checkASTCodeBody(const Decl *D,
170 BugReporter &BR) const {
172 auto DoublePointerParamM =
173 parmVarDecl(hasType(hasCanonicalType(pointerType(
174 pointee(hasCanonicalType(objcObjectPointerType()))))))
177 auto ReferencedParamM =
178 declRefExpr(to(parmVarDecl(DoublePointerParamM))).bind(CapturedBind);
180 // Write into a binded object, e.g. *ParamBind = X.
181 auto WritesIntoM = binaryOperator(
182 hasLHS(unaryOperator(
183 hasOperatorName("*"),
185 ignoringParenImpCasts(ReferencedParamM))
188 ).bind(ProblematicWriteBind);
190 auto ArgumentCaptureM = hasAnyArgument(
191 ignoringParenImpCasts(ReferencedParamM));
192 auto CapturedInParamM = stmt(anyOf(
193 callExpr(ArgumentCaptureM),
194 objcMessageExpr(ArgumentCaptureM)));
196 // WritesIntoM happens inside a block passed as an argument.
197 auto WritesOrCapturesInBlockM = hasAnyArgument(allOf(
198 hasType(hasCanonicalType(blockPointerType())),
200 stmt(anyOf(WritesIntoM, CapturedInParamM))
203 auto BlockPassedToMarkedFuncM = stmt(anyOf(
205 callsNames(FunctionsWithAutoreleasingPool), WritesOrCapturesInBlockM)),
206 objcMessageExpr(allOf(
207 hasAnySelector(toRefs(SelectorsWithAutoreleasingPool)),
208 WritesOrCapturesInBlockM))
211 // WritesIntoM happens inside an explicit @autoreleasepool.
212 auto WritesOrCapturesInPoolM =
214 forEachDescendant(stmt(anyOf(WritesIntoM, CapturedInParamM))))
217 auto HasParamAndWritesInMarkedFuncM =
218 allOf(hasAnyParameter(DoublePointerParamM),
219 anyOf(forEachDescendant(BlockPassedToMarkedFuncM),
220 forEachDescendant(WritesOrCapturesInPoolM)));
222 auto MatcherM = decl(anyOf(
223 objcMethodDecl(HasParamAndWritesInMarkedFuncM).bind(IsMethodBind),
224 functionDecl(HasParamAndWritesInMarkedFuncM),
225 blockDecl(HasParamAndWritesInMarkedFuncM)));
227 auto Matches = match(MatcherM, *D, AM.getASTContext());
228 for (BoundNodes Match : Matches)
229 emitDiagnostics(Match, D, BR, AM, this);
232 void ento::registerAutoreleaseWriteChecker(CheckerManager &Mgr) {
233 Mgr.registerChecker<ObjCAutoreleaseWriteChecker>();
236 bool ento::shouldRegisterAutoreleaseWriteChecker(const CheckerManager &mgr) {