blob: 086f365201dfc498a209f6da5ad9f039b7cafd73 [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"
Anna Zaksf57be282011-08-01 22:40:01 +000022
23using namespace clang;
24using namespace ento;
25
26namespace {
27class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
28 check::PreStmt<ReturnStmt>,
29 check::PostStmt<CallExpr>,
Anna Zaks703ffb12011-08-12 21:56:43 +000030 check::EndPath,
31 check::DeadSymbols> {
Anna Zaks03826aa2011-08-04 00:26:57 +000032 mutable llvm::OwningPtr<BugType> BT;
33
Anna Zaksf57be282011-08-01 22:40:01 +000034public:
Anna Zaks864d2522011-08-12 21:14:26 +000035 /// AllocationState is a part of the checker specific state together with the
36 /// MemRegion corresponding to the allocated data.
37 struct AllocationState {
38 const Expr *Address;
39 /// The index of the allocator function.
40 unsigned int AllocatorIdx;
41 SymbolRef RetValue;
42
43 AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
44 Address(E),
45 AllocatorIdx(Idx),
46 RetValue(R) {}
47
48 bool operator==(const AllocationState &X) const {
49 return Address == X.Address;
50 }
51 void Profile(llvm::FoldingSetNodeID &ID) const {
52 ID.AddPointer(Address);
53 ID.AddInteger(AllocatorIdx);
54 }
55 };
56
Anna Zaksf57be282011-08-01 22:40:01 +000057 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
58 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
59 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
60
Anna Zaks703ffb12011-08-12 21:56:43 +000061 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000062 void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
63
64private:
Anna Zaks083fcb22011-08-04 17:28:06 +000065 /// Stores the information about the allocator and deallocator functions -
66 /// these are the functions the checker is tracking.
67 struct ADFunctionInfo {
68 const char* Name;
69 unsigned int Param;
70 unsigned int DeallocatorIdx;
Anna Zaks7bbd1662011-08-22 23:18:12 +000071 /// The flag specifies if the call is valid or is a result of a common user
72 /// error (Ex: free instead of SecKeychainItemFreeContent), which we also
73 /// track for better diagnostics.
74 bool isValid;
Anna Zaks083fcb22011-08-04 17:28:06 +000075 };
76 static const unsigned InvalidIdx = 100000;
Anna Zaks7bbd1662011-08-22 23:18:12 +000077 static const unsigned FunctionsToTrackSize = 7;
Anna Zaks083fcb22011-08-04 17:28:06 +000078 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000079 /// The value, which represents no error return value for allocator functions.
80 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000081
Anna Zaks083fcb22011-08-04 17:28:06 +000082 /// Given the function name, returns the index of the allocator/deallocator
83 /// function.
84 unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const;
Anna Zaks03826aa2011-08-04 00:26:57 +000085
86 inline void initBugType() const {
87 if (!BT)
88 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
89 }
Anna Zaks703ffb12011-08-12 21:56:43 +000090
Anna Zakse172e8b2011-08-17 23:00:25 +000091 BugReport *generateAllocatedDataNotReleasedReport(const AllocationState &AS,
92 ExplodedNode *N) const;
Anna Zaks703ffb12011-08-12 21:56:43 +000093
94 /// Check if RetSym evaluates to an error value in the current state.
95 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000096 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +000097 SValBuilder &Builder,
98 bool noError = false) const;
99
100 /// Check if RetSym evaluates to a NoErr value in the current state.
101 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000102 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000103 SValBuilder &Builder) const {
104 return definitelyReturnedError(RetSym, State, Builder, true);
105 }
106
Anna Zaksf57be282011-08-01 22:40:01 +0000107};
108}
109
Anna Zaks7d458b02011-08-15 23:23:15 +0000110/// ProgramState traits to store the currently allocated (and not yet freed)
111/// symbols. This is a map from the allocated content symbol to the
112/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000113typedef llvm::ImmutableMap<SymbolRef,
114 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000115
116namespace { struct AllocatedData {}; }
117namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000118template<> struct ProgramStateTrait<AllocatedData>
119 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000120 static void *GDMIndex() { static int index = 0; return &index; }
121};
122}}
123
Anna Zaks03826aa2011-08-04 00:26:57 +0000124static bool isEnclosingFunctionParam(const Expr *E) {
125 E = E->IgnoreParenCasts();
126 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
127 const ValueDecl *VD = DRE->getDecl();
128 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
129 return true;
130 }
131 return false;
132}
133
Anna Zaks083fcb22011-08-04 17:28:06 +0000134const MacOSKeychainAPIChecker::ADFunctionInfo
135 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks7bbd1662011-08-22 23:18:12 +0000136 {"SecKeychainItemCopyContent", 4, 3, true}, // 0
137 {"SecKeychainFindGenericPassword", 6, 3, true}, // 1
138 {"SecKeychainFindInternetPassword", 13, 3, true}, // 2
139 {"SecKeychainItemFreeContent", 1, InvalidIdx, true}, // 3
140 {"SecKeychainItemCopyAttributesAndData", 5, 5, true}, // 4
141 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, true}, // 5
142 {"free", 0, InvalidIdx, false}, // 6
Anna Zaks083fcb22011-08-04 17:28:06 +0000143};
144
145unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
146 bool IsAllocator) const {
147 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
148 ADFunctionInfo FI = FunctionsToTrack[I];
149 if (FI.Name != Name)
150 continue;
151 // Make sure the function is of the right type (allocator vs deallocator).
152 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
153 return InvalidIdx;
154 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
155 return InvalidIdx;
156
157 return I;
158 }
159 // The function is not tracked.
160 return InvalidIdx;
161}
162
Anna Zaks864d2522011-08-12 21:14:26 +0000163static SymbolRef getSymbolForRegion(CheckerContext &C,
164 const MemRegion *R) {
165 if (!isa<SymbolicRegion>(R))
166 return 0;
167 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000168}
169
Anna Zaks864d2522011-08-12 21:14:26 +0000170static bool isBadDeallocationArgument(const MemRegion *Arg) {
171 if (isa<AllocaRegion>(Arg) ||
172 isa<BlockDataRegion>(Arg) ||
173 isa<TypedRegion>(Arg)) {
174 return true;
175 }
176 return false;
177}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000178/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000179/// that value is itself an address, and return the corresponding symbol.
180static SymbolRef getAsPointeeSymbol(const Expr *Expr,
181 CheckerContext &C) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000182 const ProgramState *State = C.getState();
Anna Zaksca0b57e2011-08-05 00:37:00 +0000183 SVal ArgV = State->getSVal(Expr);
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000184
Anna Zaksca0b57e2011-08-05 00:37:00 +0000185 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
186 StoreManager& SM = C.getStoreManager();
187 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000188 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000189 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000190 }
191 return 0;
192}
193
Anna Zaks703ffb12011-08-12 21:56:43 +0000194// When checking for error code, we need to consider the following cases:
195// 1) noErr / [0]
196// 2) someErr / [1, inf]
197// 3) unknown
198// If noError, returns true iff (1).
199// If !noError, returns true iff (2).
200bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000201 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000202 SValBuilder &Builder,
203 bool noError) const {
204 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
205 Builder.getSymbolManager().getType(RetSym));
206 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
207 nonloc::SymbolVal(RetSym));
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000208 const ProgramState *ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000209 if (ErrState == State) {
210 return true;
211 }
212
213 return false;
214}
215
Anna Zaksf57be282011-08-01 22:40:01 +0000216void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
217 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000218 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000219 const Expr *Callee = CE->getCallee();
220 SVal L = State->getSVal(Callee);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000221 unsigned idx = InvalidIdx;
Anna Zaksf57be282011-08-01 22:40:01 +0000222
223 const FunctionDecl *funDecl = L.getAsFunctionDecl();
224 if (!funDecl)
225 return;
226 IdentifierInfo *funI = funDecl->getIdentifier();
227 if (!funI)
228 return;
229 StringRef funName = funI->getName();
230
Anna Zaksca0b57e2011-08-05 00:37:00 +0000231 // If it is a call to an allocator function, it could be a double allocation.
232 idx = getTrackedFunctionIndex(funName, true);
233 if (idx != InvalidIdx) {
234 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000235 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000236 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000237 if (!definitelyReturnedError(AS->RetValue, State, C.getSValBuilder())) {
238 // Remove the value from the state. The new symbol will be added for
239 // tracking when the second allocator is processed in checkPostStmt().
240 State = State->remove<AllocatedData>(V);
241 ExplodedNode *N = C.generateNode(State);
242 if (!N)
243 return;
244 initBugType();
245 llvm::SmallString<128> sbuf;
246 llvm::raw_svector_ostream os(sbuf);
247 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
248 os << "Allocated data should be released before another call to "
249 << "the allocator: missing a call to '"
250 << FunctionsToTrack[DIdx].Name
251 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000252 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000253 Report->addRange(ArgExpr->getSourceRange());
254 C.EmitReport(Report);
255 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000256 }
257 return;
258 }
259
260 // Is it a call to one of deallocator functions?
261 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000262 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000263 return;
264
Anna Zaks7bbd1662011-08-22 23:18:12 +0000265 // We also track invalid deallocators. Ex: free() for enhanced error messages.
266 bool isValidDeallocator = FunctionsToTrack[idx].isValid;
267
Anna Zaks864d2522011-08-12 21:14:26 +0000268 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000269 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000270 SVal ArgSVal = State->getSVal(ArgExpr);
271
272 // Undef is reported by another checker.
273 if (ArgSVal.isUndef())
274 return;
275
276 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000277 if (!Arg)
278 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000279
280 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
281 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
282 // If the argument is coming from the heap, globals, or unknown, do not
283 // report it.
284 if (!ArgSM && !RegionArgIsBad)
285 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000286
Anna Zaks67f7fa42011-08-15 18:42:00 +0000287 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000288 // TODO: We might want a more precise diagnostic for double free
289 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000290 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
Anna Zaks7bbd1662011-08-22 23:18:12 +0000291 if ((!AS || RegionArgIsBad) && isValidDeallocator) {
Anna Zaks08551b52011-08-04 00:31:38 +0000292 // It is possible that this is a false positive - the argument might
293 // have entered as an enclosing function parameter.
294 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000295 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000296
Anna Zaks08551b52011-08-04 00:31:38 +0000297 ExplodedNode *N = C.generateNode(State);
298 if (!N)
299 return;
300 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000301 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000302 "Trying to free data which has not been allocated.", N);
303 Report->addRange(ArgExpr->getSourceRange());
304 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000305 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000306 }
Anna Zaks08551b52011-08-04 00:31:38 +0000307
Anna Zaks7d458b02011-08-15 23:23:15 +0000308 // The call is deallocating a value we previously allocated, so remove it
309 // from the next state.
310 State = State->remove<AllocatedData>(ArgSM);
311
312 // Check if the proper deallocator is used. If not, report, but also stop
313 // tracking the allocated symbol to avoid reporting a missing free after the
314 // deallocator mismatch error.
Anna Zaks76cbb752011-08-04 21:53:01 +0000315 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks7bbd1662011-08-22 23:18:12 +0000316 if (PDeallocIdx != idx || !isValidDeallocator) {
Anna Zaks7d458b02011-08-15 23:23:15 +0000317 ExplodedNode *N = C.generateNode(State);
Anna Zaks76cbb752011-08-04 21:53:01 +0000318 if (!N)
319 return;
320 initBugType();
321
Anna Zaks67f7fa42011-08-15 18:42:00 +0000322 llvm::SmallString<80> sbuf;
323 llvm::raw_svector_ostream os(sbuf);
Anna Zaks7bbd1662011-08-22 23:18:12 +0000324 os << "Deallocator doesn't match the allocator: '"
Anna Zaks76cbb752011-08-04 21:53:01 +0000325 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000326 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks76cbb752011-08-04 21:53:01 +0000327 Report->addRange(ArgExpr->getSourceRange());
328 C.EmitReport(Report);
329 return;
330 }
331
Anna Zaks703ffb12011-08-12 21:56:43 +0000332 // If the return status is undefined or is error, report a bad call to free.
333 if (!definitelyDidnotReturnError(AS->RetValue, State, C.getSValBuilder())) {
334 ExplodedNode *N = C.generateNode(State);
335 if (!N)
336 return;
337 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000338 BugReport *Report = new BugReport(*BT,
Anna Zaks703ffb12011-08-12 21:56:43 +0000339 "Call to free data when error was returned during allocation.", N);
340 Report->addRange(ArgExpr->getSourceRange());
341 C.EmitReport(Report);
342 return;
343 }
344
Anna Zaks08551b52011-08-04 00:31:38 +0000345 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000346}
347
348void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
349 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000350 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000351 const Expr *Callee = CE->getCallee();
352 SVal L = State->getSVal(Callee);
Anna Zaksf57be282011-08-01 22:40:01 +0000353
354 const FunctionDecl *funDecl = L.getAsFunctionDecl();
355 if (!funDecl)
356 return;
357 IdentifierInfo *funI = funDecl->getIdentifier();
358 if (!funI)
359 return;
360 StringRef funName = funI->getName();
361
362 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000363 unsigned idx = getTrackedFunctionIndex(funName, true);
364 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000365 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000366
Anna Zaks083fcb22011-08-04 17:28:06 +0000367 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000368 // If the argument entered as an enclosing function parameter, skip it to
369 // avoid false positives.
370 if (isEnclosingFunctionParam(ArgExpr))
371 return;
372
Anna Zaks864d2522011-08-12 21:14:26 +0000373 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
374 // If the argument points to something that's not a symbolic region, it
375 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000376 // - unknown (cannot reason about it)
377 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000378 // - constant (null - should not be tracked,
379 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000380 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000381
382 // The call return value symbol should stay alive for as long as the
383 // allocated value symbol, since our diagnostics depend on the value
384 // returned by the call. Ex: Data should only be freed if noErr was
385 // returned during allocation.)
Anna Zaks864d2522011-08-12 21:14:26 +0000386 SymbolRef RetStatusSymbol = State->getSVal(CE).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000387 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
388
389 // Track the allocated value in the checker state.
390 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000391 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000392 assert(State);
393 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000394 }
395}
396
397void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
398 CheckerContext &C) const {
399 const Expr *retExpr = S->getRetValue();
400 if (!retExpr)
401 return;
402
403 // Check if the value is escaping through the return.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000404 const ProgramState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000405 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000406 if (!V)
407 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000408 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000409
Anna Zaks03826aa2011-08-04 00:26:57 +0000410 // Proceed from the new state.
411 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000412}
413
Anna Zaks703ffb12011-08-12 21:56:43 +0000414// TODO: The report has to mention the expression which contains the
415// allocated content as well as the point at which it has been allocated.
Anna Zakse172e8b2011-08-17 23:00:25 +0000416BugReport *MacOSKeychainAPIChecker::
Anna Zaks703ffb12011-08-12 21:56:43 +0000417 generateAllocatedDataNotReleasedReport(const AllocationState &AS,
418 ExplodedNode *N) const {
419 const ADFunctionInfo &FI = FunctionsToTrack[AS.AllocatorIdx];
420 initBugType();
Anna Zaks67f7fa42011-08-15 18:42:00 +0000421 llvm::SmallString<70> sbuf;
422 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000423 os << "Allocated data is not released: missing a call to '"
424 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000425 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000426 Report->addRange(AS.Address->getSourceRange());
427 return Report;
428}
429
430void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
431 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000432 const ProgramState *State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000433 AllocatedSetTy ASet = State->get<AllocatedData>();
434 if (ASet.isEmpty())
435 return;
436
437 bool Changed = false;
438 llvm::SmallVector<const AllocationState*, 1> Errors;
439 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
440 if (SR.isLive(I->first))
441 continue;
442
443 Changed = true;
444 State = State->remove<AllocatedData>(I->first);
445 // If the allocated symbol is null or if the allocation call might have
446 // returned an error, do not report.
447 if (State->getSymVal(I->first) ||
448 definitelyReturnedError(I->second.RetValue, State, C.getSValBuilder()))
449 continue;
450 Errors.push_back(&I->second);
451 }
452 if (!Changed)
453 return;
454
455 // Generate the new, cleaned up state.
456 ExplodedNode *N = C.generateNode(State);
457 if (!N)
458 return;
459
460 // Generate the error reports.
461 for (llvm::SmallVector<const AllocationState*, 3>::iterator
462 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
463 C.EmitReport(generateAllocatedDataNotReleasedReport(**I, N));
464 }
465}
466
467// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksf57be282011-08-01 22:40:01 +0000468void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000469 ExprEngine &Eng) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000470 const ProgramState *state = B.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000471 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000472 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000473 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000474
475 // Anything which has been allocated but not freed (nor escaped) will be
476 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000477 bool Changed = false;
478 llvm::SmallVector<const AllocationState*, 1> Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000479 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000480 Changed = true;
481 state = state->remove<AllocatedData>(I->first);
482 // If the allocated symbol is null or if error code was returned at
483 // allocation, do not report.
484 if (state->getSymVal(I.getKey()) ||
485 definitelyReturnedError(I->second.RetValue, state,
486 Eng.getSValBuilder())) {
487 continue;
488 }
489 Errors.push_back(&I->second);
Anna Zaksf57be282011-08-01 22:40:01 +0000490 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000491
492 // If no change, do not generate a new state.
493 if (!Changed)
494 return;
495
496 ExplodedNode *N = B.generateNode(state);
497 if (!N)
498 return;
499
500 // Generate the error reports.
501 for (llvm::SmallVector<const AllocationState*, 3>::iterator
502 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
503 Eng.getBugReporter().EmitReport(
504 generateAllocatedDataNotReleasedReport(**I, N));
505 }
506
Anna Zaksf57be282011-08-01 22:40:01 +0000507}
508
509void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
510 mgr.registerChecker<MacOSKeychainAPIChecker>();
511}