blob: 83eff9d1d4f062496f28ecac6e23c91fdaa19f84 [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 Zaksaf498a22011-10-25 19:56:48 +000062 void checkEndPath(CheckerContext &Ctx) 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 Zaks98401112011-08-24 20:52:46 +0000104 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zakse172e8b2011-08-17 23:00:25 +0000105 ExplodedNode *N) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000106
107 /// Check if RetSym evaluates to an error value in the current state.
108 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000109 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000110 SValBuilder &Builder,
111 bool noError = false) const;
112
113 /// Check if RetSym evaluates to a NoErr value in the current state.
114 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000115 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000116 SValBuilder &Builder) const {
117 return definitelyReturnedError(RetSym, State, Builder, true);
118 }
119
Anna Zaks98401112011-08-24 20:52:46 +0000120 /// The bug visitor which allows us to print extra diagnostics along the
121 /// BugReport path. For example, showing the allocation site of the leaked
122 /// region.
123 class SecKeychainBugVisitor : public BugReporterVisitor {
124 protected:
125 // The allocated region symbol tracked by the main analysis.
126 SymbolRef Sym;
127
128 public:
129 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
130 virtual ~SecKeychainBugVisitor() {}
131
132 void Profile(llvm::FoldingSetNodeID &ID) const {
133 static int X = 0;
134 ID.AddPointer(&X);
135 ID.AddPointer(Sym);
136 }
137
138 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
139 const ExplodedNode *PrevN,
140 BugReporterContext &BRC,
141 BugReport &BR);
142 };
Anna Zaksf57be282011-08-01 22:40:01 +0000143};
144}
145
Anna Zaks7d458b02011-08-15 23:23:15 +0000146/// ProgramState traits to store the currently allocated (and not yet freed)
147/// symbols. This is a map from the allocated content symbol to the
148/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000149typedef llvm::ImmutableMap<SymbolRef,
150 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000151
152namespace { struct AllocatedData {}; }
153namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000154template<> struct ProgramStateTrait<AllocatedData>
155 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000156 static void *GDMIndex() { static int index = 0; return &index; }
157};
158}}
159
Anna Zaks03826aa2011-08-04 00:26:57 +0000160static bool isEnclosingFunctionParam(const Expr *E) {
161 E = E->IgnoreParenCasts();
162 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
163 const ValueDecl *VD = DRE->getDecl();
164 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
165 return true;
166 }
167 return false;
168}
169
Anna Zaks083fcb22011-08-04 17:28:06 +0000170const MacOSKeychainAPIChecker::ADFunctionInfo
171 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000172 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
173 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
174 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
175 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
176 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
177 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
178 {"free", 0, InvalidIdx, ErrorAPI}, // 6
179 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000180};
181
182unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000183 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000184 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
185 ADFunctionInfo FI = FunctionsToTrack[I];
186 if (FI.Name != Name)
187 continue;
188 // Make sure the function is of the right type (allocator vs deallocator).
189 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
190 return InvalidIdx;
191 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
192 return InvalidIdx;
193
194 return I;
195 }
196 // The function is not tracked.
197 return InvalidIdx;
198}
199
Anna Zaks864d2522011-08-12 21:14:26 +0000200static SymbolRef getSymbolForRegion(CheckerContext &C,
201 const MemRegion *R) {
Anna Zaks065a4052011-08-29 21:10:00 +0000202 // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
203 // region, if that is the case, get the underlining region.
204 R = R->StripCasts();
Anna Zaks31e10282011-08-23 23:56:12 +0000205 if (!isa<SymbolicRegion>(R)) {
Anna Zaks31e10282011-08-23 23:56:12 +0000206 return 0;
207 }
Anna Zaks864d2522011-08-12 21:14:26 +0000208 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000209}
210
Anna Zaks864d2522011-08-12 21:14:26 +0000211static bool isBadDeallocationArgument(const MemRegion *Arg) {
212 if (isa<AllocaRegion>(Arg) ||
213 isa<BlockDataRegion>(Arg) ||
214 isa<TypedRegion>(Arg)) {
215 return true;
216 }
217 return false;
218}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000219/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000220/// that value is itself an address, and return the corresponding symbol.
221static SymbolRef getAsPointeeSymbol(const Expr *Expr,
222 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000223 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000224 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000225
Anna Zaksca0b57e2011-08-05 00:37:00 +0000226 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
227 StoreManager& SM = C.getStoreManager();
Anna Zaks14374252012-01-12 02:22:40 +0000228 const MemRegion *V = SM.getBinding(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000229 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000230 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000231 }
232 return 0;
233}
234
Anna Zaks703ffb12011-08-12 21:56:43 +0000235// When checking for error code, we need to consider the following cases:
236// 1) noErr / [0]
237// 2) someErr / [1, inf]
238// 3) unknown
239// If noError, returns true iff (1).
240// If !noError, returns true iff (2).
241bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000242 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000243 SValBuilder &Builder,
244 bool noError) const {
245 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
246 Builder.getSymbolManager().getType(RetSym));
247 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
248 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000249 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000250 if (ErrState == State) {
251 return true;
252 }
253
254 return false;
255}
256
Anna Zaksdd6060e2011-08-23 23:47:36 +0000257// Report deallocator mismatch. Remove the region from tracking - reporting a
258// missing free error after this one is redundant.
259void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000260 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000261 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000262 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000263 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000264 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000265 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000266
267 if (!N)
268 return;
269 initBugType();
270 llvm::SmallString<80> sbuf;
271 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000272 unsigned int PDeallocIdx =
273 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000274
275 os << "Deallocator doesn't match the allocator: '"
276 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
277 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000278 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000279 Report->addRange(ArgExpr->getSourceRange());
280 C.EmitReport(Report);
281}
282
Anna Zaksf57be282011-08-01 22:40:01 +0000283void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
284 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000285 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000286 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000287
Anna Zaksb805c8f2011-12-01 05:57:37 +0000288 StringRef funName = C.getCalleeName(CE);
289 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000290 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000291
Anna Zaksca0b57e2011-08-05 00:37:00 +0000292 // If it is a call to an allocator function, it could be a double allocation.
293 idx = getTrackedFunctionIndex(funName, true);
294 if (idx != InvalidIdx) {
295 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000296 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000297 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000298 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000299 // Remove the value from the state. The new symbol will be added for
300 // tracking when the second allocator is processed in checkPostStmt().
301 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000302 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000303 if (!N)
304 return;
305 initBugType();
306 llvm::SmallString<128> sbuf;
307 llvm::raw_svector_ostream os(sbuf);
308 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
309 os << "Allocated data should be released before another call to "
310 << "the allocator: missing a call to '"
311 << FunctionsToTrack[DIdx].Name
312 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000313 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000314 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000315 Report->addRange(ArgExpr->getSourceRange());
316 C.EmitReport(Report);
317 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000318 }
319 return;
320 }
321
322 // Is it a call to one of deallocator functions?
323 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000324 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000325 return;
326
Anna Zaks864d2522011-08-12 21:14:26 +0000327 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000328 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000329 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000330
331 // Undef is reported by another checker.
332 if (ArgSVal.isUndef())
333 return;
334
335 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000336 if (!Arg)
337 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000338
339 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
340 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
341 // If the argument is coming from the heap, globals, or unknown, do not
342 // report it.
343 if (!ArgSM && !RegionArgIsBad)
344 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000345
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000346 // Is the argument to the call being tracked?
347 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
348 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
349 return;
350 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000351 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000352 // TODO: We might want a more precise diagnostic for double free
353 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000354 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000355 // It is possible that this is a false positive - the argument might
356 // have entered as an enclosing function parameter.
357 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000358 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000359
Anna Zaks0bd6b112011-10-26 21:06:34 +0000360 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000361 if (!N)
362 return;
363 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000364 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000365 "Trying to free data which has not been allocated.", N);
366 Report->addRange(ArgExpr->getSourceRange());
367 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000368 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000369 }
Anna Zaks08551b52011-08-04 00:31:38 +0000370
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000371 // Process functions which might deallocate.
372 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
373
374 if (funName == "CFStringCreateWithBytesNoCopy") {
375 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
376 // NULL ~ default deallocator, so warn.
377 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
378 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000379 const AllocationPair AP = std::make_pair(ArgSM, AS);
380 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000381 return;
382 }
383 // One of the default allocators, so warn.
384 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
385 StringRef DeallocatorName = DE->getFoundDecl()->getName();
386 if (DeallocatorName == "kCFAllocatorDefault" ||
387 DeallocatorName == "kCFAllocatorSystemDefault" ||
388 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000389 const AllocationPair AP = std::make_pair(ArgSM, AS);
390 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000391 return;
392 }
393 // If kCFAllocatorNull, which does not deallocate, we still have to
394 // find the deallocator. Otherwise, assume that the user had written a
395 // custom deallocator which does the right thing.
396 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
397 State = State->remove<AllocatedData>(ArgSM);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000398 C.addTransition(State);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000399 return;
400 }
401 }
402 }
403 return;
404 }
405
Anna Zaks7d458b02011-08-15 23:23:15 +0000406 // The call is deallocating a value we previously allocated, so remove it
407 // from the next state.
408 State = State->remove<AllocatedData>(ArgSM);
409
Anna Zaksdd6060e2011-08-23 23:47:36 +0000410 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000411 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000412 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000413 const AllocationPair AP = std::make_pair(ArgSM, AS);
414 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000415 return;
416 }
417
Anna Zaksee5a21f2011-12-01 16:41:58 +0000418 // If the buffer can be null and the return status can be an error,
419 // report a bad call to free.
420 if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
421 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000422 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000423 if (!N)
424 return;
425 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000426 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000427 "Only call free if a valid (non-NULL) buffer was returned.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000428 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000429 Report->addRange(ArgExpr->getSourceRange());
430 C.EmitReport(Report);
431 return;
432 }
433
Anna Zaks0bd6b112011-10-26 21:06:34 +0000434 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000435}
436
437void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
438 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000439 ProgramStateRef State = C.getState();
Anna Zaks0e12ebf2011-11-16 19:57:55 +0000440 StringRef funName = C.getCalleeName(CE);
Anna Zaksf57be282011-08-01 22:40:01 +0000441
442 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000443 unsigned idx = getTrackedFunctionIndex(funName, true);
444 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000445 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000446
Anna Zaks083fcb22011-08-04 17:28:06 +0000447 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000448 // If the argument entered as an enclosing function parameter, skip it to
449 // avoid false positives.
450 if (isEnclosingFunctionParam(ArgExpr))
451 return;
452
Anna Zaks864d2522011-08-12 21:14:26 +0000453 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
454 // If the argument points to something that's not a symbolic region, it
455 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000456 // - unknown (cannot reason about it)
457 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000458 // - constant (null - should not be tracked,
459 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000460 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000461
462 // The call return value symbol should stay alive for as long as the
463 // allocated value symbol, since our diagnostics depend on the value
464 // returned by the call. Ex: Data should only be freed if noErr was
465 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000466 SymbolRef RetStatusSymbol =
467 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000468 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
469
470 // Track the allocated value in the checker state.
471 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000472 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000473 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000474 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000475 }
476}
477
478void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
479 CheckerContext &C) const {
480 const Expr *retExpr = S->getRetValue();
481 if (!retExpr)
482 return;
483
484 // Check if the value is escaping through the return.
Ted Kremenek8bef8232012-01-26 21:29:00 +0000485 ProgramStateRef state = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000486 const MemRegion *V =
487 state->getSVal(retExpr, C.getLocationContext()).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000488 if (!V)
489 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000490 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000491
Anna Zaks03826aa2011-08-04 00:26:57 +0000492 // Proceed from the new state.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000493 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000494}
495
Anna Zakse172e8b2011-08-17 23:00:25 +0000496BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000497 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaks703ffb12011-08-12 21:56:43 +0000498 ExplodedNode *N) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000499 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000500 initBugType();
Anna Zaks67f7fa42011-08-15 18:42:00 +0000501 llvm::SmallString<70> sbuf;
502 llvm::raw_svector_ostream os(sbuf);
Anna Zaks98401112011-08-24 20:52:46 +0000503
Anna Zaks703ffb12011-08-12 21:56:43 +0000504 os << "Allocated data is not released: missing a call to '"
505 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000506 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks98401112011-08-24 20:52:46 +0000507 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
508 Report->addRange(SourceRange());
Anna Zaks703ffb12011-08-12 21:56:43 +0000509 return Report;
510}
511
512void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
513 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000514 ProgramStateRef State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000515 AllocatedSetTy ASet = State->get<AllocatedData>();
516 if (ASet.isEmpty())
517 return;
518
519 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000520 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000521 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
522 if (SR.isLive(I->first))
523 continue;
524
525 Changed = true;
526 State = State->remove<AllocatedData>(I->first);
527 // If the allocated symbol is null or if the allocation call might have
528 // returned an error, do not report.
529 if (State->getSymVal(I->first) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000530 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000531 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000532 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000533 }
534 if (!Changed)
535 return;
536
537 // Generate the new, cleaned up state.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000538 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000539 if (!N)
540 return;
541
542 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000543 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
544 I != E; ++I) {
545 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000546 }
547}
548
549// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksaf498a22011-10-25 19:56:48 +0000550void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &Ctx) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000551 ProgramStateRef state = Ctx.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000552 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000553 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000554 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000555
556 // Anything which has been allocated but not freed (nor escaped) will be
557 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000558 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000559 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000560 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000561 Changed = true;
562 state = state->remove<AllocatedData>(I->first);
563 // If the allocated symbol is null or if error code was returned at
564 // allocation, do not report.
565 if (state->getSymVal(I.getKey()) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000566 definitelyReturnedError(I->second.Region, state,
Anna Zaksaf498a22011-10-25 19:56:48 +0000567 Ctx.getSValBuilder())) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000568 continue;
569 }
Anna Zaks5eb7d822011-08-24 21:58:55 +0000570 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000571 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000572
573 // If no change, do not generate a new state.
574 if (!Changed)
575 return;
576
Anna Zaks0bd6b112011-10-26 21:06:34 +0000577 ExplodedNode *N = Ctx.addTransition(state);
Anna Zaks703ffb12011-08-12 21:56:43 +0000578 if (!N)
579 return;
580
581 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000582 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
583 I != E; ++I) {
Anna Zaksaf498a22011-10-25 19:56:48 +0000584 Ctx.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000585 }
Anna Zaks98401112011-08-24 20:52:46 +0000586}
Anna Zaks703ffb12011-08-12 21:56:43 +0000587
Anna Zaks98401112011-08-24 20:52:46 +0000588
589PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
590 const ExplodedNode *N,
591 const ExplodedNode *PrevN,
592 BugReporterContext &BRC,
593 BugReport &BR) {
594 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
595 if (!AS)
596 return 0;
597 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
598 if (ASPrev)
599 return 0;
600
601 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
602 // allocation site.
603 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
604 .getStmt());
605 const FunctionDecl *funDecl = CE->getDirectCallee();
606 assert(funDecl && "We do not support indirect function calls as of now.");
607 StringRef funName = funDecl->getName();
608
609 // Get the expression of the corresponding argument.
610 unsigned Idx = getTrackedFunctionIndex(funName, true);
611 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
612 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000613 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
614 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000615 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000616}
617
618void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
619 mgr.registerChecker<MacOSKeychainAPIChecker>();
620}