blob: 40c9c72dc2a2db89cc711d71590502c866c328ff [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 {
Anna Zaks864d2522011-08-12 21:14:26 +000038 /// The index of the allocator function.
39 unsigned int AllocatorIdx;
Anna Zakseacd2b42011-08-25 00:59:06 +000040 SymbolRef Region;
Anna Zaks864d2522011-08-12 21:14:26 +000041
42 AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
Anna Zaks864d2522011-08-12 21:14:26 +000043 AllocatorIdx(Idx),
Anna Zakseacd2b42011-08-25 00:59:06 +000044 Region(R) {}
Anna Zaks864d2522011-08-12 21:14:26 +000045
46 bool operator==(const AllocationState &X) const {
Anna Zakseacd2b42011-08-25 00:59:06 +000047 return (AllocatorIdx == X.AllocatorIdx &&
48 Region == X.Region);
Anna Zaks864d2522011-08-12 21:14:26 +000049 }
Anna Zakseacd2b42011-08-25 00:59:06 +000050
Anna Zaks864d2522011-08-12 21:14:26 +000051 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks864d2522011-08-12 21:14:26 +000052 ID.AddInteger(AllocatorIdx);
Anna Zakseacd2b42011-08-25 00:59:06 +000053 ID.AddPointer(Region);
Anna Zaks864d2522011-08-12 21:14:26 +000054 }
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;
Anna Zaks703ffb12011-08-12 21:56:43 +000060 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000061 void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
62
63private:
Anna Zaks5eb7d822011-08-24 21:58:55 +000064 typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
Anna Zaks98401112011-08-24 20:52:46 +000065 typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
66
67 enum APIKind {
Anna Zaks6cf0ed02011-08-24 00:06:27 +000068 /// Denotes functions tracked by this checker.
69 ValidAPI = 0,
70 /// The functions commonly/mistakenly used in place of the given API.
71 ErrorAPI = 1,
72 /// The functions which may allocate the data. These are tracked to reduce
73 /// the false alarm rate.
74 PossibleAPI = 2
75 };
Anna Zaks083fcb22011-08-04 17:28:06 +000076 /// Stores the information about the allocator and deallocator functions -
77 /// these are the functions the checker is tracking.
78 struct ADFunctionInfo {
79 const char* Name;
80 unsigned int Param;
81 unsigned int DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000082 APIKind Kind;
Anna Zaks083fcb22011-08-04 17:28:06 +000083 };
84 static const unsigned InvalidIdx = 100000;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000085 static const unsigned FunctionsToTrackSize = 8;
Anna Zaks083fcb22011-08-04 17:28:06 +000086 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000087 /// The value, which represents no error return value for allocator functions.
88 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000089
Anna Zaks083fcb22011-08-04 17:28:06 +000090 /// Given the function name, returns the index of the allocator/deallocator
91 /// function.
Anna Zaks98401112011-08-24 20:52:46 +000092 static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
Anna Zaks03826aa2011-08-04 00:26:57 +000093
94 inline void initBugType() const {
95 if (!BT)
96 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
97 }
Anna Zaks703ffb12011-08-12 21:56:43 +000098
Anna Zaks6b7aad92011-08-25 00:32:42 +000099 void generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000100 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000101 CheckerContext &C) const;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000102
Anna Zaks98401112011-08-24 20:52:46 +0000103 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zakse172e8b2011-08-17 23:00:25 +0000104 ExplodedNode *N) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000105
106 /// Check if RetSym evaluates to an error value in the current state.
107 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000108 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000109 SValBuilder &Builder,
110 bool noError = false) const;
111
112 /// Check if RetSym evaluates to a NoErr value in the current state.
113 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000114 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000115 SValBuilder &Builder) const {
116 return definitelyReturnedError(RetSym, State, Builder, true);
117 }
118
Anna Zaks98401112011-08-24 20:52:46 +0000119 /// The bug visitor which allows us to print extra diagnostics along the
120 /// BugReport path. For example, showing the allocation site of the leaked
121 /// region.
122 class SecKeychainBugVisitor : public BugReporterVisitor {
123 protected:
124 // The allocated region symbol tracked by the main analysis.
125 SymbolRef Sym;
126
127 public:
128 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
129 virtual ~SecKeychainBugVisitor() {}
130
131 void Profile(llvm::FoldingSetNodeID &ID) const {
132 static int X = 0;
133 ID.AddPointer(&X);
134 ID.AddPointer(Sym);
135 }
136
137 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
138 const ExplodedNode *PrevN,
139 BugReporterContext &BRC,
140 BugReport &BR);
141 };
Anna Zaksf57be282011-08-01 22:40:01 +0000142};
143}
144
Anna Zaks7d458b02011-08-15 23:23:15 +0000145/// ProgramState traits to store the currently allocated (and not yet freed)
146/// symbols. This is a map from the allocated content symbol to the
147/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000148typedef llvm::ImmutableMap<SymbolRef,
149 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000150
151namespace { struct AllocatedData {}; }
152namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000153template<> struct ProgramStateTrait<AllocatedData>
154 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000155 static void *GDMIndex() { static int index = 0; return &index; }
156};
157}}
158
Anna Zaks03826aa2011-08-04 00:26:57 +0000159static bool isEnclosingFunctionParam(const Expr *E) {
160 E = E->IgnoreParenCasts();
161 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
162 const ValueDecl *VD = DRE->getDecl();
163 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
164 return true;
165 }
166 return false;
167}
168
Anna Zaks083fcb22011-08-04 17:28:06 +0000169const MacOSKeychainAPIChecker::ADFunctionInfo
170 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000171 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
172 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
173 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
174 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
175 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
176 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
177 {"free", 0, InvalidIdx, ErrorAPI}, // 6
178 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000179};
180
181unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000182 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000183 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
184 ADFunctionInfo FI = FunctionsToTrack[I];
185 if (FI.Name != Name)
186 continue;
187 // Make sure the function is of the right type (allocator vs deallocator).
188 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
189 return InvalidIdx;
190 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
191 return InvalidIdx;
192
193 return I;
194 }
195 // The function is not tracked.
196 return InvalidIdx;
197}
198
Anna Zaks864d2522011-08-12 21:14:26 +0000199static SymbolRef getSymbolForRegion(CheckerContext &C,
200 const MemRegion *R) {
Anna Zaks31e10282011-08-23 23:56:12 +0000201 if (!isa<SymbolicRegion>(R)) {
202 // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
203 // region, if that is the case, get the underlining region.
204 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R))
205 R = ER->getAsArrayOffset().getRegion();
206 else
207 return 0;
208 }
Anna Zaks864d2522011-08-12 21:14:26 +0000209 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000210}
211
Anna Zaks864d2522011-08-12 21:14:26 +0000212static bool isBadDeallocationArgument(const MemRegion *Arg) {
213 if (isa<AllocaRegion>(Arg) ||
214 isa<BlockDataRegion>(Arg) ||
215 isa<TypedRegion>(Arg)) {
216 return true;
217 }
218 return false;
219}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000220/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000221/// that value is itself an address, and return the corresponding symbol.
222static SymbolRef getAsPointeeSymbol(const Expr *Expr,
223 CheckerContext &C) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000224 const ProgramState *State = C.getState();
Anna Zaksca0b57e2011-08-05 00:37:00 +0000225 SVal ArgV = State->getSVal(Expr);
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000226
Anna Zaksca0b57e2011-08-05 00:37:00 +0000227 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
228 StoreManager& SM = C.getStoreManager();
229 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000230 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000231 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000232 }
233 return 0;
234}
235
Anna Zaks703ffb12011-08-12 21:56:43 +0000236// When checking for error code, we need to consider the following cases:
237// 1) noErr / [0]
238// 2) someErr / [1, inf]
239// 3) unknown
240// If noError, returns true iff (1).
241// If !noError, returns true iff (2).
242bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000243 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000244 SValBuilder &Builder,
245 bool noError) const {
246 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
247 Builder.getSymbolManager().getType(RetSym));
248 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
249 nonloc::SymbolVal(RetSym));
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000250 const ProgramState *ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000251 if (ErrState == State) {
252 return true;
253 }
254
255 return false;
256}
257
Anna Zaksdd6060e2011-08-23 23:47:36 +0000258// Report deallocator mismatch. Remove the region from tracking - reporting a
259// missing free error after this one is redundant.
260void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000261 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000262 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000263 CheckerContext &C) const {
Anna Zaksdd6060e2011-08-23 23:47:36 +0000264 const ProgramState *State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000265 State = State->remove<AllocatedData>(AP.first);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000266 ExplodedNode *N = C.generateNode(State);
267
268 if (!N)
269 return;
270 initBugType();
271 llvm::SmallString<80> sbuf;
272 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000273 unsigned int PDeallocIdx =
274 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000275
276 os << "Deallocator doesn't match the allocator: '"
277 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
278 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000279 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000280 Report->addRange(ArgExpr->getSourceRange());
281 C.EmitReport(Report);
282}
283
Anna Zaksf57be282011-08-01 22:40:01 +0000284void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
285 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000286 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000287 const Expr *Callee = CE->getCallee();
288 SVal L = State->getSVal(Callee);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000289 unsigned idx = InvalidIdx;
Anna Zaksf57be282011-08-01 22:40:01 +0000290
291 const FunctionDecl *funDecl = L.getAsFunctionDecl();
292 if (!funDecl)
293 return;
294 IdentifierInfo *funI = funDecl->getIdentifier();
295 if (!funI)
296 return;
297 StringRef funName = funI->getName();
298
Anna Zaksca0b57e2011-08-05 00:37:00 +0000299 // If it is a call to an allocator function, it could be a double allocation.
300 idx = getTrackedFunctionIndex(funName, true);
301 if (idx != InvalidIdx) {
302 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000303 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000304 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000305 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000306 // Remove the value from the state. The new symbol will be added for
307 // tracking when the second allocator is processed in checkPostStmt().
308 State = State->remove<AllocatedData>(V);
309 ExplodedNode *N = C.generateNode(State);
310 if (!N)
311 return;
312 initBugType();
313 llvm::SmallString<128> sbuf;
314 llvm::raw_svector_ostream os(sbuf);
315 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
316 os << "Allocated data should be released before another call to "
317 << "the allocator: missing a call to '"
318 << FunctionsToTrack[DIdx].Name
319 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000320 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000321 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000322 Report->addRange(ArgExpr->getSourceRange());
323 C.EmitReport(Report);
324 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000325 }
326 return;
327 }
328
329 // Is it a call to one of deallocator functions?
330 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000331 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000332 return;
333
Anna Zaks864d2522011-08-12 21:14:26 +0000334 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000335 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000336 SVal ArgSVal = State->getSVal(ArgExpr);
337
338 // Undef is reported by another checker.
339 if (ArgSVal.isUndef())
340 return;
341
342 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000343 if (!Arg)
344 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000345
346 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
347 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
348 // If the argument is coming from the heap, globals, or unknown, do not
349 // report it.
350 if (!ArgSM && !RegionArgIsBad)
351 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000352
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000353 // Is the argument to the call being tracked?
354 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
355 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
356 return;
357 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000358 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000359 // TODO: We might want a more precise diagnostic for double free
360 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000361 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000362 // It is possible that this is a false positive - the argument might
363 // have entered as an enclosing function parameter.
364 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000365 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000366
Anna Zaks08551b52011-08-04 00:31:38 +0000367 ExplodedNode *N = C.generateNode(State);
368 if (!N)
369 return;
370 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000371 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000372 "Trying to free data which has not been allocated.", N);
373 Report->addRange(ArgExpr->getSourceRange());
374 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000375 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000376 }
Anna Zaks08551b52011-08-04 00:31:38 +0000377
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000378 // Process functions which might deallocate.
379 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
380
381 if (funName == "CFStringCreateWithBytesNoCopy") {
382 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
383 // NULL ~ default deallocator, so warn.
384 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
385 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000386 const AllocationPair AP = std::make_pair(ArgSM, AS);
387 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000388 return;
389 }
390 // One of the default allocators, so warn.
391 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
392 StringRef DeallocatorName = DE->getFoundDecl()->getName();
393 if (DeallocatorName == "kCFAllocatorDefault" ||
394 DeallocatorName == "kCFAllocatorSystemDefault" ||
395 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000396 const AllocationPair AP = std::make_pair(ArgSM, AS);
397 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000398 return;
399 }
400 // If kCFAllocatorNull, which does not deallocate, we still have to
401 // find the deallocator. Otherwise, assume that the user had written a
402 // custom deallocator which does the right thing.
403 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
404 State = State->remove<AllocatedData>(ArgSM);
405 C.addTransition(State);
406 return;
407 }
408 }
409 }
410 return;
411 }
412
Anna Zaks7d458b02011-08-15 23:23:15 +0000413 // The call is deallocating a value we previously allocated, so remove it
414 // from the next state.
415 State = State->remove<AllocatedData>(ArgSM);
416
Anna Zaksdd6060e2011-08-23 23:47:36 +0000417 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000418 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000419 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000420 const AllocationPair AP = std::make_pair(ArgSM, AS);
421 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000422 return;
423 }
424
Anna Zaks703ffb12011-08-12 21:56:43 +0000425 // If the return status is undefined or is error, report a bad call to free.
Anna Zakseacd2b42011-08-25 00:59:06 +0000426 if (!definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000427 ExplodedNode *N = C.generateNode(State);
428 if (!N)
429 return;
430 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000431 BugReport *Report = new BugReport(*BT,
Anna Zaks703ffb12011-08-12 21:56:43 +0000432 "Call to free data when error was returned during allocation.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000433 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000434 Report->addRange(ArgExpr->getSourceRange());
435 C.EmitReport(Report);
436 return;
437 }
438
Anna Zaks08551b52011-08-04 00:31:38 +0000439 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000440}
441
442void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
443 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000444 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000445 const Expr *Callee = CE->getCallee();
446 SVal L = State->getSVal(Callee);
Anna Zaksf57be282011-08-01 22:40:01 +0000447
448 const FunctionDecl *funDecl = L.getAsFunctionDecl();
449 if (!funDecl)
450 return;
451 IdentifierInfo *funI = funDecl->getIdentifier();
452 if (!funI)
453 return;
454 StringRef funName = funI->getName();
455
456 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000457 unsigned idx = getTrackedFunctionIndex(funName, true);
458 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000459 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000460
Anna Zaks083fcb22011-08-04 17:28:06 +0000461 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000462 // If the argument entered as an enclosing function parameter, skip it to
463 // avoid false positives.
464 if (isEnclosingFunctionParam(ArgExpr))
465 return;
466
Anna Zaks864d2522011-08-12 21:14:26 +0000467 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
468 // If the argument points to something that's not a symbolic region, it
469 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000470 // - unknown (cannot reason about it)
471 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000472 // - constant (null - should not be tracked,
473 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000474 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000475
476 // The call return value symbol should stay alive for as long as the
477 // allocated value symbol, since our diagnostics depend on the value
478 // returned by the call. Ex: Data should only be freed if noErr was
479 // returned during allocation.)
Anna Zaks864d2522011-08-12 21:14:26 +0000480 SymbolRef RetStatusSymbol = State->getSVal(CE).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000481 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
482
483 // Track the allocated value in the checker state.
484 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000485 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000486 assert(State);
487 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000488 }
489}
490
491void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
492 CheckerContext &C) const {
493 const Expr *retExpr = S->getRetValue();
494 if (!retExpr)
495 return;
496
497 // Check if the value is escaping through the return.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000498 const ProgramState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000499 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000500 if (!V)
501 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000502 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000503
Anna Zaks03826aa2011-08-04 00:26:57 +0000504 // Proceed from the new state.
505 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000506}
507
Anna Zakse172e8b2011-08-17 23:00:25 +0000508BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000509 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaks703ffb12011-08-12 21:56:43 +0000510 ExplodedNode *N) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000511 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000512 initBugType();
Anna Zaks67f7fa42011-08-15 18:42:00 +0000513 llvm::SmallString<70> sbuf;
514 llvm::raw_svector_ostream os(sbuf);
Anna Zaks98401112011-08-24 20:52:46 +0000515
Anna Zaks703ffb12011-08-12 21:56:43 +0000516 os << "Allocated data is not released: missing a call to '"
517 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000518 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks98401112011-08-24 20:52:46 +0000519 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
520 Report->addRange(SourceRange());
Anna Zaks703ffb12011-08-12 21:56:43 +0000521 return Report;
522}
523
524void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
525 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000526 const ProgramState *State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000527 AllocatedSetTy ASet = State->get<AllocatedData>();
528 if (ASet.isEmpty())
529 return;
530
531 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000532 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000533 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
534 if (SR.isLive(I->first))
535 continue;
536
537 Changed = true;
538 State = State->remove<AllocatedData>(I->first);
539 // If the allocated symbol is null or if the allocation call might have
540 // returned an error, do not report.
541 if (State->getSymVal(I->first) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000542 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000543 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000544 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000545 }
546 if (!Changed)
547 return;
548
549 // Generate the new, cleaned up state.
550 ExplodedNode *N = C.generateNode(State);
551 if (!N)
552 return;
553
554 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000555 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
556 I != E; ++I) {
557 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000558 }
559}
560
561// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksf57be282011-08-01 22:40:01 +0000562void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000563 ExprEngine &Eng) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000564 const ProgramState *state = B.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000565 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000566 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000567 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000568
569 // Anything which has been allocated but not freed (nor escaped) will be
570 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000571 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000572 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000573 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000574 Changed = true;
575 state = state->remove<AllocatedData>(I->first);
576 // If the allocated symbol is null or if error code was returned at
577 // allocation, do not report.
578 if (state->getSymVal(I.getKey()) ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000579 definitelyReturnedError(I->second.Region, state,
Anna Zaks703ffb12011-08-12 21:56:43 +0000580 Eng.getSValBuilder())) {
581 continue;
582 }
Anna Zaks5eb7d822011-08-24 21:58:55 +0000583 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000584 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000585
586 // If no change, do not generate a new state.
587 if (!Changed)
588 return;
589
590 ExplodedNode *N = B.generateNode(state);
591 if (!N)
592 return;
593
594 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000595 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
596 I != E; ++I) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000597 Eng.getBugReporter().EmitReport(
Anna Zaks98401112011-08-24 20:52:46 +0000598 generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000599 }
Anna Zaks98401112011-08-24 20:52:46 +0000600}
Anna Zaks703ffb12011-08-12 21:56:43 +0000601
Anna Zaks98401112011-08-24 20:52:46 +0000602
603PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
604 const ExplodedNode *N,
605 const ExplodedNode *PrevN,
606 BugReporterContext &BRC,
607 BugReport &BR) {
608 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
609 if (!AS)
610 return 0;
611 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
612 if (ASPrev)
613 return 0;
614
615 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
616 // allocation site.
617 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
618 .getStmt());
619 const FunctionDecl *funDecl = CE->getDirectCallee();
620 assert(funDecl && "We do not support indirect function calls as of now.");
621 StringRef funName = funDecl->getName();
622
623 // Get the expression of the corresponding argument.
624 unsigned Idx = getTrackedFunctionIndex(funName, true);
625 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
626 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
627 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager());
628 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000629}
630
631void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
632 mgr.registerChecker<MacOSKeychainAPIChecker>();
633}