blob: 765266b786d3b0026449348d211507707d3b1a13 [file] [log] [blame]
Anna Zaks083fcb22011-08-04 17:28:06 +00001//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
Anna Zaksf57be282011-08-01 22:40:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This checker flags misuses of KeyChainAPI. In particular, the password data
10// allocated/returned by SecKeychainItemCopyContent,
11// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
12// to be freed using a call to SecKeychainItemFreeContent.
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
16#include "clang/StaticAnalyzer/Core/Checker.h"
17#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Anna Zaks03826aa2011-08-04 00:26:57 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaksf57be282011-08-01 22:40:01 +000019#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000022#include "llvm/ADT/SmallString.h"
Anna Zaksf57be282011-08-01 22:40:01 +000023
24using namespace clang;
25using namespace ento;
26
27namespace {
28class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
Anna Zaksf57be282011-08-01 22:40:01 +000029 check::PostStmt<CallExpr>,
Anna Zaks703ffb12011-08-12 21:56:43 +000030 check::DeadSymbols> {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000031 mutable OwningPtr<BugType> BT;
Anna Zaks03826aa2011-08-04 00:26:57 +000032
Anna Zaksf57be282011-08-01 22:40:01 +000033public:
Anna Zaks864d2522011-08-12 21:14:26 +000034 /// AllocationState is a part of the checker specific state together with the
35 /// MemRegion corresponding to the allocated data.
36 struct AllocationState {
Anna Zaks864d2522011-08-12 21:14:26 +000037 /// The index of the allocator function.
38 unsigned int AllocatorIdx;
Anna Zakseacd2b42011-08-25 00:59:06 +000039 SymbolRef Region;
Anna Zaks864d2522011-08-12 21:14:26 +000040
41 AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
Anna Zaks864d2522011-08-12 21:14:26 +000042 AllocatorIdx(Idx),
Anna Zakseacd2b42011-08-25 00:59:06 +000043 Region(R) {}
Anna Zaks864d2522011-08-12 21:14:26 +000044
45 bool operator==(const AllocationState &X) const {
Anna Zakseacd2b42011-08-25 00:59:06 +000046 return (AllocatorIdx == X.AllocatorIdx &&
47 Region == X.Region);
Anna Zaks864d2522011-08-12 21:14:26 +000048 }
Anna Zakseacd2b42011-08-25 00:59:06 +000049
Anna Zaks864d2522011-08-12 21:14:26 +000050 void Profile(llvm::FoldingSetNodeID &ID) const {
Anna Zaks864d2522011-08-12 21:14:26 +000051 ID.AddInteger(AllocatorIdx);
Anna Zakseacd2b42011-08-25 00:59:06 +000052 ID.AddPointer(Region);
Anna Zaks864d2522011-08-12 21:14:26 +000053 }
54 };
55
Anna Zaksf57be282011-08-01 22:40:01 +000056 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000057 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +000058 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000059
60private:
Anna Zaks5eb7d822011-08-24 21:58:55 +000061 typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
Anna Zaks98401112011-08-24 20:52:46 +000062 typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
63
64 enum APIKind {
Anna Zaks6cf0ed02011-08-24 00:06:27 +000065 /// Denotes functions tracked by this checker.
66 ValidAPI = 0,
67 /// The functions commonly/mistakenly used in place of the given API.
68 ErrorAPI = 1,
69 /// The functions which may allocate the data. These are tracked to reduce
70 /// the false alarm rate.
71 PossibleAPI = 2
72 };
Anna Zaks083fcb22011-08-04 17:28:06 +000073 /// Stores the information about the allocator and deallocator functions -
74 /// these are the functions the checker is tracking.
75 struct ADFunctionInfo {
76 const char* Name;
77 unsigned int Param;
78 unsigned int DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000079 APIKind Kind;
Anna Zaks083fcb22011-08-04 17:28:06 +000080 };
81 static const unsigned InvalidIdx = 100000;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000082 static const unsigned FunctionsToTrackSize = 8;
Anna Zaks083fcb22011-08-04 17:28:06 +000083 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000084 /// The value, which represents no error return value for allocator functions.
85 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000086
Anna Zaks083fcb22011-08-04 17:28:06 +000087 /// Given the function name, returns the index of the allocator/deallocator
88 /// function.
Anna Zaks98401112011-08-24 20:52:46 +000089 static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
Anna Zaks03826aa2011-08-04 00:26:57 +000090
91 inline void initBugType() const {
92 if (!BT)
93 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
94 }
Anna Zaks703ffb12011-08-12 21:56:43 +000095
Anna Zaks6b7aad92011-08-25 00:32:42 +000096 void generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +000097 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +000098 CheckerContext &C) const;
Anna Zaksdd6060e2011-08-23 23:47:36 +000099
Anna Zaksd708bac2012-02-23 22:53:29 +0000100 /// Find the allocation site for Sym on the path leading to the node N.
101 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
102 CheckerContext &C) const;
103
Anna Zaks98401112011-08-24 20:52:46 +0000104 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000105 ExplodedNode *N,
106 CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000107
108 /// Check if RetSym evaluates to an error value in the current state.
109 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000110 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000111 SValBuilder &Builder,
112 bool noError = false) const;
113
114 /// Check if RetSym evaluates to a NoErr value in the current state.
115 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000116 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000117 SValBuilder &Builder) const {
118 return definitelyReturnedError(RetSym, State, Builder, true);
119 }
Ted Kremenek76aadc32012-03-09 01:13:14 +0000120
121 /// Mark an AllocationPair interesting for diagnostic reporting.
122 void markInteresting(BugReport *R, const AllocationPair &AP) const {
123 R->markInteresting(AP.first);
124 R->markInteresting(AP.second->Region);
125 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000126
Anna Zaks98401112011-08-24 20:52:46 +0000127 /// The bug visitor which allows us to print extra diagnostics along the
128 /// BugReport path. For example, showing the allocation site of the leaked
129 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000130 class SecKeychainBugVisitor
131 : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
Anna Zaks98401112011-08-24 20:52:46 +0000132 protected:
133 // The allocated region symbol tracked by the main analysis.
134 SymbolRef Sym;
135
136 public:
137 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
138 virtual ~SecKeychainBugVisitor() {}
139
140 void Profile(llvm::FoldingSetNodeID &ID) const {
141 static int X = 0;
142 ID.AddPointer(&X);
143 ID.AddPointer(Sym);
144 }
145
146 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
147 const ExplodedNode *PrevN,
148 BugReporterContext &BRC,
149 BugReport &BR);
150 };
Anna Zaksf57be282011-08-01 22:40:01 +0000151};
152}
153
Anna Zaks7d458b02011-08-15 23:23:15 +0000154/// ProgramState traits to store the currently allocated (and not yet freed)
155/// symbols. This is a map from the allocated content symbol to the
156/// corresponding AllocationState.
Jordan Rose166d5022012-11-02 01:54:06 +0000157REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
158 SymbolRef,
159 MacOSKeychainAPIChecker::AllocationState)
Anna Zaksf57be282011-08-01 22:40:01 +0000160
Anna Zaks03826aa2011-08-04 00:26:57 +0000161static bool isEnclosingFunctionParam(const Expr *E) {
162 E = E->IgnoreParenCasts();
163 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
164 const ValueDecl *VD = DRE->getDecl();
165 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
166 return true;
167 }
168 return false;
169}
170
Anna Zaks083fcb22011-08-04 17:28:06 +0000171const MacOSKeychainAPIChecker::ADFunctionInfo
172 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000173 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
174 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
175 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
176 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
177 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
178 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
179 {"free", 0, InvalidIdx, ErrorAPI}, // 6
180 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000181};
182
183unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000184 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000185 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
186 ADFunctionInfo FI = FunctionsToTrack[I];
187 if (FI.Name != Name)
188 continue;
189 // Make sure the function is of the right type (allocator vs deallocator).
190 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
191 return InvalidIdx;
192 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
193 return InvalidIdx;
194
195 return I;
196 }
197 // The function is not tracked.
198 return InvalidIdx;
199}
200
Anna Zaks864d2522011-08-12 21:14:26 +0000201static bool isBadDeallocationArgument(const MemRegion *Arg) {
Jordy Rose3e678142012-03-11 00:08:24 +0000202 if (!Arg)
203 return false;
Anna Zaks864d2522011-08-12 21:14:26 +0000204 if (isa<AllocaRegion>(Arg) ||
205 isa<BlockDataRegion>(Arg) ||
206 isa<TypedRegion>(Arg)) {
207 return true;
208 }
209 return false;
210}
Jordy Rose3e678142012-03-11 00:08:24 +0000211
Anna Zaksca0b57e2011-08-05 00:37:00 +0000212/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000213/// that value is itself an address, and return the corresponding symbol.
214static SymbolRef getAsPointeeSymbol(const Expr *Expr,
215 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000216 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000217 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000218
Anna Zaksca0b57e2011-08-05 00:37:00 +0000219 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
220 StoreManager& SM = C.getStoreManager();
Jordy Rose3e678142012-03-11 00:08:24 +0000221 SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
222 if (sym)
223 return sym;
Anna Zaksca0b57e2011-08-05 00:37:00 +0000224 }
225 return 0;
226}
227
Anna Zaks703ffb12011-08-12 21:56:43 +0000228// When checking for error code, we need to consider the following cases:
229// 1) noErr / [0]
230// 2) someErr / [1, inf]
231// 3) unknown
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000232// If noError, returns true iff (1).
233// If !noError, returns true iff (2).
Anna Zaks703ffb12011-08-12 21:56:43 +0000234bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000235 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000236 SValBuilder &Builder,
237 bool noError) const {
238 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
239 Builder.getSymbolManager().getType(RetSym));
240 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
241 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000242 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000243 if (ErrState == State) {
244 return true;
245 }
246
247 return false;
248}
249
Anna Zaksdd6060e2011-08-23 23:47:36 +0000250// Report deallocator mismatch. Remove the region from tracking - reporting a
251// missing free error after this one is redundant.
252void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000253 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000254 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000255 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000256 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000257 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000258 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000259
260 if (!N)
261 return;
262 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000263 SmallString<80> sbuf;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000264 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000265 unsigned int PDeallocIdx =
266 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000267
268 os << "Deallocator doesn't match the allocator: '"
269 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
270 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000271 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000272 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000273 markInteresting(Report, AP);
Jordan Rose785950e2012-11-02 01:53:40 +0000274 C.emitReport(Report);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000275}
276
Anna Zaksf57be282011-08-01 22:40:01 +0000277void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
278 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000279 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000280 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000281
Jordan Rose5ef6e942012-07-10 23:13:01 +0000282 const FunctionDecl *FD = C.getCalleeDecl(CE);
283 if (!FD || FD->getKind() != Decl::Function)
284 return;
285
286 StringRef funName = C.getCalleeName(FD);
Anna Zaksb805c8f2011-12-01 05:57:37 +0000287 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000288 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000289
Anna Zaksca0b57e2011-08-05 00:37:00 +0000290 // If it is a call to an allocator function, it could be a double allocation.
291 idx = getTrackedFunctionIndex(funName, true);
292 if (idx != InvalidIdx) {
293 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000294 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000295 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000296 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000297 // Remove the value from the state. The new symbol will be added for
298 // tracking when the second allocator is processed in checkPostStmt().
299 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000300 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000301 if (!N)
302 return;
303 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000304 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000305 llvm::raw_svector_ostream os(sbuf);
306 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
307 os << "Allocated data should be released before another call to "
308 << "the allocator: missing a call to '"
309 << FunctionsToTrack[DIdx].Name
310 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000311 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000312 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000313 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000314 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000315 C.emitReport(Report);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000316 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000317 }
318 return;
319 }
320
321 // Is it a call to one of deallocator functions?
322 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000323 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000324 return;
325
Anna Zaks864d2522011-08-12 21:14:26 +0000326 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000327 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000328 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000329
330 // Undef is reported by another checker.
331 if (ArgSVal.isUndef())
332 return;
333
Jordy Rose3e678142012-03-11 00:08:24 +0000334 SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
Anna Zaks864d2522011-08-12 21:14:26 +0000335
Anna Zaks864d2522011-08-12 21:14:26 +0000336 // If the argument is coming from the heap, globals, or unknown, do not
337 // report it.
Jordy Rose3e678142012-03-11 00:08:24 +0000338 bool RegionArgIsBad = false;
339 if (!ArgSM) {
340 if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
341 return;
342 RegionArgIsBad = true;
343 }
Anna Zaks08551b52011-08-04 00:31:38 +0000344
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000345 // Is the argument to the call being tracked?
346 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
347 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
348 return;
349 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000350 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000351 // TODO: We might want a more precise diagnostic for double free
352 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000353 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000354 // It is possible that this is a false positive - the argument might
355 // have entered as an enclosing function parameter.
356 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000357 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000358
Anna Zaks0bd6b112011-10-26 21:06:34 +0000359 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000360 if (!N)
361 return;
362 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000363 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000364 "Trying to free data which has not been allocated.", N);
365 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000366 if (AS)
367 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000368 C.emitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000369 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000370 }
Anna Zaks08551b52011-08-04 00:31:38 +0000371
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000372 // Process functions which might deallocate.
373 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
374
375 if (funName == "CFStringCreateWithBytesNoCopy") {
376 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
377 // NULL ~ default deallocator, so warn.
378 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
379 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000380 const AllocationPair AP = std::make_pair(ArgSM, AS);
381 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000382 return;
383 }
384 // One of the default allocators, so warn.
385 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
386 StringRef DeallocatorName = DE->getFoundDecl()->getName();
387 if (DeallocatorName == "kCFAllocatorDefault" ||
388 DeallocatorName == "kCFAllocatorSystemDefault" ||
389 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000390 const AllocationPair AP = std::make_pair(ArgSM, AS);
391 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000392 return;
393 }
394 // If kCFAllocatorNull, which does not deallocate, we still have to
395 // find the deallocator. Otherwise, assume that the user had written a
396 // custom deallocator which does the right thing.
397 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
398 State = State->remove<AllocatedData>(ArgSM);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000399 C.addTransition(State);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000400 return;
401 }
402 }
403 }
404 return;
405 }
406
Anna Zaks7d458b02011-08-15 23:23:15 +0000407 // The call is deallocating a value we previously allocated, so remove it
408 // from the next state.
409 State = State->remove<AllocatedData>(ArgSM);
410
Anna Zaksdd6060e2011-08-23 23:47:36 +0000411 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000412 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000413 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000414 const AllocationPair AP = std::make_pair(ArgSM, AS);
415 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000416 return;
417 }
418
Anna Zaksee5a21f2011-12-01 16:41:58 +0000419 // If the buffer can be null and the return status can be an error,
420 // report a bad call to free.
421 if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
422 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000423 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000424 if (!N)
425 return;
426 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000427 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000428 "Only call free if a valid (non-NULL) buffer was returned.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000429 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000430 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000431 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000432 C.emitReport(Report);
Anna Zaks703ffb12011-08-12 21:56:43 +0000433 return;
434 }
435
Anna Zaks0bd6b112011-10-26 21:06:34 +0000436 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000437}
438
439void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
440 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000441 ProgramStateRef State = C.getState();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000442 const FunctionDecl *FD = C.getCalleeDecl(CE);
443 if (!FD || FD->getKind() != Decl::Function)
444 return;
445
446 StringRef funName = C.getCalleeName(FD);
Anna Zaksf57be282011-08-01 22:40:01 +0000447
448 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000449 unsigned idx = getTrackedFunctionIndex(funName, true);
450 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000451 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000452
Anna Zaks083fcb22011-08-04 17:28:06 +0000453 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000454 // If the argument entered as an enclosing function parameter, skip it to
455 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000456 if (isEnclosingFunctionParam(ArgExpr) &&
457 C.getLocationContext()->getParent() == 0)
Anna Zaks79c9c752011-08-12 22:47:22 +0000458 return;
459
Anna Zaks864d2522011-08-12 21:14:26 +0000460 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
461 // If the argument points to something that's not a symbolic region, it
462 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000463 // - unknown (cannot reason about it)
464 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000465 // - constant (null - should not be tracked,
466 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000467 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000468
469 // The call return value symbol should stay alive for as long as the
470 // allocated value symbol, since our diagnostics depend on the value
471 // returned by the call. Ex: Data should only be freed if noErr was
472 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000473 SymbolRef RetStatusSymbol =
474 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000475 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
476
477 // Track the allocated value in the checker state.
478 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000479 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000480 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000481 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000482 }
483}
484
Anna Zaks721aa372012-02-28 03:07:06 +0000485// TODO: This logic is the same as in Malloc checker.
Anna Zaksd708bac2012-02-23 22:53:29 +0000486const Stmt *
487MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
488 SymbolRef Sym,
489 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000490 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000491 // Walk the ExplodedGraph backwards and find the first node that referred to
492 // the tracked symbol.
493 const ExplodedNode *AllocNode = N;
494
495 while (N) {
496 if (!N->getState()->get<AllocatedData>(Sym))
497 break;
Anna Zaks721aa372012-02-28 03:07:06 +0000498 // Allocation node, is the last node in the current context in which the
499 // symbol was tracked.
500 if (N->getLocationContext() == LeakContext)
501 AllocNode = N;
Anna Zaksd708bac2012-02-23 22:53:29 +0000502 N = N->pred_empty() ? NULL : *(N->pred_begin());
503 }
504
505 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +0000506 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
507 return Exit->getCalleeContext()->getCallSite();
508 if (clang::PostStmt *PS = dyn_cast<clang::PostStmt>(&P))
509 return PS->getStmt();
510 return 0;
Anna Zaksd708bac2012-02-23 22:53:29 +0000511}
512
Anna Zakse172e8b2011-08-17 23:00:25 +0000513BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000514 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000515 ExplodedNode *N,
516 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000517 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000518 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000519 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000520 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000521 os << "Allocated data is not released: missing a call to '"
522 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000523
524 // Most bug reports are cached at the location where they occurred.
525 // With leaks, we want to unique them by the location where they were
526 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000527 PathDiagnosticLocation LocUsedForUniqueing;
528 if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
529 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
530 C.getSourceManager(), N->getLocationContext());
Anna Zaksd708bac2012-02-23 22:53:29 +0000531
532 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
Anna Zaks98401112011-08-24 20:52:46 +0000533 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Ted Kremenek76aadc32012-03-09 01:13:14 +0000534 markInteresting(Report, AP);
Anna Zaks703ffb12011-08-12 21:56:43 +0000535 return Report;
536}
537
538void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
539 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000540 ProgramStateRef State = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +0000541 AllocatedDataTy ASet = State->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000542 if (ASet.isEmpty())
543 return;
544
545 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000546 AllocationPairVec Errors;
Jordan Rose166d5022012-11-02 01:54:06 +0000547 for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000548 if (SR.isLive(I->first))
549 continue;
550
551 Changed = true;
552 State = State->remove<AllocatedData>(I->first);
553 // If the allocated symbol is null or if the allocation call might have
554 // returned an error, do not report.
Jordan Roseec8d4202012-11-01 00:18:27 +0000555 ConstraintManager &CMgr = State->getConstraintManager();
556 ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
557 if (AllocFailed.isConstrainedTrue() ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000558 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000559 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000560 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000561 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000562 if (!Changed) {
563 // Generate the new, cleaned up state.
564 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000565 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000566 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000567
Anna Zaksd708bac2012-02-23 22:53:29 +0000568 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
569 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000570
571 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000572 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
573 I != E; ++I) {
Jordan Rose785950e2012-11-02 01:53:40 +0000574 C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000575 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000576
577 // Generate the new, cleaned up state.
578 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000579}
580
Anna Zaks98401112011-08-24 20:52:46 +0000581
582PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
583 const ExplodedNode *N,
584 const ExplodedNode *PrevN,
585 BugReporterContext &BRC,
586 BugReport &BR) {
587 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
588 if (!AS)
589 return 0;
590 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
591 if (ASPrev)
592 return 0;
593
594 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
595 // allocation site.
596 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
597 .getStmt());
598 const FunctionDecl *funDecl = CE->getDirectCallee();
599 assert(funDecl && "We do not support indirect function calls as of now.");
600 StringRef funName = funDecl->getName();
601
602 // Get the expression of the corresponding argument.
603 unsigned Idx = getTrackedFunctionIndex(funName, true);
604 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
605 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000606 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
607 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000608 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000609}
610
611void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
612 mgr.registerChecker<MacOSKeychainAPIChecker>();
613}