blob: 936e2477c083d63e3fcc671891d06c872d2e293d [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 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 Kremenek18c66fd2011-08-15 22:09:50 +0000109 const ProgramState *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 Kremenek18c66fd2011-08-15 22:09:50 +0000115 const ProgramState *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 Zaks31e10282011-08-23 23:56:12 +0000202 if (!isa<SymbolicRegion>(R)) {
203 // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
204 // region, if that is the case, get the underlining region.
205 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R))
206 R = ER->getAsArrayOffset().getRegion();
207 else
208 return 0;
209 }
Anna Zaks864d2522011-08-12 21:14:26 +0000210 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000211}
212
Anna Zaks864d2522011-08-12 21:14:26 +0000213static bool isBadDeallocationArgument(const MemRegion *Arg) {
214 if (isa<AllocaRegion>(Arg) ||
215 isa<BlockDataRegion>(Arg) ||
216 isa<TypedRegion>(Arg)) {
217 return true;
218 }
219 return false;
220}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000221/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000222/// that value is itself an address, and return the corresponding symbol.
223static SymbolRef getAsPointeeSymbol(const Expr *Expr,
224 CheckerContext &C) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000225 const ProgramState *State = C.getState();
Anna Zaksca0b57e2011-08-05 00:37:00 +0000226 SVal ArgV = State->getSVal(Expr);
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000227
Anna Zaksca0b57e2011-08-05 00:37:00 +0000228 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
229 StoreManager& SM = C.getStoreManager();
230 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000231 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000232 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000233 }
234 return 0;
235}
236
Anna Zaks703ffb12011-08-12 21:56:43 +0000237// When checking for error code, we need to consider the following cases:
238// 1) noErr / [0]
239// 2) someErr / [1, inf]
240// 3) unknown
241// If noError, returns true iff (1).
242// If !noError, returns true iff (2).
243bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000244 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000245 SValBuilder &Builder,
246 bool noError) const {
247 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
248 Builder.getSymbolManager().getType(RetSym));
249 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
250 nonloc::SymbolVal(RetSym));
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000251 const ProgramState *ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000252 if (ErrState == State) {
253 return true;
254 }
255
256 return false;
257}
258
Anna Zaksdd6060e2011-08-23 23:47:36 +0000259// Report deallocator mismatch. Remove the region from tracking - reporting a
260// missing free error after this one is redundant.
261void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000262 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000263 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000264 CheckerContext &C) const {
Anna Zaksdd6060e2011-08-23 23:47:36 +0000265 const ProgramState *State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000266 State = State->remove<AllocatedData>(AP.first);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000267 ExplodedNode *N = C.generateNode(State);
268
269 if (!N)
270 return;
271 initBugType();
272 llvm::SmallString<80> sbuf;
273 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000274 unsigned int PDeallocIdx =
275 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000276
277 os << "Deallocator doesn't match the allocator: '"
278 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
279 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000280 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000281 Report->addRange(ArgExpr->getSourceRange());
282 C.EmitReport(Report);
283}
284
Anna Zaksf57be282011-08-01 22:40:01 +0000285void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
286 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000287 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000288 const Expr *Callee = CE->getCallee();
289 SVal L = State->getSVal(Callee);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000290 unsigned idx = InvalidIdx;
Anna Zaksf57be282011-08-01 22:40:01 +0000291
292 const FunctionDecl *funDecl = L.getAsFunctionDecl();
293 if (!funDecl)
294 return;
295 IdentifierInfo *funI = funDecl->getIdentifier();
296 if (!funI)
297 return;
298 StringRef funName = funI->getName();
299
Anna Zaksca0b57e2011-08-05 00:37:00 +0000300 // If it is a call to an allocator function, it could be a double allocation.
301 idx = getTrackedFunctionIndex(funName, true);
302 if (idx != InvalidIdx) {
303 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000304 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000305 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000306 if (!definitelyReturnedError(AS->RetValue, State, C.getSValBuilder())) {
307 // Remove the value from the state. The new symbol will be added for
308 // tracking when the second allocator is processed in checkPostStmt().
309 State = State->remove<AllocatedData>(V);
310 ExplodedNode *N = C.generateNode(State);
311 if (!N)
312 return;
313 initBugType();
314 llvm::SmallString<128> sbuf;
315 llvm::raw_svector_ostream os(sbuf);
316 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
317 os << "Allocated data should be released before another call to "
318 << "the allocator: missing a call to '"
319 << FunctionsToTrack[DIdx].Name
320 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000321 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000322 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000323 Report->addRange(ArgExpr->getSourceRange());
324 C.EmitReport(Report);
325 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000326 }
327 return;
328 }
329
330 // Is it a call to one of deallocator functions?
331 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000332 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000333 return;
334
Anna Zaks864d2522011-08-12 21:14:26 +0000335 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000336 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000337 SVal ArgSVal = State->getSVal(ArgExpr);
338
339 // Undef is reported by another checker.
340 if (ArgSVal.isUndef())
341 return;
342
343 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000344 if (!Arg)
345 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000346
347 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
348 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
349 // If the argument is coming from the heap, globals, or unknown, do not
350 // report it.
351 if (!ArgSM && !RegionArgIsBad)
352 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000353
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000354 // Is the argument to the call being tracked?
355 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
356 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
357 return;
358 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000359 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000360 // TODO: We might want a more precise diagnostic for double free
361 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000362 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000363 // It is possible that this is a false positive - the argument might
364 // have entered as an enclosing function parameter.
365 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000366 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000367
Anna Zaks08551b52011-08-04 00:31:38 +0000368 ExplodedNode *N = C.generateNode(State);
369 if (!N)
370 return;
371 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000372 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000373 "Trying to free data which has not been allocated.", N);
374 Report->addRange(ArgExpr->getSourceRange());
375 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000376 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000377 }
Anna Zaks08551b52011-08-04 00:31:38 +0000378
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000379 // Process functions which might deallocate.
380 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
381
382 if (funName == "CFStringCreateWithBytesNoCopy") {
383 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
384 // NULL ~ default deallocator, so warn.
385 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
386 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000387 const AllocationPair AP = std::make_pair(ArgSM, AS);
388 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000389 return;
390 }
391 // One of the default allocators, so warn.
392 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
393 StringRef DeallocatorName = DE->getFoundDecl()->getName();
394 if (DeallocatorName == "kCFAllocatorDefault" ||
395 DeallocatorName == "kCFAllocatorSystemDefault" ||
396 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000397 const AllocationPair AP = std::make_pair(ArgSM, AS);
398 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000399 return;
400 }
401 // If kCFAllocatorNull, which does not deallocate, we still have to
402 // find the deallocator. Otherwise, assume that the user had written a
403 // custom deallocator which does the right thing.
404 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
405 State = State->remove<AllocatedData>(ArgSM);
406 C.addTransition(State);
407 return;
408 }
409 }
410 }
411 return;
412 }
413
Anna Zaks7d458b02011-08-15 23:23:15 +0000414 // The call is deallocating a value we previously allocated, so remove it
415 // from the next state.
416 State = State->remove<AllocatedData>(ArgSM);
417
Anna Zaksdd6060e2011-08-23 23:47:36 +0000418 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000419 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000420 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000421 const AllocationPair AP = std::make_pair(ArgSM, AS);
422 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000423 return;
424 }
425
Anna Zaks703ffb12011-08-12 21:56:43 +0000426 // If the return status is undefined or is error, report a bad call to free.
427 if (!definitelyDidnotReturnError(AS->RetValue, State, C.getSValBuilder())) {
428 ExplodedNode *N = C.generateNode(State);
429 if (!N)
430 return;
431 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000432 BugReport *Report = new BugReport(*BT,
Anna Zaks703ffb12011-08-12 21:56:43 +0000433 "Call to free data when error was returned during allocation.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000434 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000435 Report->addRange(ArgExpr->getSourceRange());
436 C.EmitReport(Report);
437 return;
438 }
439
Anna Zaks08551b52011-08-04 00:31:38 +0000440 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000441}
442
443void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
444 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000445 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000446 const Expr *Callee = CE->getCallee();
447 SVal L = State->getSVal(Callee);
Anna Zaksf57be282011-08-01 22:40:01 +0000448
449 const FunctionDecl *funDecl = L.getAsFunctionDecl();
450 if (!funDecl)
451 return;
452 IdentifierInfo *funI = funDecl->getIdentifier();
453 if (!funI)
454 return;
455 StringRef funName = funI->getName();
456
457 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000458 unsigned idx = getTrackedFunctionIndex(funName, true);
459 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000460 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000461
Anna Zaks083fcb22011-08-04 17:28:06 +0000462 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000463 // If the argument entered as an enclosing function parameter, skip it to
464 // avoid false positives.
465 if (isEnclosingFunctionParam(ArgExpr))
466 return;
467
Anna Zaks864d2522011-08-12 21:14:26 +0000468 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
469 // If the argument points to something that's not a symbolic region, it
470 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000471 // - unknown (cannot reason about it)
472 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000473 // - constant (null - should not be tracked,
474 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000475 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000476
477 // The call return value symbol should stay alive for as long as the
478 // allocated value symbol, since our diagnostics depend on the value
479 // returned by the call. Ex: Data should only be freed if noErr was
480 // returned during allocation.)
Anna Zaks864d2522011-08-12 21:14:26 +0000481 SymbolRef RetStatusSymbol = State->getSVal(CE).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000482 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
483
484 // Track the allocated value in the checker state.
485 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000486 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000487 assert(State);
488 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000489 }
490}
491
492void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
493 CheckerContext &C) const {
494 const Expr *retExpr = S->getRetValue();
495 if (!retExpr)
496 return;
497
498 // Check if the value is escaping through the return.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000499 const ProgramState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000500 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000501 if (!V)
502 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000503 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000504
Anna Zaks03826aa2011-08-04 00:26:57 +0000505 // Proceed from the new state.
506 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000507}
508
Anna Zakse172e8b2011-08-17 23:00:25 +0000509BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000510 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaks703ffb12011-08-12 21:56:43 +0000511 ExplodedNode *N) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000512 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000513 initBugType();
Anna Zaks67f7fa42011-08-15 18:42:00 +0000514 llvm::SmallString<70> sbuf;
515 llvm::raw_svector_ostream os(sbuf);
Anna Zaks98401112011-08-24 20:52:46 +0000516
Anna Zaks703ffb12011-08-12 21:56:43 +0000517 os << "Allocated data is not released: missing a call to '"
518 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000519 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks98401112011-08-24 20:52:46 +0000520 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
521 Report->addRange(SourceRange());
Anna Zaks703ffb12011-08-12 21:56:43 +0000522 return Report;
523}
524
525void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
526 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000527 const ProgramState *State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000528 AllocatedSetTy ASet = State->get<AllocatedData>();
529 if (ASet.isEmpty())
530 return;
531
532 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000533 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000534 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
535 if (SR.isLive(I->first))
536 continue;
537
538 Changed = true;
539 State = State->remove<AllocatedData>(I->first);
540 // If the allocated symbol is null or if the allocation call might have
541 // returned an error, do not report.
542 if (State->getSymVal(I->first) ||
543 definitelyReturnedError(I->second.RetValue, State, C.getSValBuilder()))
544 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000545 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000546 }
547 if (!Changed)
548 return;
549
550 // Generate the new, cleaned up state.
551 ExplodedNode *N = C.generateNode(State);
552 if (!N)
553 return;
554
555 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000556 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
557 I != E; ++I) {
558 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000559 }
560}
561
562// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksf57be282011-08-01 22:40:01 +0000563void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000564 ExprEngine &Eng) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000565 const ProgramState *state = B.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000566 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000567 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000568 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000569
570 // Anything which has been allocated but not freed (nor escaped) will be
571 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000572 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000573 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000574 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000575 Changed = true;
576 state = state->remove<AllocatedData>(I->first);
577 // If the allocated symbol is null or if error code was returned at
578 // allocation, do not report.
579 if (state->getSymVal(I.getKey()) ||
580 definitelyReturnedError(I->second.RetValue, state,
581 Eng.getSValBuilder())) {
582 continue;
583 }
Anna Zaks5eb7d822011-08-24 21:58:55 +0000584 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000585 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000586
587 // If no change, do not generate a new state.
588 if (!Changed)
589 return;
590
591 ExplodedNode *N = B.generateNode(state);
592 if (!N)
593 return;
594
595 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000596 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
597 I != E; ++I) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000598 Eng.getBugReporter().EmitReport(
Anna Zaks98401112011-08-24 20:52:46 +0000599 generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000600 }
Anna Zaks98401112011-08-24 20:52:46 +0000601}
Anna Zaks703ffb12011-08-12 21:56:43 +0000602
Anna Zaks98401112011-08-24 20:52:46 +0000603
604PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
605 const ExplodedNode *N,
606 const ExplodedNode *PrevN,
607 BugReporterContext &BRC,
608 BugReport &BR) {
609 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
610 if (!AS)
611 return 0;
612 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
613 if (ASPrev)
614 return 0;
615
616 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
617 // allocation site.
618 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
619 .getStmt());
620 const FunctionDecl *funDecl = CE->getDirectCallee();
621 assert(funDecl && "We do not support indirect function calls as of now.");
622 StringRef funName = funDecl->getName();
623
624 // Get the expression of the corresponding argument.
625 unsigned Idx = getTrackedFunctionIndex(funName, true);
626 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
627 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
628 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager());
629 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000630}
631
632void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
633 mgr.registerChecker<MacOSKeychainAPIChecker>();
634}