blob: ce149b003f09b4ba4b4d843bfa63f4c8f1ac01a7 [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;
71 };
72 static const unsigned InvalidIdx = 100000;
Anna Zaks76cbb752011-08-04 21:53:01 +000073 static const unsigned FunctionsToTrackSize = 6;
Anna Zaks083fcb22011-08-04 17:28:06 +000074 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000075 /// The value, which represents no error return value for allocator functions.
76 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000077
Anna Zaks083fcb22011-08-04 17:28:06 +000078 /// Given the function name, returns the index of the allocator/deallocator
79 /// function.
80 unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const;
Anna Zaks03826aa2011-08-04 00:26:57 +000081
82 inline void initBugType() const {
83 if (!BT)
84 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
85 }
Anna Zaks703ffb12011-08-12 21:56:43 +000086
Anna Zakse172e8b2011-08-17 23:00:25 +000087 BugReport *generateAllocatedDataNotReleasedReport(const AllocationState &AS,
88 ExplodedNode *N) const;
Anna Zaks703ffb12011-08-12 21:56:43 +000089
90 /// Check if RetSym evaluates to an error value in the current state.
91 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000092 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +000093 SValBuilder &Builder,
94 bool noError = false) const;
95
96 /// Check if RetSym evaluates to a NoErr value in the current state.
97 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +000098 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +000099 SValBuilder &Builder) const {
100 return definitelyReturnedError(RetSym, State, Builder, true);
101 }
102
Anna Zaksf57be282011-08-01 22:40:01 +0000103};
104}
105
Anna Zaks7d458b02011-08-15 23:23:15 +0000106/// ProgramState traits to store the currently allocated (and not yet freed)
107/// symbols. This is a map from the allocated content symbol to the
108/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000109typedef llvm::ImmutableMap<SymbolRef,
110 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000111
112namespace { struct AllocatedData {}; }
113namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000114template<> struct ProgramStateTrait<AllocatedData>
115 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000116 static void *GDMIndex() { static int index = 0; return &index; }
117};
118}}
119
Anna Zaks03826aa2011-08-04 00:26:57 +0000120static bool isEnclosingFunctionParam(const Expr *E) {
121 E = E->IgnoreParenCasts();
122 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
123 const ValueDecl *VD = DRE->getDecl();
124 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
125 return true;
126 }
127 return false;
128}
129
Anna Zaks083fcb22011-08-04 17:28:06 +0000130const MacOSKeychainAPIChecker::ADFunctionInfo
131 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
132 {"SecKeychainItemCopyContent", 4, 3}, // 0
133 {"SecKeychainFindGenericPassword", 6, 3}, // 1
134 {"SecKeychainFindInternetPassword", 13, 3}, // 2
135 {"SecKeychainItemFreeContent", 1, InvalidIdx}, // 3
Anna Zaks76cbb752011-08-04 21:53:01 +0000136 {"SecKeychainItemCopyAttributesAndData", 5, 5}, // 4
137 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx}, // 5
Anna Zaks083fcb22011-08-04 17:28:06 +0000138};
139
140unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
141 bool IsAllocator) const {
142 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
143 ADFunctionInfo FI = FunctionsToTrack[I];
144 if (FI.Name != Name)
145 continue;
146 // Make sure the function is of the right type (allocator vs deallocator).
147 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
148 return InvalidIdx;
149 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
150 return InvalidIdx;
151
152 return I;
153 }
154 // The function is not tracked.
155 return InvalidIdx;
156}
157
Anna Zaks864d2522011-08-12 21:14:26 +0000158static SymbolRef getSymbolForRegion(CheckerContext &C,
159 const MemRegion *R) {
160 if (!isa<SymbolicRegion>(R))
161 return 0;
162 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000163}
164
Anna Zaks864d2522011-08-12 21:14:26 +0000165static bool isBadDeallocationArgument(const MemRegion *Arg) {
166 if (isa<AllocaRegion>(Arg) ||
167 isa<BlockDataRegion>(Arg) ||
168 isa<TypedRegion>(Arg)) {
169 return true;
170 }
171 return false;
172}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000173/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000174/// that value is itself an address, and return the corresponding symbol.
175static SymbolRef getAsPointeeSymbol(const Expr *Expr,
176 CheckerContext &C) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000177 const ProgramState *State = C.getState();
Anna Zaksca0b57e2011-08-05 00:37:00 +0000178 SVal ArgV = State->getSVal(Expr);
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000179
Anna Zaksca0b57e2011-08-05 00:37:00 +0000180 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
181 StoreManager& SM = C.getStoreManager();
182 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000183 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000184 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000185 }
186 return 0;
187}
188
Anna Zaks703ffb12011-08-12 21:56:43 +0000189// When checking for error code, we need to consider the following cases:
190// 1) noErr / [0]
191// 2) someErr / [1, inf]
192// 3) unknown
193// If noError, returns true iff (1).
194// If !noError, returns true iff (2).
195bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000196 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000197 SValBuilder &Builder,
198 bool noError) const {
199 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
200 Builder.getSymbolManager().getType(RetSym));
201 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
202 nonloc::SymbolVal(RetSym));
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000203 const ProgramState *ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000204 if (ErrState == State) {
205 return true;
206 }
207
208 return false;
209}
210
Anna Zaksf57be282011-08-01 22:40:01 +0000211void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
212 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000213 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000214 const Expr *Callee = CE->getCallee();
215 SVal L = State->getSVal(Callee);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000216 unsigned idx = InvalidIdx;
Anna Zaksf57be282011-08-01 22:40:01 +0000217
218 const FunctionDecl *funDecl = L.getAsFunctionDecl();
219 if (!funDecl)
220 return;
221 IdentifierInfo *funI = funDecl->getIdentifier();
222 if (!funI)
223 return;
224 StringRef funName = funI->getName();
225
Anna Zaksca0b57e2011-08-05 00:37:00 +0000226 // If it is a call to an allocator function, it could be a double allocation.
227 idx = getTrackedFunctionIndex(funName, true);
228 if (idx != InvalidIdx) {
229 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000230 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000231 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000232 if (!definitelyReturnedError(AS->RetValue, State, C.getSValBuilder())) {
233 // Remove the value from the state. The new symbol will be added for
234 // tracking when the second allocator is processed in checkPostStmt().
235 State = State->remove<AllocatedData>(V);
236 ExplodedNode *N = C.generateNode(State);
237 if (!N)
238 return;
239 initBugType();
240 llvm::SmallString<128> sbuf;
241 llvm::raw_svector_ostream os(sbuf);
242 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
243 os << "Allocated data should be released before another call to "
244 << "the allocator: missing a call to '"
245 << FunctionsToTrack[DIdx].Name
246 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000247 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000248 Report->addRange(ArgExpr->getSourceRange());
249 C.EmitReport(Report);
250 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000251 }
252 return;
253 }
254
255 // Is it a call to one of deallocator functions?
256 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000257 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000258 return;
259
Anna Zaks864d2522011-08-12 21:14:26 +0000260 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000261 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000262 SVal ArgSVal = State->getSVal(ArgExpr);
263
264 // Undef is reported by another checker.
265 if (ArgSVal.isUndef())
266 return;
267
268 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000269 if (!Arg)
270 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000271
272 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
273 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
274 // If the argument is coming from the heap, globals, or unknown, do not
275 // report it.
276 if (!ArgSM && !RegionArgIsBad)
277 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000278
Anna Zaks67f7fa42011-08-15 18:42:00 +0000279 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000280 // TODO: We might want a more precise diagnostic for double free
281 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000282 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
Anna Zaks864d2522011-08-12 21:14:26 +0000283 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000284 // It is possible that this is a false positive - the argument might
285 // have entered as an enclosing function parameter.
286 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000287 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000288
Anna Zaks08551b52011-08-04 00:31:38 +0000289 ExplodedNode *N = C.generateNode(State);
290 if (!N)
291 return;
292 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000293 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000294 "Trying to free data which has not been allocated.", N);
295 Report->addRange(ArgExpr->getSourceRange());
296 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000297 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000298 }
Anna Zaks08551b52011-08-04 00:31:38 +0000299
Anna Zaks7d458b02011-08-15 23:23:15 +0000300 // The call is deallocating a value we previously allocated, so remove it
301 // from the next state.
302 State = State->remove<AllocatedData>(ArgSM);
303
304 // Check if the proper deallocator is used. If not, report, but also stop
305 // tracking the allocated symbol to avoid reporting a missing free after the
306 // deallocator mismatch error.
Anna Zaks76cbb752011-08-04 21:53:01 +0000307 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
308 if (PDeallocIdx != idx) {
Anna Zaks7d458b02011-08-15 23:23:15 +0000309 ExplodedNode *N = C.generateNode(State);
Anna Zaks76cbb752011-08-04 21:53:01 +0000310 if (!N)
311 return;
312 initBugType();
313
Anna Zaks67f7fa42011-08-15 18:42:00 +0000314 llvm::SmallString<80> sbuf;
315 llvm::raw_svector_ostream os(sbuf);
Anna Zaks76cbb752011-08-04 21:53:01 +0000316 os << "Allocator doesn't match the deallocator: '"
317 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000318 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks76cbb752011-08-04 21:53:01 +0000319 Report->addRange(ArgExpr->getSourceRange());
320 C.EmitReport(Report);
321 return;
322 }
323
Anna Zaks703ffb12011-08-12 21:56:43 +0000324 // If the return status is undefined or is error, report a bad call to free.
325 if (!definitelyDidnotReturnError(AS->RetValue, State, C.getSValBuilder())) {
326 ExplodedNode *N = C.generateNode(State);
327 if (!N)
328 return;
329 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000330 BugReport *Report = new BugReport(*BT,
Anna Zaks703ffb12011-08-12 21:56:43 +0000331 "Call to free data when error was returned during allocation.", N);
332 Report->addRange(ArgExpr->getSourceRange());
333 C.EmitReport(Report);
334 return;
335 }
336
Anna Zaks08551b52011-08-04 00:31:38 +0000337 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000338}
339
340void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
341 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000342 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000343 const Expr *Callee = CE->getCallee();
344 SVal L = State->getSVal(Callee);
Anna Zaksf57be282011-08-01 22:40:01 +0000345
346 const FunctionDecl *funDecl = L.getAsFunctionDecl();
347 if (!funDecl)
348 return;
349 IdentifierInfo *funI = funDecl->getIdentifier();
350 if (!funI)
351 return;
352 StringRef funName = funI->getName();
353
354 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000355 unsigned idx = getTrackedFunctionIndex(funName, true);
356 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000357 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000358
Anna Zaks083fcb22011-08-04 17:28:06 +0000359 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000360 // If the argument entered as an enclosing function parameter, skip it to
361 // avoid false positives.
362 if (isEnclosingFunctionParam(ArgExpr))
363 return;
364
Anna Zaks864d2522011-08-12 21:14:26 +0000365 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
366 // If the argument points to something that's not a symbolic region, it
367 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000368 // - unknown (cannot reason about it)
369 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000370 // - constant (null - should not be tracked,
371 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000372 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000373
374 // The call return value symbol should stay alive for as long as the
375 // allocated value symbol, since our diagnostics depend on the value
376 // returned by the call. Ex: Data should only be freed if noErr was
377 // returned during allocation.)
Anna Zaks864d2522011-08-12 21:14:26 +0000378 SymbolRef RetStatusSymbol = State->getSVal(CE).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000379 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
380
381 // Track the allocated value in the checker state.
382 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000383 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000384 assert(State);
385 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000386 }
387}
388
389void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
390 CheckerContext &C) const {
391 const Expr *retExpr = S->getRetValue();
392 if (!retExpr)
393 return;
394
395 // Check if the value is escaping through the return.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000396 const ProgramState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000397 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000398 if (!V)
399 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000400 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000401
Anna Zaks03826aa2011-08-04 00:26:57 +0000402 // Proceed from the new state.
403 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000404}
405
Anna Zaks703ffb12011-08-12 21:56:43 +0000406// TODO: The report has to mention the expression which contains the
407// allocated content as well as the point at which it has been allocated.
Anna Zakse172e8b2011-08-17 23:00:25 +0000408BugReport *MacOSKeychainAPIChecker::
Anna Zaks703ffb12011-08-12 21:56:43 +0000409 generateAllocatedDataNotReleasedReport(const AllocationState &AS,
410 ExplodedNode *N) const {
411 const ADFunctionInfo &FI = FunctionsToTrack[AS.AllocatorIdx];
412 initBugType();
Anna Zaks67f7fa42011-08-15 18:42:00 +0000413 llvm::SmallString<70> sbuf;
414 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000415 os << "Allocated data is not released: missing a call to '"
416 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000417 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000418 Report->addRange(AS.Address->getSourceRange());
419 return Report;
420}
421
422void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
423 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000424 const ProgramState *State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000425 AllocatedSetTy ASet = State->get<AllocatedData>();
426 if (ASet.isEmpty())
427 return;
428
429 bool Changed = false;
430 llvm::SmallVector<const AllocationState*, 1> Errors;
431 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
432 if (SR.isLive(I->first))
433 continue;
434
435 Changed = true;
436 State = State->remove<AllocatedData>(I->first);
437 // If the allocated symbol is null or if the allocation call might have
438 // returned an error, do not report.
439 if (State->getSymVal(I->first) ||
440 definitelyReturnedError(I->second.RetValue, State, C.getSValBuilder()))
441 continue;
442 Errors.push_back(&I->second);
443 }
444 if (!Changed)
445 return;
446
447 // Generate the new, cleaned up state.
448 ExplodedNode *N = C.generateNode(State);
449 if (!N)
450 return;
451
452 // Generate the error reports.
453 for (llvm::SmallVector<const AllocationState*, 3>::iterator
454 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
455 C.EmitReport(generateAllocatedDataNotReleasedReport(**I, N));
456 }
457}
458
459// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksf57be282011-08-01 22:40:01 +0000460void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000461 ExprEngine &Eng) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000462 const ProgramState *state = B.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000463 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000464 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000465 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000466
467 // Anything which has been allocated but not freed (nor escaped) will be
468 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000469 bool Changed = false;
470 llvm::SmallVector<const AllocationState*, 1> Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000471 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000472 Changed = true;
473 state = state->remove<AllocatedData>(I->first);
474 // If the allocated symbol is null or if error code was returned at
475 // allocation, do not report.
476 if (state->getSymVal(I.getKey()) ||
477 definitelyReturnedError(I->second.RetValue, state,
478 Eng.getSValBuilder())) {
479 continue;
480 }
481 Errors.push_back(&I->second);
Anna Zaksf57be282011-08-01 22:40:01 +0000482 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000483
484 // If no change, do not generate a new state.
485 if (!Changed)
486 return;
487
488 ExplodedNode *N = B.generateNode(state);
489 if (!N)
490 return;
491
492 // Generate the error reports.
493 for (llvm::SmallVector<const AllocationState*, 3>::iterator
494 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
495 Eng.getBugReporter().EmitReport(
496 generateAllocatedDataNotReleasedReport(**I, N));
497 }
498
Anna Zaksf57be282011-08-01 22:40:01 +0000499}
500
501void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
502 mgr.registerChecker<MacOSKeychainAPIChecker>();
503}