blob: 294f3617d717665ec92a270935d9469cced46bc3 [file] [log] [blame]
Anna Zaks08be9b92011-08-04 17:28:06 +00001//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
Anna Zaks15f496c2011-08-01 22:40:01 +00002//
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// This checker flags misuses of KeyChainAPI. In particular, the password data
10// allocated/returned by SecKeychainItemCopyContent,
11// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
12// to be freed using a call to SecKeychainItemFreeContent.
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaks15f496c2011-08-01 22:40:01 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
18#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek001fd5b2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000023#include "llvm/Support/raw_ostream.h"
Anna Zaks15f496c2011-08-01 22:40:01 +000024
25using namespace clang;
26using namespace ento;
27
28namespace {
29class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
Anna Zaks15f496c2011-08-01 22:40:01 +000030 check::PostStmt<CallExpr>,
Anna Zaksfdd0aca2011-08-12 21:56:43 +000031 check::DeadSymbols> {
Ahmed Charlesb8984322014-03-07 20:03:18 +000032 mutable std::unique_ptr<BugType> BT;
Anna Zaks388c18e2011-08-04 00:26:57 +000033
Anna Zaks15f496c2011-08-01 22:40:01 +000034public:
Anna Zaksc94894f2011-08-12 21:14:26 +000035 /// AllocationState is a part of the checker specific state together with the
36 /// MemRegion corresponding to the allocated data.
37 struct AllocationState {
Anna Zaksc94894f2011-08-12 21:14:26 +000038 /// The index of the allocator function.
39 unsigned int AllocatorIdx;
Anna Zaks5be8a4d2011-08-25 00:59:06 +000040 SymbolRef Region;
Anna Zaksc94894f2011-08-12 21:14:26 +000041
42 AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
Anna Zaksc94894f2011-08-12 21:14:26 +000043 AllocatorIdx(Idx),
Anna Zaks5be8a4d2011-08-25 00:59:06 +000044 Region(R) {}
Anna Zaksc94894f2011-08-12 21:14:26 +000045
46 bool operator==(const AllocationState &X) const {
Anna Zaks5be8a4d2011-08-25 00:59:06 +000047 return (AllocatorIdx == X.AllocatorIdx &&
48 Region == X.Region);
Anna Zaksc94894f2011-08-12 21:14:26 +000049 }
Anna Zaks5be8a4d2011-08-25 00:59:06 +000050
Anna Zaksc94894f2011-08-12 21:14:26 +000051 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaksc94894f2011-08-12 21:14:26 +000052 ID.AddInteger(AllocatorIdx);
Anna Zaks5be8a4d2011-08-25 00:59:06 +000053 ID.AddPointer(Region);
Anna Zaksc94894f2011-08-12 21:14:26 +000054 }
55 };
56
Anna Zaks15f496c2011-08-01 22:40:01 +000057 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaks15f496c2011-08-01 22:40:01 +000058 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksfdd0aca2011-08-12 21:56:43 +000059 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaks15f496c2011-08-01 22:40:01 +000060
61private:
Anna Zaksf880cff2011-08-24 21:58:55 +000062 typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000063 typedef SmallVector<AllocationPair, 2> AllocationPairVec;
Anna Zaksbe460892011-08-24 20:52:46 +000064
65 enum APIKind {
Anna Zaks0897a232011-08-24 00:06:27 +000066 /// Denotes functions tracked by this checker.
67 ValidAPI = 0,
68 /// The functions commonly/mistakenly used in place of the given API.
69 ErrorAPI = 1,
70 /// The functions which may allocate the data. These are tracked to reduce
71 /// the false alarm rate.
72 PossibleAPI = 2
73 };
Anna Zaks08be9b92011-08-04 17:28:06 +000074 /// Stores the information about the allocator and deallocator functions -
75 /// these are the functions the checker is tracking.
76 struct ADFunctionInfo {
77 const char* Name;
78 unsigned int Param;
79 unsigned int DeallocatorIdx;
Anna Zaks0897a232011-08-24 00:06:27 +000080 APIKind Kind;
Anna Zaks08be9b92011-08-04 17:28:06 +000081 };
82 static const unsigned InvalidIdx = 100000;
Anna Zaks0897a232011-08-24 00:06:27 +000083 static const unsigned FunctionsToTrackSize = 8;
Anna Zaks08be9b92011-08-04 17:28:06 +000084 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks177ecfa2011-08-05 23:52:45 +000085 /// The value, which represents no error return value for allocator functions.
86 static const unsigned NoErr = 0;
Anna Zaks15f496c2011-08-01 22:40:01 +000087
Anna Zaks08be9b92011-08-04 17:28:06 +000088 /// Given the function name, returns the index of the allocator/deallocator
89 /// function.
Anna Zaksbe460892011-08-24 20:52:46 +000090 static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
Anna Zaks388c18e2011-08-04 00:26:57 +000091
92 inline void initBugType() const {
93 if (!BT)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +000094 BT.reset(new BugType(this, "Improper use of SecKeychain API",
Anna Zaks8ef07e52013-04-03 19:28:22 +000095 "API Misuse (Apple)"));
Anna Zaks388c18e2011-08-04 00:26:57 +000096 }
Anna Zaksfdd0aca2011-08-12 21:56:43 +000097
Anna Zaks85913db2011-08-25 00:32:42 +000098 void generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksbb167012011-08-23 23:47:36 +000099 const Expr *ArgExpr,
Anna Zaks85913db2011-08-25 00:32:42 +0000100 CheckerContext &C) const;
Anna Zaksbb167012011-08-23 23:47:36 +0000101
Anna Zaks4b062cb2012-02-23 22:53:29 +0000102 /// Find the allocation site for Sym on the path leading to the node N.
Anna Zaksa043d0c2013-01-08 00:25:29 +0000103 const ExplodedNode *getAllocationNode(const ExplodedNode *N, SymbolRef Sym,
104 CheckerContext &C) const;
Anna Zaks4b062cb2012-02-23 22:53:29 +0000105
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000106 std::unique_ptr<BugReport> generateAllocatedDataNotReleasedReport(
107 const AllocationPair &AP, ExplodedNode *N, CheckerContext &C) const;
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000108
109 /// Check if RetSym evaluates to an error value in the current state.
110 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000111 ProgramStateRef State,
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000112 SValBuilder &Builder,
113 bool noError = false) const;
114
115 /// Check if RetSym evaluates to a NoErr value in the current state.
116 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000117 ProgramStateRef State,
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000118 SValBuilder &Builder) const {
119 return definitelyReturnedError(RetSym, State, Builder, true);
120 }
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000121
Ted Kremenek1e809b42012-03-09 01:13:14 +0000122 /// Mark an AllocationPair interesting for diagnostic reporting.
123 void markInteresting(BugReport *R, const AllocationPair &AP) const {
124 R->markInteresting(AP.first);
125 R->markInteresting(AP.second->Region);
126 }
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000127
Anna Zaksbe460892011-08-24 20:52:46 +0000128 /// The bug visitor which allows us to print extra diagnostics along the
129 /// BugReport path. For example, showing the allocation site of the leaked
130 /// region.
Jordy Rosef78877e2012-03-24 02:45:35 +0000131 class SecKeychainBugVisitor
132 : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
Anna Zaksbe460892011-08-24 20:52:46 +0000133 protected:
134 // The allocated region symbol tracked by the main analysis.
135 SymbolRef Sym;
136
137 public:
138 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
Anna Zaksbe460892011-08-24 20:52:46 +0000139
Craig Topperfb6b25b2014-03-15 04:29:04 +0000140 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaksbe460892011-08-24 20:52:46 +0000141 static int X = 0;
142 ID.AddPointer(&X);
143 ID.AddPointer(Sym);
144 }
145
146 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
147 const ExplodedNode *PrevN,
148 BugReporterContext &BRC,
Craig Topperfb6b25b2014-03-15 04:29:04 +0000149 BugReport &BR) override;
Anna Zaksbe460892011-08-24 20:52:46 +0000150 };
Anna Zaks15f496c2011-08-01 22:40:01 +0000151};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000152}
Anna Zaks15f496c2011-08-01 22:40:01 +0000153
Anna Zaks5443a642011-08-15 23:23:15 +0000154/// ProgramState traits to store the currently allocated (and not yet freed)
155/// symbols. This is a map from the allocated content symbol to the
156/// corresponding AllocationState.
Jordan Rose0c153cb2012-11-02 01:54:06 +0000157REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
158 SymbolRef,
159 MacOSKeychainAPIChecker::AllocationState)
Anna Zaks15f496c2011-08-01 22:40:01 +0000160
Anna Zaks388c18e2011-08-04 00:26:57 +0000161static bool isEnclosingFunctionParam(const Expr *E) {
162 E = E->IgnoreParenCasts();
163 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
164 const ValueDecl *VD = DRE->getDecl();
165 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
166 return true;
167 }
168 return false;
169}
170
Anna Zaks08be9b92011-08-04 17:28:06 +0000171const MacOSKeychainAPIChecker::ADFunctionInfo
172 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks0897a232011-08-24 00:06:27 +0000173 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
174 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
175 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
176 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
177 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
178 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
179 {"free", 0, InvalidIdx, ErrorAPI}, // 6
180 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks08be9b92011-08-04 17:28:06 +0000181};
182
183unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaksbe460892011-08-24 20:52:46 +0000184 bool IsAllocator) {
Anna Zaks08be9b92011-08-04 17:28:06 +0000185 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
186 ADFunctionInfo FI = FunctionsToTrack[I];
187 if (FI.Name != Name)
188 continue;
189 // Make sure the function is of the right type (allocator vs deallocator).
190 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
191 return InvalidIdx;
192 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
193 return InvalidIdx;
194
195 return I;
196 }
197 // The function is not tracked.
198 return InvalidIdx;
199}
200
Anna Zaksc94894f2011-08-12 21:14:26 +0000201static bool isBadDeallocationArgument(const MemRegion *Arg) {
Jordy Rosef80b2cc2012-03-11 00:08:24 +0000202 if (!Arg)
203 return false;
Anna Zaksc94894f2011-08-12 21:14:26 +0000204 if (isa<AllocaRegion>(Arg) ||
205 isa<BlockDataRegion>(Arg) ||
206 isa<TypedRegion>(Arg)) {
207 return true;
208 }
209 return false;
210}
Jordy Rosef80b2cc2012-03-11 00:08:24 +0000211
Anna Zaksc52bed12011-08-05 00:37:00 +0000212/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaksc94894f2011-08-12 21:14:26 +0000213/// that value is itself an address, and return the corresponding symbol.
214static SymbolRef getAsPointeeSymbol(const Expr *Expr,
215 CheckerContext &C) {
Ted Kremenek49b1e382012-01-26 21:29:00 +0000216 ProgramStateRef State = C.getState();
Ted Kremenek632e3b72012-01-06 22:09:28 +0000217 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks177ecfa2011-08-05 23:52:45 +0000218
David Blaikie05785d12013-02-20 22:23:23 +0000219 if (Optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) {
Anna Zaksc52bed12011-08-05 00:37:00 +0000220 StoreManager& SM = C.getStoreManager();
Jordy Rosef80b2cc2012-03-11 00:08:24 +0000221 SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
222 if (sym)
223 return sym;
Anna Zaksc52bed12011-08-05 00:37:00 +0000224 }
Craig Topper0dbb7832014-05-27 02:45:47 +0000225 return nullptr;
Anna Zaksc52bed12011-08-05 00:37:00 +0000226}
227
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000228// When checking for error code, we need to consider the following cases:
229// 1) noErr / [0]
230// 2) someErr / [1, inf]
231// 3) unknown
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000232// If noError, returns true iff (1).
233// If !noError, returns true iff (2).
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000234bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek49b1e382012-01-26 21:29:00 +0000235 ProgramStateRef State,
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000236 SValBuilder &Builder,
237 bool noError) const {
238 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
239 Builder.getSymbolManager().getType(RetSym));
240 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
241 nonloc::SymbolVal(RetSym));
Ted Kremenek49b1e382012-01-26 21:29:00 +0000242 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000243 if (ErrState == State) {
244 return true;
245 }
246
247 return false;
248}
249
Anna Zaksbb167012011-08-23 23:47:36 +0000250// Report deallocator mismatch. Remove the region from tracking - reporting a
251// missing free error after this one is redundant.
252void MacOSKeychainAPIChecker::
Anna Zaks85913db2011-08-25 00:32:42 +0000253 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksbb167012011-08-23 23:47:36 +0000254 const Expr *ArgExpr,
Anna Zaks85913db2011-08-25 00:32:42 +0000255 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +0000256 ProgramStateRef State = C.getState();
Anna Zaks85913db2011-08-25 00:32:42 +0000257 State = State->remove<AllocatedData>(AP.first);
Devin Coughline39bd402015-09-16 22:03:05 +0000258 ExplodedNode *N = C.generateNonFatalErrorNode(State);
Anna Zaksbb167012011-08-23 23:47:36 +0000259
260 if (!N)
261 return;
262 initBugType();
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000263 SmallString<80> sbuf;
Anna Zaksbb167012011-08-23 23:47:36 +0000264 llvm::raw_svector_ostream os(sbuf);
Anna Zaks85913db2011-08-25 00:32:42 +0000265 unsigned int PDeallocIdx =
266 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksbb167012011-08-23 23:47:36 +0000267
268 os << "Deallocator doesn't match the allocator: '"
269 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000270 auto Report = llvm::make_unique<BugReport>(*BT, os.str(), N);
David Blaikie91e79022014-09-04 23:54:33 +0000271 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
Anna Zaksbb167012011-08-23 23:47:36 +0000272 Report->addRange(ArgExpr->getSourceRange());
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000273 markInteresting(Report.get(), AP);
274 C.emitReport(std::move(Report));
Anna Zaksbb167012011-08-23 23:47:36 +0000275}
276
Anna Zaks15f496c2011-08-01 22:40:01 +0000277void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
278 CheckerContext &C) const {
Anna Zaksc52bed12011-08-05 00:37:00 +0000279 unsigned idx = InvalidIdx;
Ted Kremenek49b1e382012-01-26 21:29:00 +0000280 ProgramStateRef State = C.getState();
Anna Zaks15f496c2011-08-01 22:40:01 +0000281
Jordan Rose6cd16c52012-07-10 23:13:01 +0000282 const FunctionDecl *FD = C.getCalleeDecl(CE);
283 if (!FD || FD->getKind() != Decl::Function)
284 return;
Ted Kremenek3a0678e2015-09-08 03:50:52 +0000285
Jordan Rose6cd16c52012-07-10 23:13:01 +0000286 StringRef funName = C.getCalleeName(FD);
Anna Zaksc6aa5312011-12-01 05:57:37 +0000287 if (funName.empty())
Anna Zaks15f496c2011-08-01 22:40:01 +0000288 return;
Anna Zaks15f496c2011-08-01 22:40:01 +0000289
Anna Zaksc52bed12011-08-05 00:37:00 +0000290 // If it is a call to an allocator function, it could be a double allocation.
291 idx = getTrackedFunctionIndex(funName, true);
292 if (idx != InvalidIdx) {
Anna Zaks33f06322015-02-05 01:02:56 +0000293 unsigned paramIdx = FunctionsToTrack[idx].Param;
294 if (CE->getNumArgs() <= paramIdx)
295 return;
296
297 const Expr *ArgExpr = CE->getArg(paramIdx);
Anna Zaksc94894f2011-08-12 21:14:26 +0000298 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksc52bed12011-08-05 00:37:00 +0000299 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zaks5be8a4d2011-08-25 00:59:06 +0000300 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks01ae1e12011-08-16 16:30:24 +0000301 // Remove the value from the state. The new symbol will be added for
302 // tracking when the second allocator is processed in checkPostStmt().
303 State = State->remove<AllocatedData>(V);
Devin Coughline39bd402015-09-16 22:03:05 +0000304 ExplodedNode *N = C.generateNonFatalErrorNode(State);
Anna Zaks01ae1e12011-08-16 16:30:24 +0000305 if (!N)
306 return;
307 initBugType();
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000308 SmallString<128> sbuf;
Anna Zaks01ae1e12011-08-16 16:30:24 +0000309 llvm::raw_svector_ostream os(sbuf);
310 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
311 os << "Allocated data should be released before another call to "
312 << "the allocator: missing a call to '"
313 << FunctionsToTrack[DIdx].Name
314 << "'.";
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000315 auto Report = llvm::make_unique<BugReport>(*BT, os.str(), N);
David Blaikie91e79022014-09-04 23:54:33 +0000316 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(V));
Anna Zaks01ae1e12011-08-16 16:30:24 +0000317 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek1e809b42012-03-09 01:13:14 +0000318 Report->markInteresting(AS->Region);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000319 C.emitReport(std::move(Report));
Anna Zaks01ae1e12011-08-16 16:30:24 +0000320 }
Anna Zaksc52bed12011-08-05 00:37:00 +0000321 }
322 return;
323 }
324
325 // Is it a call to one of deallocator functions?
326 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks08be9b92011-08-04 17:28:06 +0000327 if (idx == InvalidIdx)
Anna Zaks4aa34a532011-08-04 00:31:38 +0000328 return;
329
Anna Zaks33f06322015-02-05 01:02:56 +0000330 unsigned paramIdx = FunctionsToTrack[idx].Param;
331 if (CE->getNumArgs() <= paramIdx)
332 return;
333
Anna Zaksc94894f2011-08-12 21:14:26 +0000334 // Check the argument to the deallocator.
Anna Zaks33f06322015-02-05 01:02:56 +0000335 const Expr *ArgExpr = CE->getArg(paramIdx);
Ted Kremenek632e3b72012-01-06 22:09:28 +0000336 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaksc94894f2011-08-12 21:14:26 +0000337
338 // Undef is reported by another checker.
339 if (ArgSVal.isUndef())
340 return;
341
Jordy Rosef80b2cc2012-03-11 00:08:24 +0000342 SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
Anna Zaksc94894f2011-08-12 21:14:26 +0000343
Anna Zaksc94894f2011-08-12 21:14:26 +0000344 // If the argument is coming from the heap, globals, or unknown, do not
345 // report it.
Jordy Rosef80b2cc2012-03-11 00:08:24 +0000346 bool RegionArgIsBad = false;
347 if (!ArgSM) {
348 if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
349 return;
350 RegionArgIsBad = true;
351 }
Anna Zaks4aa34a532011-08-04 00:31:38 +0000352
Anna Zaks0897a232011-08-24 00:06:27 +0000353 // Is the argument to the call being tracked?
354 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
355 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
356 return;
357 }
Anna Zaks29f9b7a2011-08-15 18:42:00 +0000358 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks5443a642011-08-15 23:23:15 +0000359 // TODO: We might want a more precise diagnostic for double free
360 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks0897a232011-08-24 00:06:27 +0000361 if (!AS || RegionArgIsBad) {
Anna Zaks4aa34a532011-08-04 00:31:38 +0000362 // It is possible that this is a false positive - the argument might
363 // have entered as an enclosing function parameter.
364 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaks15f496c2011-08-01 22:40:01 +0000365 return;
Anna Zaks388c18e2011-08-04 00:26:57 +0000366
Devin Coughline39bd402015-09-16 22:03:05 +0000367 ExplodedNode *N = C.generateNonFatalErrorNode(State);
Anna Zaks4aa34a532011-08-04 00:31:38 +0000368 if (!N)
369 return;
370 initBugType();
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000371 auto Report = llvm::make_unique<BugReport>(
372 *BT, "Trying to free data which has not been allocated.", N);
Anna Zaks4aa34a532011-08-04 00:31:38 +0000373 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek1e809b42012-03-09 01:13:14 +0000374 if (AS)
375 Report->markInteresting(AS->Region);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000376 C.emitReport(std::move(Report));
Anna Zaks08be9b92011-08-04 17:28:06 +0000377 return;
Anna Zaks15f496c2011-08-01 22:40:01 +0000378 }
Anna Zaks4aa34a532011-08-04 00:31:38 +0000379
Anna Zaks0897a232011-08-24 00:06:27 +0000380 // Process functions which might deallocate.
381 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
382
383 if (funName == "CFStringCreateWithBytesNoCopy") {
384 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
385 // NULL ~ default deallocator, so warn.
386 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
387 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks85913db2011-08-25 00:32:42 +0000388 const AllocationPair AP = std::make_pair(ArgSM, AS);
389 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks0897a232011-08-24 00:06:27 +0000390 return;
391 }
392 // One of the default allocators, so warn.
393 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
394 StringRef DeallocatorName = DE->getFoundDecl()->getName();
395 if (DeallocatorName == "kCFAllocatorDefault" ||
396 DeallocatorName == "kCFAllocatorSystemDefault" ||
397 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks85913db2011-08-25 00:32:42 +0000398 const AllocationPair AP = std::make_pair(ArgSM, AS);
399 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks0897a232011-08-24 00:06:27 +0000400 return;
401 }
402 // If kCFAllocatorNull, which does not deallocate, we still have to
Anna Zaks030e65d2013-01-07 19:13:00 +0000403 // find the deallocator.
404 if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
Anna Zaks0897a232011-08-24 00:06:27 +0000405 return;
Anna Zaks0897a232011-08-24 00:06:27 +0000406 }
Anna Zaks030e65d2013-01-07 19:13:00 +0000407 // In all other cases, assume the user supplied a correct deallocator
408 // that will free memory so stop tracking.
409 State = State->remove<AllocatedData>(ArgSM);
410 C.addTransition(State);
411 return;
Anna Zaks0897a232011-08-24 00:06:27 +0000412 }
Anna Zaks030e65d2013-01-07 19:13:00 +0000413
414 llvm_unreachable("We know of no other possible APIs.");
Anna Zaks0897a232011-08-24 00:06:27 +0000415 }
416
Anna Zaks5443a642011-08-15 23:23:15 +0000417 // The call is deallocating a value we previously allocated, so remove it
418 // from the next state.
419 State = State->remove<AllocatedData>(ArgSM);
420
Anna Zaksbb167012011-08-23 23:47:36 +0000421 // Check if the proper deallocator is used.
Anna Zaksc6861772011-08-04 21:53:01 +0000422 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks0897a232011-08-24 00:06:27 +0000423 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks85913db2011-08-25 00:32:42 +0000424 const AllocationPair AP = std::make_pair(ArgSM, AS);
425 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaksc6861772011-08-04 21:53:01 +0000426 return;
427 }
428
Anna Zaks719051e2011-12-01 16:41:58 +0000429 // If the buffer can be null and the return status can be an error,
430 // report a bad call to free.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000431 if (State->assume(ArgSVal.castAs<DefinedSVal>(), false) &&
Anna Zaks719051e2011-12-01 16:41:58 +0000432 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Devin Coughline39bd402015-09-16 22:03:05 +0000433 ExplodedNode *N = C.generateNonFatalErrorNode(State);
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000434 if (!N)
435 return;
436 initBugType();
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000437 auto Report = llvm::make_unique<BugReport>(
438 *BT, "Only call free if a valid (non-NULL) buffer was returned.", N);
David Blaikie91e79022014-09-04 23:54:33 +0000439 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(ArgSM));
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000440 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek1e809b42012-03-09 01:13:14 +0000441 Report->markInteresting(AS->Region);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000442 C.emitReport(std::move(Report));
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000443 return;
444 }
445
Anna Zaksda4c8d62011-10-26 21:06:34 +0000446 C.addTransition(State);
Anna Zaks15f496c2011-08-01 22:40:01 +0000447}
448
449void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
450 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +0000451 ProgramStateRef State = C.getState();
Jordan Rose6cd16c52012-07-10 23:13:01 +0000452 const FunctionDecl *FD = C.getCalleeDecl(CE);
453 if (!FD || FD->getKind() != Decl::Function)
454 return;
455
456 StringRef funName = C.getCalleeName(FD);
Anna Zaks15f496c2011-08-01 22:40:01 +0000457
458 // If a value has been allocated, add it to the set for tracking.
Anna Zaks08be9b92011-08-04 17:28:06 +0000459 unsigned idx = getTrackedFunctionIndex(funName, true);
460 if (idx == InvalidIdx)
Anna Zaks4aa34a532011-08-04 00:31:38 +0000461 return;
Anna Zaks388c18e2011-08-04 00:26:57 +0000462
Anna Zaks08be9b92011-08-04 17:28:06 +0000463 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks59d741f2011-08-12 22:47:22 +0000464 // If the argument entered as an enclosing function parameter, skip it to
465 // avoid false positives.
Anna Zaks19a66672012-02-21 00:00:44 +0000466 if (isEnclosingFunctionParam(ArgExpr) &&
Craig Topper0dbb7832014-05-27 02:45:47 +0000467 C.getLocationContext()->getParent() == nullptr)
Anna Zaks59d741f2011-08-12 22:47:22 +0000468 return;
469
Anna Zaksc94894f2011-08-12 21:14:26 +0000470 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
471 // If the argument points to something that's not a symbolic region, it
472 // can be:
Anna Zaks4aa34a532011-08-04 00:31:38 +0000473 // - unknown (cannot reason about it)
474 // - undefined (already reported by other checker)
Anna Zaks08be9b92011-08-04 17:28:06 +0000475 // - constant (null - should not be tracked,
476 // other constant will generate a compiler warning)
Anna Zaks4aa34a532011-08-04 00:31:38 +0000477 // - goto (should be reported by other checker)
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000478
479 // The call return value symbol should stay alive for as long as the
480 // allocated value symbol, since our diagnostics depend on the value
481 // returned by the call. Ex: Data should only be freed if noErr was
482 // returned during allocation.)
Ted Kremenek632e3b72012-01-06 22:09:28 +0000483 SymbolRef RetStatusSymbol =
484 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000485 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
486
487 // Track the allocated value in the checker state.
488 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaksc94894f2011-08-12 21:14:26 +0000489 RetStatusSymbol));
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000490 assert(State);
Anna Zaksda4c8d62011-10-26 21:06:34 +0000491 C.addTransition(State);
Anna Zaks15f496c2011-08-01 22:40:01 +0000492 }
493}
494
Anna Zaks6ca4fd52012-02-28 03:07:06 +0000495// TODO: This logic is the same as in Malloc checker.
Anna Zaksa043d0c2013-01-08 00:25:29 +0000496const ExplodedNode *
497MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
Anna Zaks4b062cb2012-02-23 22:53:29 +0000498 SymbolRef Sym,
499 CheckerContext &C) const {
Anna Zaks6ca4fd52012-02-28 03:07:06 +0000500 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaks4b062cb2012-02-23 22:53:29 +0000501 // Walk the ExplodedGraph backwards and find the first node that referred to
502 // the tracked symbol.
503 const ExplodedNode *AllocNode = N;
504
505 while (N) {
506 if (!N->getState()->get<AllocatedData>(Sym))
507 break;
Anna Zaks486a0ff2015-02-05 01:02:53 +0000508 // Allocation node, is the last node in the current or parent context in
509 // which the symbol was tracked.
510 const LocationContext *NContext = N->getLocationContext();
511 if (NContext == LeakContext ||
512 NContext->isParentOf(LeakContext))
Anna Zaks6ca4fd52012-02-28 03:07:06 +0000513 AllocNode = N;
Craig Topper0dbb7832014-05-27 02:45:47 +0000514 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaks4b062cb2012-02-23 22:53:29 +0000515 }
516
Anna Zaksa043d0c2013-01-08 00:25:29 +0000517 return AllocNode;
Anna Zaks4b062cb2012-02-23 22:53:29 +0000518}
519
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000520std::unique_ptr<BugReport>
521MacOSKeychainAPIChecker::generateAllocatedDataNotReleasedReport(
522 const AllocationPair &AP, ExplodedNode *N, CheckerContext &C) const {
Anna Zaksf880cff2011-08-24 21:58:55 +0000523 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000524 initBugType();
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000525 SmallString<70> sbuf;
Anna Zaks29f9b7a2011-08-15 18:42:00 +0000526 llvm::raw_svector_ostream os(sbuf);
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000527 os << "Allocated data is not released: missing a call to '"
528 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaks4b062cb2012-02-23 22:53:29 +0000529
530 // Most bug reports are cached at the location where they occurred.
531 // With leaks, we want to unique them by the location where they were
532 // allocated, and only report a single path.
Anna Zaks6ca4fd52012-02-28 03:07:06 +0000533 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaksa043d0c2013-01-08 00:25:29 +0000534 const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
Craig Topper0dbb7832014-05-27 02:45:47 +0000535 const Stmt *AllocStmt = nullptr;
Anna Zaksa043d0c2013-01-08 00:25:29 +0000536 ProgramPoint P = AllocNode->getLocation();
David Blaikie87396b92013-02-21 22:23:56 +0000537 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaksa043d0c2013-01-08 00:25:29 +0000538 AllocStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie87396b92013-02-21 22:23:56 +0000539 else if (Optional<clang::PostStmt> PS = P.getAs<clang::PostStmt>())
Anna Zaksa043d0c2013-01-08 00:25:29 +0000540 AllocStmt = PS->getStmt();
Anna Zaks4b062cb2012-02-23 22:53:29 +0000541
Anna Zaksa043d0c2013-01-08 00:25:29 +0000542 if (AllocStmt)
543 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
544 C.getSourceManager(),
545 AllocNode->getLocationContext());
546
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000547 auto Report =
548 llvm::make_unique<BugReport>(*BT, os.str(), N, LocUsedForUniqueing,
549 AllocNode->getLocationContext()->getDecl());
Anna Zaksa043d0c2013-01-08 00:25:29 +0000550
David Blaikie91e79022014-09-04 23:54:33 +0000551 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000552 markInteresting(Report.get(), AP);
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000553 return Report;
554}
555
556void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
557 CheckerContext &C) const {
Ted Kremenek49b1e382012-01-26 21:29:00 +0000558 ProgramStateRef State = C.getState();
Jordan Rose0c153cb2012-11-02 01:54:06 +0000559 AllocatedDataTy ASet = State->get<AllocatedData>();
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000560 if (ASet.isEmpty())
561 return;
562
563 bool Changed = false;
Anna Zaksbe460892011-08-24 20:52:46 +0000564 AllocationPairVec Errors;
Jordan Rose0c153cb2012-11-02 01:54:06 +0000565 for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000566 if (SR.isLive(I->first))
567 continue;
568
569 Changed = true;
570 State = State->remove<AllocatedData>(I->first);
571 // If the allocated symbol is null or if the allocation call might have
572 // returned an error, do not report.
Jordan Rose14fe9f32012-11-01 00:18:27 +0000573 ConstraintManager &CMgr = State->getConstraintManager();
574 ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
575 if (AllocFailed.isConstrainedTrue() ||
Anna Zaks5be8a4d2011-08-25 00:59:06 +0000576 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000577 continue;
Anna Zaksf880cff2011-08-24 21:58:55 +0000578 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000579 }
Anna Zaks4b062cb2012-02-23 22:53:29 +0000580 if (!Changed) {
581 // Generate the new, cleaned up state.
582 C.addTransition(State);
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000583 return;
Anna Zaks4b062cb2012-02-23 22:53:29 +0000584 }
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000585
Anton Yartsev6a619222014-02-17 18:25:34 +0000586 static CheckerProgramPointTag Tag(this, "DeadSymbolsLeak");
Devin Coughline39bd402015-09-16 22:03:05 +0000587 ExplodedNode *N = C.generateNonFatalErrorNode(C.getState(), &Tag);
588 if (!N)
589 return;
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000590
591 // Generate the error reports.
Benjamin Kramer72e64312015-09-24 14:48:49 +0000592 for (const auto &P : Errors)
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000593 C.emitReport(generateAllocatedDataNotReleasedReport(P, N, C));
Anna Zaks4b062cb2012-02-23 22:53:29 +0000594
595 // Generate the new, cleaned up state.
596 C.addTransition(State, N);
Anna Zaksfdd0aca2011-08-12 21:56:43 +0000597}
598
Anna Zaksbe460892011-08-24 20:52:46 +0000599
600PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
601 const ExplodedNode *N,
602 const ExplodedNode *PrevN,
603 BugReporterContext &BRC,
604 BugReport &BR) {
605 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
606 if (!AS)
Craig Topper0dbb7832014-05-27 02:45:47 +0000607 return nullptr;
Anna Zaksbe460892011-08-24 20:52:46 +0000608 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
609 if (ASPrev)
Craig Topper0dbb7832014-05-27 02:45:47 +0000610 return nullptr;
Anna Zaksbe460892011-08-24 20:52:46 +0000611
612 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
613 // allocation site.
David Blaikie87396b92013-02-21 22:23:56 +0000614 const CallExpr *CE =
615 cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
Anna Zaksbe460892011-08-24 20:52:46 +0000616 const FunctionDecl *funDecl = CE->getDirectCallee();
617 assert(funDecl && "We do not support indirect function calls as of now.");
618 StringRef funName = funDecl->getName();
619
620 // Get the expression of the corresponding argument.
621 unsigned Idx = getTrackedFunctionIndex(funName, true);
622 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
623 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks3a769bd2011-09-15 01:08:34 +0000624 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
625 N->getLocationContext());
Anna Zaksbe460892011-08-24 20:52:46 +0000626 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaks15f496c2011-08-01 22:40:01 +0000627}
628
629void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
630 mgr.registerChecker<MacOSKeychainAPIChecker>();
631}