blob: 1b8dd6874c87db99b4202de84cc1562f18fc7c61 [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 SymbolRef getSymbolForRegion(CheckerContext &C,
212 const MemRegion *R) {
Anna Zaks065a4052011-08-29 21:10:00 +0000213 // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
214 // region, if that is the case, get the underlining region.
215 R = R->StripCasts();
Anna Zaks31e10282011-08-23 23:56:12 +0000216 if (!isa<SymbolicRegion>(R)) {
Anna Zaks31e10282011-08-23 23:56:12 +0000217 return 0;
218 }
Anna Zaks864d2522011-08-12 21:14:26 +0000219 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000220}
221
Anna Zaks864d2522011-08-12 21:14:26 +0000222static bool isBadDeallocationArgument(const MemRegion *Arg) {
223 if (isa<AllocaRegion>(Arg) ||
224 isa<BlockDataRegion>(Arg) ||
225 isa<TypedRegion>(Arg)) {
226 return true;
227 }
228 return false;
229}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000230/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000231/// that value is itself an address, and return the corresponding symbol.
232static SymbolRef getAsPointeeSymbol(const Expr *Expr,
233 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000234 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000235 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000236
Anna Zaksca0b57e2011-08-05 00:37:00 +0000237 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
238 StoreManager& SM = C.getStoreManager();
Anna Zaks14374252012-01-12 02:22:40 +0000239 const MemRegion *V = SM.getBinding(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000240 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000241 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000242 }
243 return 0;
244}
245
Anna Zaks703ffb12011-08-12 21:56:43 +0000246// When checking for error code, we need to consider the following cases:
247// 1) noErr / [0]
248// 2) someErr / [1, inf]
249// 3) unknown
250// If noError, returns true iff (1).
251// If !noError, returns true iff (2).
252bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000253 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000254 SValBuilder &Builder,
255 bool noError) const {
256 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
257 Builder.getSymbolManager().getType(RetSym));
258 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
259 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000260 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000261 if (ErrState == State) {
262 return true;
263 }
264
265 return false;
266}
267
Anna Zaksdd6060e2011-08-23 23:47:36 +0000268// Report deallocator mismatch. Remove the region from tracking - reporting a
269// missing free error after this one is redundant.
270void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000271 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000272 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000273 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000274 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000275 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000276 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000277
278 if (!N)
279 return;
280 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000281 SmallString<80> sbuf;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000282 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000283 unsigned int PDeallocIdx =
284 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000285
286 os << "Deallocator doesn't match the allocator: '"
287 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
288 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000289 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000290 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000291 markInteresting(Report, AP);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000292 C.EmitReport(Report);
293}
294
Anna Zaksf57be282011-08-01 22:40:01 +0000295void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
296 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000297 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000298 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000299
Anna Zaksb805c8f2011-12-01 05:57:37 +0000300 StringRef funName = C.getCalleeName(CE);
301 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000302 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000303
Anna Zaksca0b57e2011-08-05 00:37:00 +0000304 // If it is a call to an allocator function, it could be a double allocation.
305 idx = getTrackedFunctionIndex(funName, true);
306 if (idx != InvalidIdx) {
307 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000308 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000309 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000310 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000311 // Remove the value from the state. The new symbol will be added for
312 // tracking when the second allocator is processed in checkPostStmt().
313 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000314 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000315 if (!N)
316 return;
317 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000318 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000319 llvm::raw_svector_ostream os(sbuf);
320 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
321 os << "Allocated data should be released before another call to "
322 << "the allocator: missing a call to '"
323 << FunctionsToTrack[DIdx].Name
324 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000325 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000326 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000327 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000328 Report->markInteresting(AS->Region);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000329 C.EmitReport(Report);
330 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000331 }
332 return;
333 }
334
335 // Is it a call to one of deallocator functions?
336 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000337 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000338 return;
339
Anna Zaks864d2522011-08-12 21:14:26 +0000340 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000341 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000342 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000343
344 // Undef is reported by another checker.
345 if (ArgSVal.isUndef())
346 return;
347
348 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000349 if (!Arg)
350 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000351
352 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
353 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
354 // If the argument is coming from the heap, globals, or unknown, do not
355 // report it.
356 if (!ArgSM && !RegionArgIsBad)
357 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000358
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000359 // Is the argument to the call being tracked?
360 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
361 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
362 return;
363 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000364 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000365 // TODO: We might want a more precise diagnostic for double free
366 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000367 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000368 // It is possible that this is a false positive - the argument might
369 // have entered as an enclosing function parameter.
370 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000371 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000372
Anna Zaks0bd6b112011-10-26 21:06:34 +0000373 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000374 if (!N)
375 return;
376 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000377 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000378 "Trying to free data which has not been allocated.", N);
379 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000380 if (AS)
381 Report->markInteresting(AS->Region);
Anna Zaks08551b52011-08-04 00:31:38 +0000382 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000383 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000384 }
Anna Zaks08551b52011-08-04 00:31:38 +0000385
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000386 // Process functions which might deallocate.
387 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
388
389 if (funName == "CFStringCreateWithBytesNoCopy") {
390 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
391 // NULL ~ default deallocator, so warn.
392 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
393 Expr::NPC_ValueDependentIsNotNull)) {
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 // One of the default allocators, so warn.
399 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
400 StringRef DeallocatorName = DE->getFoundDecl()->getName();
401 if (DeallocatorName == "kCFAllocatorDefault" ||
402 DeallocatorName == "kCFAllocatorSystemDefault" ||
403 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000404 const AllocationPair AP = std::make_pair(ArgSM, AS);
405 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000406 return;
407 }
408 // If kCFAllocatorNull, which does not deallocate, we still have to
409 // find the deallocator. Otherwise, assume that the user had written a
410 // custom deallocator which does the right thing.
411 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
412 State = State->remove<AllocatedData>(ArgSM);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000413 C.addTransition(State);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000414 return;
415 }
416 }
417 }
418 return;
419 }
420
Anna Zaks7d458b02011-08-15 23:23:15 +0000421 // The call is deallocating a value we previously allocated, so remove it
422 // from the next state.
423 State = State->remove<AllocatedData>(ArgSM);
424
Anna Zaksdd6060e2011-08-23 23:47:36 +0000425 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000426 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000427 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000428 const AllocationPair AP = std::make_pair(ArgSM, AS);
429 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000430 return;
431 }
432
Anna Zaksee5a21f2011-12-01 16:41:58 +0000433 // If the buffer can be null and the return status can be an error,
434 // report a bad call to free.
435 if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
436 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000437 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000438 if (!N)
439 return;
440 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000441 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000442 "Only call free if a valid (non-NULL) buffer was returned.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000443 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000444 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000445 Report->markInteresting(AS->Region);
Anna Zaks703ffb12011-08-12 21:56:43 +0000446 C.EmitReport(Report);
447 return;
448 }
449
Anna Zaks0bd6b112011-10-26 21:06:34 +0000450 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000451}
452
453void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
454 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000455 ProgramStateRef State = C.getState();
Anna Zaks0e12ebf2011-11-16 19:57:55 +0000456 StringRef funName = C.getCalleeName(CE);
Anna Zaksf57be282011-08-01 22:40:01 +0000457
458 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000459 unsigned idx = getTrackedFunctionIndex(funName, true);
460 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000461 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000462
Anna Zaks083fcb22011-08-04 17:28:06 +0000463 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000464 // If the argument entered as an enclosing function parameter, skip it to
465 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000466 if (isEnclosingFunctionParam(ArgExpr) &&
467 C.getLocationContext()->getParent() == 0)
Anna Zaks79c9c752011-08-12 22:47:22 +0000468 return;
469
Anna Zaks864d2522011-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 Zaks08551b52011-08-04 00:31:38 +0000473 // - unknown (cannot reason about it)
474 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000475 // - constant (null - should not be tracked,
476 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000477 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-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 Kremenek5eca4822012-01-06 22:09:28 +0000483 SymbolRef RetStatusSymbol =
484 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-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 Zaks864d2522011-08-12 21:14:26 +0000489 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000490 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000491 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000492 }
493}
494
495void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
496 CheckerContext &C) const {
497 const Expr *retExpr = S->getRetValue();
498 if (!retExpr)
499 return;
500
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000501 // If inside inlined call, skip it.
502 if (C.getLocationContext()->getParent() != 0)
503 return;
504
Anna Zaksf57be282011-08-01 22:40:01 +0000505 // Check if the value is escaping through the return.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000506 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000507 const MemRegion *V =
508 state->getSVal(retExpr, C.getLocationContext()).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000509 if (!V)
510 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000511 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000512
Anna Zaks03826aa2011-08-04 00:26:57 +0000513 // Proceed from the new state.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000514 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000515}
516
Anna Zaks721aa372012-02-28 03:07:06 +0000517// TODO: This logic is the same as in Malloc checker.
Anna Zaksd708bac2012-02-23 22:53:29 +0000518const Stmt *
519MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
520 SymbolRef Sym,
521 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000522 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000523 // Walk the ExplodedGraph backwards and find the first node that referred to
524 // the tracked symbol.
525 const ExplodedNode *AllocNode = N;
526
527 while (N) {
528 if (!N->getState()->get<AllocatedData>(Sym))
529 break;
Anna Zaks721aa372012-02-28 03:07:06 +0000530 // Allocation node, is the last node in the current context in which the
531 // symbol was tracked.
532 if (N->getLocationContext() == LeakContext)
533 AllocNode = N;
Anna Zaksd708bac2012-02-23 22:53:29 +0000534 N = N->pred_empty() ? NULL : *(N->pred_begin());
535 }
536
537 ProgramPoint P = AllocNode->getLocation();
Anna Zaks721aa372012-02-28 03:07:06 +0000538 if (!isa<StmtPoint>(P))
539 return 0;
Anna Zaksd708bac2012-02-23 22:53:29 +0000540 return cast<clang::PostStmt>(P).getStmt();
541}
542
Anna Zakse172e8b2011-08-17 23:00:25 +0000543BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000544 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000545 ExplodedNode *N,
546 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000547 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000548 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000549 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000550 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000551 os << "Allocated data is not released: missing a call to '"
552 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000553
554 // Most bug reports are cached at the location where they occurred.
555 // With leaks, we want to unique them by the location where they were
556 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000557 PathDiagnosticLocation LocUsedForUniqueing;
558 if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
559 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
560 C.getSourceManager(), N->getLocationContext());
Anna Zaksd708bac2012-02-23 22:53:29 +0000561
562 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
Anna Zaks98401112011-08-24 20:52:46 +0000563 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Ted Kremenek76aadc32012-03-09 01:13:14 +0000564 markInteresting(Report, AP);
Anna Zaks703ffb12011-08-12 21:56:43 +0000565 return Report;
566}
567
568void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
569 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000570 ProgramStateRef State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000571 AllocatedSetTy ASet = State->get<AllocatedData>();
572 if (ASet.isEmpty())
573 return;
574
575 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000576 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000577 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
578 if (SR.isLive(I->first))
579 continue;
580
581 Changed = true;
582 State = State->remove<AllocatedData>(I->first);
583 // If the allocated symbol is null or if the allocation call might have
584 // returned an error, do not report.
585 if (State->getSymVal(I->first) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000586 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000587 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000588 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000589 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000590 if (!Changed) {
591 // Generate the new, cleaned up state.
592 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000593 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000594 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000595
Anna Zaksd708bac2012-02-23 22:53:29 +0000596 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
597 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000598
599 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000600 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
601 I != E; ++I) {
Anna Zaksd708bac2012-02-23 22:53:29 +0000602 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000603 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000604
605 // Generate the new, cleaned up state.
606 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000607}
608
609// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksd708bac2012-02-23 22:53:29 +0000610void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
611 ProgramStateRef state = C.getState();
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000612
613 // If inside inlined call, skip it.
Anna Zaksd708bac2012-02-23 22:53:29 +0000614 if (C.getLocationContext()->getParent() != 0)
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000615 return;
616
Anna Zaksf57be282011-08-01 22:40:01 +0000617 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000618 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000619 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000620
621 // Anything which has been allocated but not freed (nor escaped) will be
622 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000623 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000624 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000625 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000626 Changed = true;
627 state = state->remove<AllocatedData>(I->first);
628 // If the allocated symbol is null or if error code was returned at
629 // allocation, do not report.
630 if (state->getSymVal(I.getKey()) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000631 definitelyReturnedError(I->second.Region, state,
Anna Zaksd708bac2012-02-23 22:53:29 +0000632 C.getSValBuilder())) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000633 continue;
634 }
Anna Zaks5eb7d822011-08-24 21:58:55 +0000635 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000636 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000637
638 // If no change, do not generate a new state.
Anna Zaksd708bac2012-02-23 22:53:29 +0000639 if (!Changed) {
640 C.addTransition(state);
Anna Zaks703ffb12011-08-12 21:56:43 +0000641 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000642 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000643
Anna Zaksd708bac2012-02-23 22:53:29 +0000644 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
645 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000646
647 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000648 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
649 I != E; ++I) {
Anna Zaksd708bac2012-02-23 22:53:29 +0000650 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000651 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000652
653 C.addTransition(state, N);
Anna Zaks98401112011-08-24 20:52:46 +0000654}
Anna Zaks703ffb12011-08-12 21:56:43 +0000655
Anna Zaks98401112011-08-24 20:52:46 +0000656
657PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
658 const ExplodedNode *N,
659 const ExplodedNode *PrevN,
660 BugReporterContext &BRC,
661 BugReport &BR) {
662 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
663 if (!AS)
664 return 0;
665 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
666 if (ASPrev)
667 return 0;
668
669 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
670 // allocation site.
671 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
672 .getStmt());
673 const FunctionDecl *funDecl = CE->getDirectCallee();
674 assert(funDecl && "We do not support indirect function calls as of now.");
675 StringRef funName = funDecl->getName();
676
677 // Get the expression of the corresponding argument.
678 unsigned Idx = getTrackedFunctionIndex(funName, true);
679 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
680 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000681 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
682 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000683 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000684}
685
686void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
687 mgr.registerChecker<MacOSKeychainAPIChecker>();
688}