blob: b96bc66b6f79678450550636811774fed3552d44 [file] [log] [blame]
Anna Zaks083fcb22011-08-04 17:28:06 +00001//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
Anna Zaksf57be282011-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"
16#include "clang/StaticAnalyzer/Core/Checker.h"
17#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Anna Zaks03826aa2011-08-04 00:26:57 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaksf57be282011-08-01 22:40:01 +000019#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Anna Zaksf57be282011-08-01 22:40:01 +000023
24using namespace clang;
25using namespace ento;
26
27namespace {
28class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
29 check::PreStmt<ReturnStmt>,
30 check::PostStmt<CallExpr>,
Anna Zaks703ffb12011-08-12 21:56:43 +000031 check::EndPath,
32 check::DeadSymbols> {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000033 mutable OwningPtr<BugType> BT;
Anna Zaks03826aa2011-08-04 00:26:57 +000034
Anna Zaksf57be282011-08-01 22:40:01 +000035public:
Anna Zaks864d2522011-08-12 21:14:26 +000036 /// AllocationState is a part of the checker specific state together with the
37 /// MemRegion corresponding to the allocated data.
38 struct AllocationState {
Anna Zaks864d2522011-08-12 21:14:26 +000039 /// The index of the allocator function.
40 unsigned int AllocatorIdx;
Anna Zakseacd2b42011-08-25 00:59:06 +000041 SymbolRef Region;
Anna Zaks864d2522011-08-12 21:14:26 +000042
43 AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
Anna Zaks864d2522011-08-12 21:14:26 +000044 AllocatorIdx(Idx),
Anna Zakseacd2b42011-08-25 00:59:06 +000045 Region(R) {}
Anna Zaks864d2522011-08-12 21:14:26 +000046
47 bool operator==(const AllocationState &X) const {
Anna Zakseacd2b42011-08-25 00:59:06 +000048 return (AllocatorIdx == X.AllocatorIdx &&
49 Region == X.Region);
Anna Zaks864d2522011-08-12 21:14:26 +000050 }
Anna Zakseacd2b42011-08-25 00:59:06 +000051
Anna Zaks864d2522011-08-12 21:14:26 +000052 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks864d2522011-08-12 21:14:26 +000053 ID.AddInteger(AllocatorIdx);
Anna Zakseacd2b42011-08-25 00:59:06 +000054 ID.AddPointer(Region);
Anna Zaks864d2522011-08-12 21:14:26 +000055 }
56 };
57
Anna Zaksf57be282011-08-01 22:40:01 +000058 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
59 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
60 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +000061 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaksd708bac2012-02-23 22:53:29 +000062 void checkEndPath(CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000063
64private:
Anna Zaks5eb7d822011-08-24 21:58:55 +000065 typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
Anna Zaks98401112011-08-24 20:52:46 +000066 typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
67
68 enum APIKind {
Anna Zaks6cf0ed02011-08-24 00:06:27 +000069 /// Denotes functions tracked by this checker.
70 ValidAPI = 0,
71 /// The functions commonly/mistakenly used in place of the given API.
72 ErrorAPI = 1,
73 /// The functions which may allocate the data. These are tracked to reduce
74 /// the false alarm rate.
75 PossibleAPI = 2
76 };
Anna Zaks083fcb22011-08-04 17:28:06 +000077 /// Stores the information about the allocator and deallocator functions -
78 /// these are the functions the checker is tracking.
79 struct ADFunctionInfo {
80 const char* Name;
81 unsigned int Param;
82 unsigned int DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000083 APIKind Kind;
Anna Zaks083fcb22011-08-04 17:28:06 +000084 };
85 static const unsigned InvalidIdx = 100000;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000086 static const unsigned FunctionsToTrackSize = 8;
Anna Zaks083fcb22011-08-04 17:28:06 +000087 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000088 /// The value, which represents no error return value for allocator functions.
89 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000090
Anna Zaks083fcb22011-08-04 17:28:06 +000091 /// Given the function name, returns the index of the allocator/deallocator
92 /// function.
Anna Zaks98401112011-08-24 20:52:46 +000093 static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
Anna Zaks03826aa2011-08-04 00:26:57 +000094
95 inline void initBugType() const {
96 if (!BT)
97 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
98 }
Anna Zaks703ffb12011-08-12 21:56:43 +000099
Anna Zaks6b7aad92011-08-25 00:32:42 +0000100 void generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000101 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000102 CheckerContext &C) const;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000103
Anna Zaksd708bac2012-02-23 22:53:29 +0000104 /// Find the allocation site for Sym on the path leading to the node N.
105 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
106 CheckerContext &C) const;
107
Anna Zaks98401112011-08-24 20:52:46 +0000108 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000109 ExplodedNode *N,
110 CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000111
112 /// Check if RetSym evaluates to an error value in the current state.
113 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000114 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000115 SValBuilder &Builder,
116 bool noError = false) const;
117
118 /// Check if RetSym evaluates to a NoErr value in the current state.
119 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000120 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000121 SValBuilder &Builder) const {
122 return definitelyReturnedError(RetSym, State, Builder, true);
123 }
124
Anna Zaks98401112011-08-24 20:52:46 +0000125 /// The bug visitor which allows us to print extra diagnostics along the
126 /// BugReport path. For example, showing the allocation site of the leaked
127 /// region.
128 class SecKeychainBugVisitor : public BugReporterVisitor {
129 protected:
130 // The allocated region symbol tracked by the main analysis.
131 SymbolRef Sym;
132
133 public:
134 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
135 virtual ~SecKeychainBugVisitor() {}
136
137 void Profile(llvm::FoldingSetNodeID &ID) const {
138 static int X = 0;
139 ID.AddPointer(&X);
140 ID.AddPointer(Sym);
141 }
142
143 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
144 const ExplodedNode *PrevN,
145 BugReporterContext &BRC,
146 BugReport &BR);
147 };
Anna Zaksf57be282011-08-01 22:40:01 +0000148};
149}
150
Anna Zaks7d458b02011-08-15 23:23:15 +0000151/// ProgramState traits to store the currently allocated (and not yet freed)
152/// symbols. This is a map from the allocated content symbol to the
153/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000154typedef llvm::ImmutableMap<SymbolRef,
155 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000156
157namespace { struct AllocatedData {}; }
158namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000159template<> struct ProgramStateTrait<AllocatedData>
160 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000161 static void *GDMIndex() { static int index = 0; return &index; }
162};
163}}
164
Anna Zaks03826aa2011-08-04 00:26:57 +0000165static bool isEnclosingFunctionParam(const Expr *E) {
166 E = E->IgnoreParenCasts();
167 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
168 const ValueDecl *VD = DRE->getDecl();
169 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
170 return true;
171 }
172 return false;
173}
174
Anna Zaks083fcb22011-08-04 17:28:06 +0000175const MacOSKeychainAPIChecker::ADFunctionInfo
176 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000177 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
178 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
179 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
180 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
181 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
182 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
183 {"free", 0, InvalidIdx, ErrorAPI}, // 6
184 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000185};
186
187unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000188 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000189 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
190 ADFunctionInfo FI = FunctionsToTrack[I];
191 if (FI.Name != Name)
192 continue;
193 // Make sure the function is of the right type (allocator vs deallocator).
194 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
195 return InvalidIdx;
196 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
197 return InvalidIdx;
198
199 return I;
200 }
201 // The function is not tracked.
202 return InvalidIdx;
203}
204
Anna Zaks864d2522011-08-12 21:14:26 +0000205static SymbolRef getSymbolForRegion(CheckerContext &C,
206 const MemRegion *R) {
Anna Zaks065a4052011-08-29 21:10:00 +0000207 // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
208 // region, if that is the case, get the underlining region.
209 R = R->StripCasts();
Anna Zaks31e10282011-08-23 23:56:12 +0000210 if (!isa<SymbolicRegion>(R)) {
Anna Zaks31e10282011-08-23 23:56:12 +0000211 return 0;
212 }
Anna Zaks864d2522011-08-12 21:14:26 +0000213 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000214}
215
Anna Zaks864d2522011-08-12 21:14:26 +0000216static bool isBadDeallocationArgument(const MemRegion *Arg) {
217 if (isa<AllocaRegion>(Arg) ||
218 isa<BlockDataRegion>(Arg) ||
219 isa<TypedRegion>(Arg)) {
220 return true;
221 }
222 return false;
223}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000224/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000225/// that value is itself an address, and return the corresponding symbol.
226static SymbolRef getAsPointeeSymbol(const Expr *Expr,
227 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000228 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000229 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000230
Anna Zaksca0b57e2011-08-05 00:37:00 +0000231 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
232 StoreManager& SM = C.getStoreManager();
Anna Zaks14374252012-01-12 02:22:40 +0000233 const MemRegion *V = SM.getBinding(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000234 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000235 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000236 }
237 return 0;
238}
239
Anna Zaks703ffb12011-08-12 21:56:43 +0000240// When checking for error code, we need to consider the following cases:
241// 1) noErr / [0]
242// 2) someErr / [1, inf]
243// 3) unknown
244// If noError, returns true iff (1).
245// If !noError, returns true iff (2).
246bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000247 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000248 SValBuilder &Builder,
249 bool noError) const {
250 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
251 Builder.getSymbolManager().getType(RetSym));
252 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
253 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000254 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000255 if (ErrState == State) {
256 return true;
257 }
258
259 return false;
260}
261
Anna Zaksdd6060e2011-08-23 23:47:36 +0000262// Report deallocator mismatch. Remove the region from tracking - reporting a
263// missing free error after this one is redundant.
264void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000265 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000266 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000267 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000268 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000269 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000270 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000271
272 if (!N)
273 return;
274 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000275 SmallString<80> sbuf;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000276 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000277 unsigned int PDeallocIdx =
278 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000279
280 os << "Deallocator doesn't match the allocator: '"
281 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
282 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000283 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000284 Report->addRange(ArgExpr->getSourceRange());
285 C.EmitReport(Report);
286}
287
Anna Zaksf57be282011-08-01 22:40:01 +0000288void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
289 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000290 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000291 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000292
Anna Zaksb805c8f2011-12-01 05:57:37 +0000293 StringRef funName = C.getCalleeName(CE);
294 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000295 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000296
Anna Zaksca0b57e2011-08-05 00:37:00 +0000297 // If it is a call to an allocator function, it could be a double allocation.
298 idx = getTrackedFunctionIndex(funName, true);
299 if (idx != InvalidIdx) {
300 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000301 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000302 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000303 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000304 // Remove the value from the state. The new symbol will be added for
305 // tracking when the second allocator is processed in checkPostStmt().
306 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000307 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000308 if (!N)
309 return;
310 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000311 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000312 llvm::raw_svector_ostream os(sbuf);
313 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
314 os << "Allocated data should be released before another call to "
315 << "the allocator: missing a call to '"
316 << FunctionsToTrack[DIdx].Name
317 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000318 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000319 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000320 Report->addRange(ArgExpr->getSourceRange());
321 C.EmitReport(Report);
322 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000323 }
324 return;
325 }
326
327 // Is it a call to one of deallocator functions?
328 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000329 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000330 return;
331
Anna Zaks864d2522011-08-12 21:14:26 +0000332 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000333 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000334 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000335
336 // Undef is reported by another checker.
337 if (ArgSVal.isUndef())
338 return;
339
340 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000341 if (!Arg)
342 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000343
344 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
345 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
346 // If the argument is coming from the heap, globals, or unknown, do not
347 // report it.
348 if (!ArgSM && !RegionArgIsBad)
349 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000350
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000351 // Is the argument to the call being tracked?
352 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
353 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
354 return;
355 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000356 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000357 // TODO: We might want a more precise diagnostic for double free
358 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000359 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000360 // It is possible that this is a false positive - the argument might
361 // have entered as an enclosing function parameter.
362 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000363 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000364
Anna Zaks0bd6b112011-10-26 21:06:34 +0000365 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000366 if (!N)
367 return;
368 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000369 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000370 "Trying to free data which has not been allocated.", N);
371 Report->addRange(ArgExpr->getSourceRange());
372 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000373 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000374 }
Anna Zaks08551b52011-08-04 00:31:38 +0000375
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000376 // Process functions which might deallocate.
377 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
378
379 if (funName == "CFStringCreateWithBytesNoCopy") {
380 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
381 // NULL ~ default deallocator, so warn.
382 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
383 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000384 const AllocationPair AP = std::make_pair(ArgSM, AS);
385 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000386 return;
387 }
388 // One of the default allocators, so warn.
389 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
390 StringRef DeallocatorName = DE->getFoundDecl()->getName();
391 if (DeallocatorName == "kCFAllocatorDefault" ||
392 DeallocatorName == "kCFAllocatorSystemDefault" ||
393 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000394 const AllocationPair AP = std::make_pair(ArgSM, AS);
395 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000396 return;
397 }
398 // If kCFAllocatorNull, which does not deallocate, we still have to
399 // find the deallocator. Otherwise, assume that the user had written a
400 // custom deallocator which does the right thing.
401 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
402 State = State->remove<AllocatedData>(ArgSM);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000403 C.addTransition(State);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000404 return;
405 }
406 }
407 }
408 return;
409 }
410
Anna Zaks7d458b02011-08-15 23:23:15 +0000411 // The call is deallocating a value we previously allocated, so remove it
412 // from the next state.
413 State = State->remove<AllocatedData>(ArgSM);
414
Anna Zaksdd6060e2011-08-23 23:47:36 +0000415 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000416 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000417 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000418 const AllocationPair AP = std::make_pair(ArgSM, AS);
419 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000420 return;
421 }
422
Anna Zaksee5a21f2011-12-01 16:41:58 +0000423 // If the buffer can be null and the return status can be an error,
424 // report a bad call to free.
425 if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
426 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000427 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000428 if (!N)
429 return;
430 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000431 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000432 "Only call free if a valid (non-NULL) buffer was returned.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000433 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000434 Report->addRange(ArgExpr->getSourceRange());
435 C.EmitReport(Report);
436 return;
437 }
438
Anna Zaks0bd6b112011-10-26 21:06:34 +0000439 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000440}
441
442void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
443 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000444 ProgramStateRef State = C.getState();
Anna Zaks0e12ebf2011-11-16 19:57:55 +0000445 StringRef funName = C.getCalleeName(CE);
Anna Zaksf57be282011-08-01 22:40:01 +0000446
447 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000448 unsigned idx = getTrackedFunctionIndex(funName, true);
449 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000450 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000451
Anna Zaks083fcb22011-08-04 17:28:06 +0000452 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000453 // If the argument entered as an enclosing function parameter, skip it to
454 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000455 if (isEnclosingFunctionParam(ArgExpr) &&
456 C.getLocationContext()->getParent() == 0)
Anna Zaks79c9c752011-08-12 22:47:22 +0000457 return;
458
Anna Zaks864d2522011-08-12 21:14:26 +0000459 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
460 // If the argument points to something that's not a symbolic region, it
461 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000462 // - unknown (cannot reason about it)
463 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000464 // - constant (null - should not be tracked,
465 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000466 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000467
468 // The call return value symbol should stay alive for as long as the
469 // allocated value symbol, since our diagnostics depend on the value
470 // returned by the call. Ex: Data should only be freed if noErr was
471 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000472 SymbolRef RetStatusSymbol =
473 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000474 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
475
476 // Track the allocated value in the checker state.
477 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000478 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000479 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000480 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000481 }
482}
483
484void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
485 CheckerContext &C) const {
486 const Expr *retExpr = S->getRetValue();
487 if (!retExpr)
488 return;
489
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000490 // If inside inlined call, skip it.
491 if (C.getLocationContext()->getParent() != 0)
492 return;
493
Anna Zaksf57be282011-08-01 22:40:01 +0000494 // Check if the value is escaping through the return.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000495 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000496 const MemRegion *V =
497 state->getSVal(retExpr, C.getLocationContext()).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000498 if (!V)
499 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000500 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000501
Anna Zaks03826aa2011-08-04 00:26:57 +0000502 // Proceed from the new state.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000503 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000504}
505
Anna Zaks721aa372012-02-28 03:07:06 +0000506// TODO: This logic is the same as in Malloc checker.
Anna Zaksd708bac2012-02-23 22:53:29 +0000507const Stmt *
508MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
509 SymbolRef Sym,
510 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000511 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000512 // Walk the ExplodedGraph backwards and find the first node that referred to
513 // the tracked symbol.
514 const ExplodedNode *AllocNode = N;
515
516 while (N) {
517 if (!N->getState()->get<AllocatedData>(Sym))
518 break;
Anna Zaks721aa372012-02-28 03:07:06 +0000519 // Allocation node, is the last node in the current context in which the
520 // symbol was tracked.
521 if (N->getLocationContext() == LeakContext)
522 AllocNode = N;
Anna Zaksd708bac2012-02-23 22:53:29 +0000523 N = N->pred_empty() ? NULL : *(N->pred_begin());
524 }
525
526 ProgramPoint P = AllocNode->getLocation();
Anna Zaks721aa372012-02-28 03:07:06 +0000527 if (!isa<StmtPoint>(P))
528 return 0;
Anna Zaksd708bac2012-02-23 22:53:29 +0000529 return cast<clang::PostStmt>(P).getStmt();
530}
531
Anna Zakse172e8b2011-08-17 23:00:25 +0000532BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000533 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000534 ExplodedNode *N,
535 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000536 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000537 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000538 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000539 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000540 os << "Allocated data is not released: missing a call to '"
541 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000542
543 // Most bug reports are cached at the location where they occurred.
544 // With leaks, we want to unique them by the location where they were
545 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000546 PathDiagnosticLocation LocUsedForUniqueing;
547 if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
548 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
549 C.getSourceManager(), N->getLocationContext());
Anna Zaksd708bac2012-02-23 22:53:29 +0000550
551 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
Anna Zaks98401112011-08-24 20:52:46 +0000552 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaks703ffb12011-08-12 21:56:43 +0000553 return Report;
554}
555
556void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
557 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000558 ProgramStateRef State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000559 AllocatedSetTy ASet = State->get<AllocatedData>();
560 if (ASet.isEmpty())
561 return;
562
563 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000564 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000565 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
566 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.
573 if (State->getSymVal(I->first) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000574 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000575 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000576 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000577 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000578 if (!Changed) {
579 // Generate the new, cleaned up state.
580 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000581 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000582 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000583
Anna Zaksd708bac2012-02-23 22:53:29 +0000584 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
585 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000586
587 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000588 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
589 I != E; ++I) {
Anna Zaksd708bac2012-02-23 22:53:29 +0000590 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000591 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000592
593 // Generate the new, cleaned up state.
594 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000595}
596
597// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksd708bac2012-02-23 22:53:29 +0000598void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
599 ProgramStateRef state = C.getState();
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000600
601 // If inside inlined call, skip it.
Anna Zaksd708bac2012-02-23 22:53:29 +0000602 if (C.getLocationContext()->getParent() != 0)
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000603 return;
604
Anna Zaksf57be282011-08-01 22:40:01 +0000605 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000606 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000607 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000608
609 // Anything which has been allocated but not freed (nor escaped) will be
610 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000611 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000612 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000613 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000614 Changed = true;
615 state = state->remove<AllocatedData>(I->first);
616 // If the allocated symbol is null or if error code was returned at
617 // allocation, do not report.
618 if (state->getSymVal(I.getKey()) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000619 definitelyReturnedError(I->second.Region, state,
Anna Zaksd708bac2012-02-23 22:53:29 +0000620 C.getSValBuilder())) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000621 continue;
622 }
Anna Zaks5eb7d822011-08-24 21:58:55 +0000623 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000624 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000625
626 // If no change, do not generate a new state.
Anna Zaksd708bac2012-02-23 22:53:29 +0000627 if (!Changed) {
628 C.addTransition(state);
Anna Zaks703ffb12011-08-12 21:56:43 +0000629 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000630 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000631
Anna Zaksd708bac2012-02-23 22:53:29 +0000632 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
633 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000634
635 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000636 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
637 I != E; ++I) {
Anna Zaksd708bac2012-02-23 22:53:29 +0000638 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000639 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000640
641 C.addTransition(state, N);
Anna Zaks98401112011-08-24 20:52:46 +0000642}
Anna Zaks703ffb12011-08-12 21:56:43 +0000643
Anna Zaks98401112011-08-24 20:52:46 +0000644
645PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
646 const ExplodedNode *N,
647 const ExplodedNode *PrevN,
648 BugReporterContext &BRC,
649 BugReport &BR) {
650 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
651 if (!AS)
652 return 0;
653 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
654 if (ASPrev)
655 return 0;
656
657 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
658 // allocation site.
659 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
660 .getStmt());
661 const FunctionDecl *funDecl = CE->getDirectCallee();
662 assert(funDecl && "We do not support indirect function calls as of now.");
663 StringRef funName = funDecl->getName();
664
665 // Get the expression of the corresponding argument.
666 unsigned Idx = getTrackedFunctionIndex(funName, true);
667 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
668 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000669 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
670 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000671 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000672}
673
674void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
675 mgr.registerChecker<MacOSKeychainAPIChecker>();
676}