blob: 677c014a962216ba1048563da74c47cc3ea2f976 [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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000023#include "llvm/Support/raw_ostream.h"
Anna Zaksf57be282011-08-01 22:40:01 +000024
25using namespace clang;
26using namespace ento;
27
28namespace {
29class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
Anna Zaksf57be282011-08-01 22:40:01 +000030 check::PostStmt<CallExpr>,
Anna Zaks703ffb12011-08-12 21:56:43 +000031 check::DeadSymbols> {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000032 mutable OwningPtr<BugType> BT;
Anna Zaks03826aa2011-08-04 00:26:57 +000033
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;
Anna Zaksf57be282011-08-01 22:40:01 +000058 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +000059 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000060
61private:
Anna Zaks5eb7d822011-08-24 21:58:55 +000062 typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
Anna Zaks98401112011-08-24 20:52:46 +000063 typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
64
65 enum APIKind {
Anna Zaks6cf0ed02011-08-24 00:06:27 +000066 /// Denotes functions tracked by this checker.
67 ValidAPI = 0,
68 /// The functions commonly/mistakenly used in place of the given API.
69 ErrorAPI = 1,
70 /// The functions which may allocate the data. These are tracked to reduce
71 /// the false alarm rate.
72 PossibleAPI = 2
73 };
Anna Zaks083fcb22011-08-04 17:28:06 +000074 /// Stores the information about the allocator and deallocator functions -
75 /// these are the functions the checker is tracking.
76 struct ADFunctionInfo {
77 const char* Name;
78 unsigned int Param;
79 unsigned int DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000080 APIKind Kind;
Anna Zaks083fcb22011-08-04 17:28:06 +000081 };
82 static const unsigned InvalidIdx = 100000;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000083 static const unsigned FunctionsToTrackSize = 8;
Anna Zaks083fcb22011-08-04 17:28:06 +000084 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000085 /// The value, which represents no error return value for allocator functions.
86 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000087
Anna Zaks083fcb22011-08-04 17:28:06 +000088 /// Given the function name, returns the index of the allocator/deallocator
89 /// function.
Anna Zaks98401112011-08-24 20:52:46 +000090 static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
Anna Zaks03826aa2011-08-04 00:26:57 +000091
92 inline void initBugType() const {
93 if (!BT)
94 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
95 }
Anna Zaks703ffb12011-08-12 21:56:43 +000096
Anna Zaks6b7aad92011-08-25 00:32:42 +000097 void generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +000098 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +000099 CheckerContext &C) const;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000100
Anna Zaksd708bac2012-02-23 22:53:29 +0000101 /// Find the allocation site for Sym on the path leading to the node N.
102 const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
103 CheckerContext &C) const;
104
Anna Zaks98401112011-08-24 20:52:46 +0000105 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000106 ExplodedNode *N,
107 CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000108
109 /// Check if RetSym evaluates to an error value in the current state.
110 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000111 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000112 SValBuilder &Builder,
113 bool noError = false) const;
114
115 /// Check if RetSym evaluates to a NoErr value in the current state.
116 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000117 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000118 SValBuilder &Builder) const {
119 return definitelyReturnedError(RetSym, State, Builder, true);
120 }
Ted Kremenek76aadc32012-03-09 01:13:14 +0000121
122 /// Mark an AllocationPair interesting for diagnostic reporting.
123 void markInteresting(BugReport *R, const AllocationPair &AP) const {
124 R->markInteresting(AP.first);
125 R->markInteresting(AP.second->Region);
126 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000127
Anna Zaks98401112011-08-24 20:52:46 +0000128 /// The bug visitor which allows us to print extra diagnostics along the
129 /// BugReport path. For example, showing the allocation site of the leaked
130 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000131 class SecKeychainBugVisitor
132 : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
Anna Zaks98401112011-08-24 20:52:46 +0000133 protected:
134 // The allocated region symbol tracked by the main analysis.
135 SymbolRef Sym;
136
137 public:
138 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
139 virtual ~SecKeychainBugVisitor() {}
140
141 void Profile(llvm::FoldingSetNodeID &ID) const {
142 static int X = 0;
143 ID.AddPointer(&X);
144 ID.AddPointer(Sym);
145 }
146
147 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
148 const ExplodedNode *PrevN,
149 BugReporterContext &BRC,
150 BugReport &BR);
151 };
Anna Zaksf57be282011-08-01 22:40:01 +0000152};
153}
154
Anna Zaks7d458b02011-08-15 23:23:15 +0000155/// ProgramState traits to store the currently allocated (and not yet freed)
156/// symbols. This is a map from the allocated content symbol to the
157/// corresponding AllocationState.
Jordan Rose166d5022012-11-02 01:54:06 +0000158REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
159 SymbolRef,
160 MacOSKeychainAPIChecker::AllocationState)
Anna Zaksf57be282011-08-01 22:40:01 +0000161
Anna Zaks03826aa2011-08-04 00:26:57 +0000162static bool isEnclosingFunctionParam(const Expr *E) {
163 E = E->IgnoreParenCasts();
164 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
165 const ValueDecl *VD = DRE->getDecl();
166 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
167 return true;
168 }
169 return false;
170}
171
Anna Zaks083fcb22011-08-04 17:28:06 +0000172const MacOSKeychainAPIChecker::ADFunctionInfo
173 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000174 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
175 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
176 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
177 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
178 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
179 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
180 {"free", 0, InvalidIdx, ErrorAPI}, // 6
181 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000182};
183
184unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000185 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000186 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
187 ADFunctionInfo FI = FunctionsToTrack[I];
188 if (FI.Name != Name)
189 continue;
190 // Make sure the function is of the right type (allocator vs deallocator).
191 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
192 return InvalidIdx;
193 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
194 return InvalidIdx;
195
196 return I;
197 }
198 // The function is not tracked.
199 return InvalidIdx;
200}
201
Anna Zaks864d2522011-08-12 21:14:26 +0000202static bool isBadDeallocationArgument(const MemRegion *Arg) {
Jordy Rose3e678142012-03-11 00:08:24 +0000203 if (!Arg)
204 return false;
Anna Zaks864d2522011-08-12 21:14:26 +0000205 if (isa<AllocaRegion>(Arg) ||
206 isa<BlockDataRegion>(Arg) ||
207 isa<TypedRegion>(Arg)) {
208 return true;
209 }
210 return false;
211}
Jordy Rose3e678142012-03-11 00:08:24 +0000212
Anna Zaksca0b57e2011-08-05 00:37:00 +0000213/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000214/// that value is itself an address, and return the corresponding symbol.
215static SymbolRef getAsPointeeSymbol(const Expr *Expr,
216 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000217 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000218 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000219
Anna Zaksca0b57e2011-08-05 00:37:00 +0000220 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
221 StoreManager& SM = C.getStoreManager();
Jordy Rose3e678142012-03-11 00:08:24 +0000222 SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
223 if (sym)
224 return sym;
Anna Zaksca0b57e2011-08-05 00:37:00 +0000225 }
226 return 0;
227}
228
Anna Zaks703ffb12011-08-12 21:56:43 +0000229// When checking for error code, we need to consider the following cases:
230// 1) noErr / [0]
231// 2) someErr / [1, inf]
232// 3) unknown
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000233// If noError, returns true iff (1).
234// If !noError, returns true iff (2).
Anna Zaks703ffb12011-08-12 21:56:43 +0000235bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000236 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000237 SValBuilder &Builder,
238 bool noError) const {
239 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
240 Builder.getSymbolManager().getType(RetSym));
241 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
242 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000243 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000244 if (ErrState == State) {
245 return true;
246 }
247
248 return false;
249}
250
Anna Zaksdd6060e2011-08-23 23:47:36 +0000251// Report deallocator mismatch. Remove the region from tracking - reporting a
252// missing free error after this one is redundant.
253void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000254 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000255 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000256 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000257 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000258 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000259 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000260
261 if (!N)
262 return;
263 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000264 SmallString<80> sbuf;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000265 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000266 unsigned int PDeallocIdx =
267 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000268
269 os << "Deallocator doesn't match the allocator: '"
270 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
271 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000272 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000273 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000274 markInteresting(Report, AP);
Jordan Rose785950e2012-11-02 01:53:40 +0000275 C.emitReport(Report);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000276}
277
Anna Zaksf57be282011-08-01 22:40:01 +0000278void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
279 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000280 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000281 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000282
Jordan Rose5ef6e942012-07-10 23:13:01 +0000283 const FunctionDecl *FD = C.getCalleeDecl(CE);
284 if (!FD || FD->getKind() != Decl::Function)
285 return;
286
287 StringRef funName = C.getCalleeName(FD);
Anna Zaksb805c8f2011-12-01 05:57:37 +0000288 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000289 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000290
Anna Zaksca0b57e2011-08-05 00:37:00 +0000291 // If it is a call to an allocator function, it could be a double allocation.
292 idx = getTrackedFunctionIndex(funName, true);
293 if (idx != InvalidIdx) {
294 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000295 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000296 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000297 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000298 // Remove the value from the state. The new symbol will be added for
299 // tracking when the second allocator is processed in checkPostStmt().
300 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000301 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000302 if (!N)
303 return;
304 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000305 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000306 llvm::raw_svector_ostream os(sbuf);
307 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
308 os << "Allocated data should be released before another call to "
309 << "the allocator: missing a call to '"
310 << FunctionsToTrack[DIdx].Name
311 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000312 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000313 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000314 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000315 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000316 C.emitReport(Report);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000317 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000318 }
319 return;
320 }
321
322 // Is it a call to one of deallocator functions?
323 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000324 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000325 return;
326
Anna Zaks864d2522011-08-12 21:14:26 +0000327 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000328 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000329 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000330
331 // Undef is reported by another checker.
332 if (ArgSVal.isUndef())
333 return;
334
Jordy Rose3e678142012-03-11 00:08:24 +0000335 SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
Anna Zaks864d2522011-08-12 21:14:26 +0000336
Anna Zaks864d2522011-08-12 21:14:26 +0000337 // If the argument is coming from the heap, globals, or unknown, do not
338 // report it.
Jordy Rose3e678142012-03-11 00:08:24 +0000339 bool RegionArgIsBad = false;
340 if (!ArgSM) {
341 if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
342 return;
343 RegionArgIsBad = true;
344 }
Anna Zaks08551b52011-08-04 00:31:38 +0000345
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000346 // Is the argument to the call being tracked?
347 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
348 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
349 return;
350 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000351 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000352 // TODO: We might want a more precise diagnostic for double free
353 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000354 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000355 // It is possible that this is a false positive - the argument might
356 // have entered as an enclosing function parameter.
357 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000358 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000359
Anna Zaks0bd6b112011-10-26 21:06:34 +0000360 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000361 if (!N)
362 return;
363 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000364 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000365 "Trying to free data which has not been allocated.", N);
366 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000367 if (AS)
368 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000369 C.emitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000370 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000371 }
Anna Zaks08551b52011-08-04 00:31:38 +0000372
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000373 // Process functions which might deallocate.
374 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
375
376 if (funName == "CFStringCreateWithBytesNoCopy") {
377 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
378 // NULL ~ default deallocator, so warn.
379 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
380 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000381 const AllocationPair AP = std::make_pair(ArgSM, AS);
382 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000383 return;
384 }
385 // One of the default allocators, so warn.
386 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
387 StringRef DeallocatorName = DE->getFoundDecl()->getName();
388 if (DeallocatorName == "kCFAllocatorDefault" ||
389 DeallocatorName == "kCFAllocatorSystemDefault" ||
390 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000391 const AllocationPair AP = std::make_pair(ArgSM, AS);
392 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000393 return;
394 }
395 // If kCFAllocatorNull, which does not deallocate, we still have to
396 // find the deallocator. Otherwise, assume that the user had written a
397 // custom deallocator which does the right thing.
398 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
399 State = State->remove<AllocatedData>(ArgSM);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000400 C.addTransition(State);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000401 return;
402 }
403 }
404 }
405 return;
406 }
407
Anna Zaks7d458b02011-08-15 23:23:15 +0000408 // The call is deallocating a value we previously allocated, so remove it
409 // from the next state.
410 State = State->remove<AllocatedData>(ArgSM);
411
Anna Zaksdd6060e2011-08-23 23:47:36 +0000412 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000413 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000414 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000415 const AllocationPair AP = std::make_pair(ArgSM, AS);
416 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000417 return;
418 }
419
Anna Zaksee5a21f2011-12-01 16:41:58 +0000420 // If the buffer can be null and the return status can be an error,
421 // report a bad call to free.
422 if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
423 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000424 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000425 if (!N)
426 return;
427 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000428 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000429 "Only call free if a valid (non-NULL) buffer was returned.", N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000430 Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000431 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000432 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000433 C.emitReport(Report);
Anna Zaks703ffb12011-08-12 21:56:43 +0000434 return;
435 }
436
Anna Zaks0bd6b112011-10-26 21:06:34 +0000437 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000438}
439
440void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
441 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000442 ProgramStateRef State = C.getState();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000443 const FunctionDecl *FD = C.getCalleeDecl(CE);
444 if (!FD || FD->getKind() != Decl::Function)
445 return;
446
447 StringRef funName = C.getCalleeName(FD);
Anna Zaksf57be282011-08-01 22:40:01 +0000448
449 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000450 unsigned idx = getTrackedFunctionIndex(funName, true);
451 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000452 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000453
Anna Zaks083fcb22011-08-04 17:28:06 +0000454 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000455 // If the argument entered as an enclosing function parameter, skip it to
456 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000457 if (isEnclosingFunctionParam(ArgExpr) &&
458 C.getLocationContext()->getParent() == 0)
Anna Zaks79c9c752011-08-12 22:47:22 +0000459 return;
460
Anna Zaks864d2522011-08-12 21:14:26 +0000461 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
462 // If the argument points to something that's not a symbolic region, it
463 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000464 // - unknown (cannot reason about it)
465 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000466 // - constant (null - should not be tracked,
467 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000468 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000469
470 // The call return value symbol should stay alive for as long as the
471 // allocated value symbol, since our diagnostics depend on the value
472 // returned by the call. Ex: Data should only be freed if noErr was
473 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000474 SymbolRef RetStatusSymbol =
475 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000476 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
477
478 // Track the allocated value in the checker state.
479 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000480 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000481 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000482 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000483 }
484}
485
Anna Zaks721aa372012-02-28 03:07:06 +0000486// TODO: This logic is the same as in Malloc checker.
Anna Zaksd708bac2012-02-23 22:53:29 +0000487const Stmt *
488MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
489 SymbolRef Sym,
490 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000491 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000492 // Walk the ExplodedGraph backwards and find the first node that referred to
493 // the tracked symbol.
494 const ExplodedNode *AllocNode = N;
495
496 while (N) {
497 if (!N->getState()->get<AllocatedData>(Sym))
498 break;
Anna Zaks721aa372012-02-28 03:07:06 +0000499 // Allocation node, is the last node in the current context in which the
500 // symbol was tracked.
501 if (N->getLocationContext() == LeakContext)
502 AllocNode = N;
Anna Zaksd708bac2012-02-23 22:53:29 +0000503 N = N->pred_empty() ? NULL : *(N->pred_begin());
504 }
505
506 ProgramPoint P = AllocNode->getLocation();
Jordan Rose852aa0d2012-07-10 22:07:52 +0000507 if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
508 return Exit->getCalleeContext()->getCallSite();
509 if (clang::PostStmt *PS = dyn_cast<clang::PostStmt>(&P))
510 return PS->getStmt();
511 return 0;
Anna Zaksd708bac2012-02-23 22:53:29 +0000512}
513
Anna Zakse172e8b2011-08-17 23:00:25 +0000514BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000515 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000516 ExplodedNode *N,
517 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000518 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000519 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000520 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000521 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000522 os << "Allocated data is not released: missing a call to '"
523 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000524
525 // Most bug reports are cached at the location where they occurred.
526 // With leaks, we want to unique them by the location where they were
527 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000528 PathDiagnosticLocation LocUsedForUniqueing;
529 if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
530 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
531 C.getSourceManager(), N->getLocationContext());
Anna Zaksd708bac2012-02-23 22:53:29 +0000532
533 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
Anna Zaks98401112011-08-24 20:52:46 +0000534 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Ted Kremenek76aadc32012-03-09 01:13:14 +0000535 markInteresting(Report, AP);
Anna Zaks703ffb12011-08-12 21:56:43 +0000536 return Report;
537}
538
539void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
540 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000541 ProgramStateRef State = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +0000542 AllocatedDataTy ASet = State->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000543 if (ASet.isEmpty())
544 return;
545
546 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000547 AllocationPairVec Errors;
Jordan Rose166d5022012-11-02 01:54:06 +0000548 for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000549 if (SR.isLive(I->first))
550 continue;
551
552 Changed = true;
553 State = State->remove<AllocatedData>(I->first);
554 // If the allocated symbol is null or if the allocation call might have
555 // returned an error, do not report.
Jordan Roseec8d4202012-11-01 00:18:27 +0000556 ConstraintManager &CMgr = State->getConstraintManager();
557 ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
558 if (AllocFailed.isConstrainedTrue() ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000559 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000560 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000561 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000562 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000563 if (!Changed) {
564 // Generate the new, cleaned up state.
565 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000566 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000567 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000568
Anna Zaksd708bac2012-02-23 22:53:29 +0000569 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
570 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000571
572 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000573 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
574 I != E; ++I) {
Jordan Rose785950e2012-11-02 01:53:40 +0000575 C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000576 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000577
578 // Generate the new, cleaned up state.
579 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000580}
581
Anna Zaks98401112011-08-24 20:52:46 +0000582
583PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
584 const ExplodedNode *N,
585 const ExplodedNode *PrevN,
586 BugReporterContext &BRC,
587 BugReport &BR) {
588 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
589 if (!AS)
590 return 0;
591 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
592 if (ASPrev)
593 return 0;
594
595 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
596 // allocation site.
597 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
598 .getStmt());
599 const FunctionDecl *funDecl = CE->getDirectCallee();
600 assert(funDecl && "We do not support indirect function calls as of now.");
601 StringRef funName = funDecl->getName();
602
603 // Get the expression of the corresponding argument.
604 unsigned Idx = getTrackedFunctionIndex(funName, true);
605 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
606 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000607 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
608 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000609 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000610}
611
612void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
613 mgr.registerChecker<MacOSKeychainAPIChecker>();
614}