blob: 3e42ba3f062c6bf0e2ec96d3888237e0f524abb9 [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 }
Ted Kremenek76aadc32012-03-09 01:13:14 +0000124
125 /// Mark an AllocationPair interesting for diagnostic reporting.
126 void markInteresting(BugReport *R, const AllocationPair &AP) const {
127 R->markInteresting(AP.first);
128 R->markInteresting(AP.second->Region);
129 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000130
Anna Zaks98401112011-08-24 20:52:46 +0000131 /// The bug visitor which allows us to print extra diagnostics along the
132 /// BugReport path. For example, showing the allocation site of the leaked
133 /// region.
134 class SecKeychainBugVisitor : public BugReporterVisitor {
135 protected:
136 // The allocated region symbol tracked by the main analysis.
137 SymbolRef Sym;
138
139 public:
140 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
141 virtual ~SecKeychainBugVisitor() {}
142
143 void Profile(llvm::FoldingSetNodeID &ID) const {
144 static int X = 0;
145 ID.AddPointer(&X);
146 ID.AddPointer(Sym);
147 }
148
149 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
150 const ExplodedNode *PrevN,
151 BugReporterContext &BRC,
152 BugReport &BR);
153 };
Anna Zaksf57be282011-08-01 22:40:01 +0000154};
155}
156
Anna Zaks7d458b02011-08-15 23:23:15 +0000157/// ProgramState traits to store the currently allocated (and not yet freed)
158/// symbols. This is a map from the allocated content symbol to the
159/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000160typedef llvm::ImmutableMap<SymbolRef,
161 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000162
163namespace { struct AllocatedData {}; }
164namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000165template<> struct ProgramStateTrait<AllocatedData>
166 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000167 static void *GDMIndex() { static int index = 0; return &index; }
168};
169}}
170
Anna Zaks03826aa2011-08-04 00:26:57 +0000171static bool isEnclosingFunctionParam(const Expr *E) {
172 E = E->IgnoreParenCasts();
173 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
174 const ValueDecl *VD = DRE->getDecl();
175 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
176 return true;
177 }
178 return false;
179}
180
Anna Zaks083fcb22011-08-04 17:28:06 +0000181const MacOSKeychainAPIChecker::ADFunctionInfo
182 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000183 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
184 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
185 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
186 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
187 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
188 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
189 {"free", 0, InvalidIdx, ErrorAPI}, // 6
190 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000191};
192
193unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000194 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000195 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
196 ADFunctionInfo FI = FunctionsToTrack[I];
197 if (FI.Name != Name)
198 continue;
199 // Make sure the function is of the right type (allocator vs deallocator).
200 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
201 return InvalidIdx;
202 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
203 return InvalidIdx;
204
205 return I;
206 }
207 // The function is not tracked.
208 return InvalidIdx;
209}
210
Anna Zaks864d2522011-08-12 21:14:26 +0000211static bool isBadDeallocationArgument(const MemRegion *Arg) {
Jordy Rose3e678142012-03-11 00:08:24 +0000212 if (!Arg)
213 return false;
Anna Zaks864d2522011-08-12 21:14:26 +0000214 if (isa<AllocaRegion>(Arg) ||
215 isa<BlockDataRegion>(Arg) ||
216 isa<TypedRegion>(Arg)) {
217 return true;
218 }
219 return false;
220}
Jordy Rose3e678142012-03-11 00:08:24 +0000221
Anna Zaksca0b57e2011-08-05 00:37:00 +0000222/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000223/// that value is itself an address, and return the corresponding symbol.
224static SymbolRef getAsPointeeSymbol(const Expr *Expr,
225 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000226 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000227 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000228
Anna Zaksca0b57e2011-08-05 00:37:00 +0000229 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
230 StoreManager& SM = C.getStoreManager();
Jordy Rose3e678142012-03-11 00:08:24 +0000231 SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
232 if (sym)
233 return sym;
Anna Zaksca0b57e2011-08-05 00:37:00 +0000234 }
235 return 0;
236}
237
Anna Zaks703ffb12011-08-12 21:56:43 +0000238// When checking for error code, we need to consider the following cases:
239// 1) noErr / [0]
240// 2) someErr / [1, inf]
241// 3) unknown
242// If noError, returns true iff (1).
243// If !noError, returns true iff (2).
244bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000245 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000246 SValBuilder &Builder,
247 bool noError) const {
248 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
249 Builder.getSymbolManager().getType(RetSym));
250 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
251 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000252 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000253 if (ErrState == State) {
254 return true;
255 }
256
257 return false;
258}
259
Anna Zaksdd6060e2011-08-23 23:47:36 +0000260// Report deallocator mismatch. Remove the region from tracking - reporting a
261// missing free error after this one is redundant.
262void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000263 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000264 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000265 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000266 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000267 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000268 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000269
270 if (!N)
271 return;
272 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000273 SmallString<80> sbuf;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000274 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000275 unsigned int PDeallocIdx =
276 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000277
278 os << "Deallocator doesn't match the allocator: '"
279 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
280 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000281 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000282 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000283 markInteresting(Report, AP);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000284 C.EmitReport(Report);
285}
286
Anna Zaksf57be282011-08-01 22:40:01 +0000287void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
288 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000289 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000290 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000291
Anna Zaksb805c8f2011-12-01 05:57:37 +0000292 StringRef funName = C.getCalleeName(CE);
293 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000294 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000295
Anna Zaksca0b57e2011-08-05 00:37:00 +0000296 // If it is a call to an allocator function, it could be a double allocation.
297 idx = getTrackedFunctionIndex(funName, true);
298 if (idx != InvalidIdx) {
299 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000300 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000301 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000302 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000303 // Remove the value from the state. The new symbol will be added for
304 // tracking when the second allocator is processed in checkPostStmt().
305 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000306 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000307 if (!N)
308 return;
309 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000310 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000311 llvm::raw_svector_ostream os(sbuf);
312 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
313 os << "Allocated data should be released before another call to "
314 << "the allocator: missing a call to '"
315 << FunctionsToTrack[DIdx].Name
316 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000317 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000318 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000319 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000320 Report->markInteresting(AS->Region);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000321 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
Jordy Rose3e678142012-03-11 00:08:24 +0000340 SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
Anna Zaks864d2522011-08-12 21:14:26 +0000341
Anna Zaks864d2522011-08-12 21:14:26 +0000342 // If the argument is coming from the heap, globals, or unknown, do not
343 // report it.
Jordy Rose3e678142012-03-11 00:08:24 +0000344 bool RegionArgIsBad = false;
345 if (!ArgSM) {
346 if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
347 return;
348 RegionArgIsBad = true;
349 }
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());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000372 if (AS)
373 Report->markInteresting(AS->Region);
Anna Zaks08551b52011-08-04 00:31:38 +0000374 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000375 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000376 }
Anna Zaks08551b52011-08-04 00:31:38 +0000377
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000378 // Process functions which might deallocate.
379 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
380
381 if (funName == "CFStringCreateWithBytesNoCopy") {
382 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
383 // NULL ~ default deallocator, so warn.
384 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
385 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000386 const AllocationPair AP = std::make_pair(ArgSM, AS);
387 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000388 return;
389 }
390 // One of the default allocators, so warn.
391 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
392 StringRef DeallocatorName = DE->getFoundDecl()->getName();
393 if (DeallocatorName == "kCFAllocatorDefault" ||
394 DeallocatorName == "kCFAllocatorSystemDefault" ||
395 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000396 const AllocationPair AP = std::make_pair(ArgSM, AS);
397 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000398 return;
399 }
400 // If kCFAllocatorNull, which does not deallocate, we still have to
401 // find the deallocator. Otherwise, assume that the user had written a
402 // custom deallocator which does the right thing.
403 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
404 State = State->remove<AllocatedData>(ArgSM);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000405 C.addTransition(State);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000406 return;
407 }
408 }
409 }
410 return;
411 }
412
Anna Zaks7d458b02011-08-15 23:23:15 +0000413 // The call is deallocating a value we previously allocated, so remove it
414 // from the next state.
415 State = State->remove<AllocatedData>(ArgSM);
416
Anna Zaksdd6060e2011-08-23 23:47:36 +0000417 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000418 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000419 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000420 const AllocationPair AP = std::make_pair(ArgSM, AS);
421 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000422 return;
423 }
424
Anna Zaksee5a21f2011-12-01 16:41:58 +0000425 // If the buffer can be null and the return status can be an error,
426 // report a bad call to free.
427 if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
428 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000429 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000430 if (!N)
431 return;
432 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000433 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000434 "Only call free if a valid (non-NULL) buffer was returned.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000435 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000436 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000437 Report->markInteresting(AS->Region);
Anna Zaks703ffb12011-08-12 21:56:43 +0000438 C.EmitReport(Report);
439 return;
440 }
441
Anna Zaks0bd6b112011-10-26 21:06:34 +0000442 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000443}
444
445void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
446 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000447 ProgramStateRef State = C.getState();
Anna Zaks0e12ebf2011-11-16 19:57:55 +0000448 StringRef funName = C.getCalleeName(CE);
Anna Zaksf57be282011-08-01 22:40:01 +0000449
450 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000451 unsigned idx = getTrackedFunctionIndex(funName, true);
452 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000453 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000454
Anna Zaks083fcb22011-08-04 17:28:06 +0000455 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000456 // If the argument entered as an enclosing function parameter, skip it to
457 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000458 if (isEnclosingFunctionParam(ArgExpr) &&
459 C.getLocationContext()->getParent() == 0)
Anna Zaks79c9c752011-08-12 22:47:22 +0000460 return;
461
Anna Zaks864d2522011-08-12 21:14:26 +0000462 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
463 // If the argument points to something that's not a symbolic region, it
464 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000465 // - unknown (cannot reason about it)
466 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000467 // - constant (null - should not be tracked,
468 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000469 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000470
471 // The call return value symbol should stay alive for as long as the
472 // allocated value symbol, since our diagnostics depend on the value
473 // returned by the call. Ex: Data should only be freed if noErr was
474 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000475 SymbolRef RetStatusSymbol =
476 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000477 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
478
479 // Track the allocated value in the checker state.
480 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000481 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000482 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000483 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000484 }
485}
486
487void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
488 CheckerContext &C) const {
489 const Expr *retExpr = S->getRetValue();
490 if (!retExpr)
491 return;
492
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000493 // If inside inlined call, skip it.
Jordy Rose3e678142012-03-11 00:08:24 +0000494 const LocationContext *LC = C.getLocationContext();
495 if (LC->getParent() != 0)
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000496 return;
497
Anna Zaksf57be282011-08-01 22:40:01 +0000498 // Check if the value is escaping through the return.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000499 ProgramStateRef state = C.getState();
Jordy Rose3e678142012-03-11 00:08:24 +0000500 SymbolRef sym = state->getSVal(retExpr, LC).getAsLocSymbol();
501 if (!sym)
Anna Zaksf57be282011-08-01 22:40:01 +0000502 return;
Jordy Rose3e678142012-03-11 00:08:24 +0000503 state = state->remove<AllocatedData>(sym);
Anna Zaksf57be282011-08-01 22:40:01 +0000504
Anna Zaks03826aa2011-08-04 00:26:57 +0000505 // Proceed from the new state.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000506 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000507}
508
Anna Zaks721aa372012-02-28 03:07:06 +0000509// TODO: This logic is the same as in Malloc checker.
Anna Zaksd708bac2012-02-23 22:53:29 +0000510const Stmt *
511MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
512 SymbolRef Sym,
513 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000514 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000515 // Walk the ExplodedGraph backwards and find the first node that referred to
516 // the tracked symbol.
517 const ExplodedNode *AllocNode = N;
518
519 while (N) {
520 if (!N->getState()->get<AllocatedData>(Sym))
521 break;
Anna Zaks721aa372012-02-28 03:07:06 +0000522 // Allocation node, is the last node in the current context in which the
523 // symbol was tracked.
524 if (N->getLocationContext() == LeakContext)
525 AllocNode = N;
Anna Zaksd708bac2012-02-23 22:53:29 +0000526 N = N->pred_empty() ? NULL : *(N->pred_begin());
527 }
528
529 ProgramPoint P = AllocNode->getLocation();
Anna Zaks721aa372012-02-28 03:07:06 +0000530 if (!isa<StmtPoint>(P))
531 return 0;
Anna Zaksd708bac2012-02-23 22:53:29 +0000532 return cast<clang::PostStmt>(P).getStmt();
533}
534
Anna Zakse172e8b2011-08-17 23:00:25 +0000535BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000536 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000537 ExplodedNode *N,
538 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000539 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000540 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000541 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000542 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000543 os << "Allocated data is not released: missing a call to '"
544 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000545
546 // Most bug reports are cached at the location where they occurred.
547 // With leaks, we want to unique them by the location where they were
548 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000549 PathDiagnosticLocation LocUsedForUniqueing;
550 if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
551 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
552 C.getSourceManager(), N->getLocationContext());
Anna Zaksd708bac2012-02-23 22:53:29 +0000553
554 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
Anna Zaks98401112011-08-24 20:52:46 +0000555 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Ted Kremenek76aadc32012-03-09 01:13:14 +0000556 markInteresting(Report, AP);
Anna Zaks703ffb12011-08-12 21:56:43 +0000557 return Report;
558}
559
560void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
561 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000562 ProgramStateRef State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000563 AllocatedSetTy ASet = State->get<AllocatedData>();
564 if (ASet.isEmpty())
565 return;
566
567 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000568 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000569 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
570 if (SR.isLive(I->first))
571 continue;
572
573 Changed = true;
574 State = State->remove<AllocatedData>(I->first);
575 // If the allocated symbol is null or if the allocation call might have
576 // returned an error, do not report.
577 if (State->getSymVal(I->first) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000578 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000579 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000580 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000581 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000582 if (!Changed) {
583 // Generate the new, cleaned up state.
584 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000585 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000586 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000587
Anna Zaksd708bac2012-02-23 22:53:29 +0000588 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
589 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000590
591 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000592 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
593 I != E; ++I) {
Anna Zaksd708bac2012-02-23 22:53:29 +0000594 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000595 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000596
597 // Generate the new, cleaned up state.
598 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000599}
600
601// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksd708bac2012-02-23 22:53:29 +0000602void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
603 ProgramStateRef state = C.getState();
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000604
605 // If inside inlined call, skip it.
Anna Zaksd708bac2012-02-23 22:53:29 +0000606 if (C.getLocationContext()->getParent() != 0)
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000607 return;
608
Anna Zaksf57be282011-08-01 22:40:01 +0000609 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000610 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000611 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000612
613 // Anything which has been allocated but not freed (nor escaped) will be
614 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000615 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000616 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000617 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000618 Changed = true;
619 state = state->remove<AllocatedData>(I->first);
620 // If the allocated symbol is null or if error code was returned at
621 // allocation, do not report.
622 if (state->getSymVal(I.getKey()) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000623 definitelyReturnedError(I->second.Region, state,
Anna Zaksd708bac2012-02-23 22:53:29 +0000624 C.getSValBuilder())) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000625 continue;
626 }
Anna Zaks5eb7d822011-08-24 21:58:55 +0000627 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000628 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000629
630 // If no change, do not generate a new state.
Anna Zaksd708bac2012-02-23 22:53:29 +0000631 if (!Changed) {
632 C.addTransition(state);
Anna Zaks703ffb12011-08-12 21:56:43 +0000633 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000634 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000635
Anna Zaksd708bac2012-02-23 22:53:29 +0000636 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
637 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000638
639 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000640 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
641 I != E; ++I) {
Anna Zaksd708bac2012-02-23 22:53:29 +0000642 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000643 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000644
645 C.addTransition(state, N);
Anna Zaks98401112011-08-24 20:52:46 +0000646}
Anna Zaks703ffb12011-08-12 21:56:43 +0000647
Anna Zaks98401112011-08-24 20:52:46 +0000648
649PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
650 const ExplodedNode *N,
651 const ExplodedNode *PrevN,
652 BugReporterContext &BRC,
653 BugReport &BR) {
654 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
655 if (!AS)
656 return 0;
657 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
658 if (ASPrev)
659 return 0;
660
661 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
662 // allocation site.
663 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
664 .getStmt());
665 const FunctionDecl *funDecl = CE->getDirectCallee();
666 assert(funDecl && "We do not support indirect function calls as of now.");
667 StringRef funName = funDecl->getName();
668
669 // Get the expression of the corresponding argument.
670 unsigned Idx = getTrackedFunctionIndex(funName, true);
671 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
672 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000673 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
674 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000675 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000676}
677
678void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
679 mgr.registerChecker<MacOSKeychainAPIChecker>();
680}