blob: f1f06c798cde2dc28d15c41a55b97c95a83354d8 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaksf57be282011-08-01 22:40:01 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
18#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#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;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000063 typedef SmallVector<AllocationPair, 2> AllocationPairVec;
Anna Zaks98401112011-08-24 20:52:46 +000064
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)
Anna Zaks88530f82013-04-03 19:28:22 +000094 BT.reset(new BugType("Improper use of SecKeychain API",
95 "API Misuse (Apple)"));
Anna Zaks03826aa2011-08-04 00:26:57 +000096 }
Anna Zaks703ffb12011-08-12 21:56:43 +000097
Anna Zaks6b7aad92011-08-25 00:32:42 +000098 void generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +000099 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000100 CheckerContext &C) const;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000101
Anna Zaksd708bac2012-02-23 22:53:29 +0000102 /// Find the allocation site for Sym on the path leading to the node N.
Anna Zaks97bfb552013-01-08 00:25:29 +0000103 const ExplodedNode *getAllocationNode(const ExplodedNode *N, SymbolRef Sym,
104 CheckerContext &C) const;
Anna Zaksd708bac2012-02-23 22:53:29 +0000105
Anna Zaks98401112011-08-24 20:52:46 +0000106 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000107 ExplodedNode *N,
108 CheckerContext &C) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000109
110 /// Check if RetSym evaluates to an error value in the current state.
111 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000112 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000113 SValBuilder &Builder,
114 bool noError = false) const;
115
116 /// Check if RetSym evaluates to a NoErr value in the current state.
117 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000118 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000119 SValBuilder &Builder) const {
120 return definitelyReturnedError(RetSym, State, Builder, true);
121 }
Ted Kremenek76aadc32012-03-09 01:13:14 +0000122
123 /// Mark an AllocationPair interesting for diagnostic reporting.
124 void markInteresting(BugReport *R, const AllocationPair &AP) const {
125 R->markInteresting(AP.first);
126 R->markInteresting(AP.second->Region);
127 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000128
Anna Zaks98401112011-08-24 20:52:46 +0000129 /// The bug visitor which allows us to print extra diagnostics along the
130 /// BugReport path. For example, showing the allocation site of the leaked
131 /// region.
Jordy Rose01153492012-03-24 02:45:35 +0000132 class SecKeychainBugVisitor
133 : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
Anna Zaks98401112011-08-24 20:52:46 +0000134 protected:
135 // The allocated region symbol tracked by the main analysis.
136 SymbolRef Sym;
137
138 public:
139 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
140 virtual ~SecKeychainBugVisitor() {}
141
142 void Profile(llvm::FoldingSetNodeID &ID) const {
143 static int X = 0;
144 ID.AddPointer(&X);
145 ID.AddPointer(Sym);
146 }
147
148 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
149 const ExplodedNode *PrevN,
150 BugReporterContext &BRC,
151 BugReport &BR);
152 };
Anna Zaksf57be282011-08-01 22:40:01 +0000153};
154}
155
Anna Zaks7d458b02011-08-15 23:23:15 +0000156/// ProgramState traits to store the currently allocated (and not yet freed)
157/// symbols. This is a map from the allocated content symbol to the
158/// corresponding AllocationState.
Jordan Rose166d5022012-11-02 01:54:06 +0000159REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
160 SymbolRef,
161 MacOSKeychainAPIChecker::AllocationState)
Anna Zaksf57be282011-08-01 22:40:01 +0000162
Anna Zaks03826aa2011-08-04 00:26:57 +0000163static bool isEnclosingFunctionParam(const Expr *E) {
164 E = E->IgnoreParenCasts();
165 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
166 const ValueDecl *VD = DRE->getDecl();
167 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
168 return true;
169 }
170 return false;
171}
172
Anna Zaks083fcb22011-08-04 17:28:06 +0000173const MacOSKeychainAPIChecker::ADFunctionInfo
174 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000175 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
176 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
177 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
178 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
179 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
180 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
181 {"free", 0, InvalidIdx, ErrorAPI}, // 6
182 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000183};
184
185unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000186 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000187 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
188 ADFunctionInfo FI = FunctionsToTrack[I];
189 if (FI.Name != Name)
190 continue;
191 // Make sure the function is of the right type (allocator vs deallocator).
192 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
193 return InvalidIdx;
194 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
195 return InvalidIdx;
196
197 return I;
198 }
199 // The function is not tracked.
200 return InvalidIdx;
201}
202
Anna Zaks864d2522011-08-12 21:14:26 +0000203static bool isBadDeallocationArgument(const MemRegion *Arg) {
Jordy Rose3e678142012-03-11 00:08:24 +0000204 if (!Arg)
205 return false;
Anna Zaks864d2522011-08-12 21:14:26 +0000206 if (isa<AllocaRegion>(Arg) ||
207 isa<BlockDataRegion>(Arg) ||
208 isa<TypedRegion>(Arg)) {
209 return true;
210 }
211 return false;
212}
Jordy Rose3e678142012-03-11 00:08:24 +0000213
Anna Zaksca0b57e2011-08-05 00:37:00 +0000214/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000215/// that value is itself an address, and return the corresponding symbol.
216static SymbolRef getAsPointeeSymbol(const Expr *Expr,
217 CheckerContext &C) {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000218 ProgramStateRef State = C.getState();
Ted Kremenek5eca4822012-01-06 22:09:28 +0000219 SVal ArgV = State->getSVal(Expr, C.getLocationContext());
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000220
David Blaikiedc84cd52013-02-20 22:23:23 +0000221 if (Optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000222 StoreManager& SM = C.getStoreManager();
Jordy Rose3e678142012-03-11 00:08:24 +0000223 SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
224 if (sym)
225 return sym;
Anna Zaksca0b57e2011-08-05 00:37:00 +0000226 }
227 return 0;
228}
229
Anna Zaks703ffb12011-08-12 21:56:43 +0000230// When checking for error code, we need to consider the following cases:
231// 1) noErr / [0]
232// 2) someErr / [1, inf]
233// 3) unknown
Sylvestre Ledruf3477c12012-09-27 10:16:10 +0000234// If noError, returns true iff (1).
235// If !noError, returns true iff (2).
Anna Zaks703ffb12011-08-12 21:56:43 +0000236bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek8bef8232012-01-26 21:29:00 +0000237 ProgramStateRef State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000238 SValBuilder &Builder,
239 bool noError) const {
240 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
241 Builder.getSymbolManager().getType(RetSym));
242 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
243 nonloc::SymbolVal(RetSym));
Ted Kremenek8bef8232012-01-26 21:29:00 +0000244 ProgramStateRef ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000245 if (ErrState == State) {
246 return true;
247 }
248
249 return false;
250}
251
Anna Zaksdd6060e2011-08-23 23:47:36 +0000252// Report deallocator mismatch. Remove the region from tracking - reporting a
253// missing free error after this one is redundant.
254void MacOSKeychainAPIChecker::
Anna Zaks6b7aad92011-08-25 00:32:42 +0000255 generateDeallocatorMismatchReport(const AllocationPair &AP,
Anna Zaksdd6060e2011-08-23 23:47:36 +0000256 const Expr *ArgExpr,
Anna Zaks6b7aad92011-08-25 00:32:42 +0000257 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000258 ProgramStateRef State = C.getState();
Anna Zaks6b7aad92011-08-25 00:32:42 +0000259 State = State->remove<AllocatedData>(AP.first);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000260 ExplodedNode *N = C.addTransition(State);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000261
262 if (!N)
263 return;
264 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000265 SmallString<80> sbuf;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000266 llvm::raw_svector_ostream os(sbuf);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000267 unsigned int PDeallocIdx =
268 FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
Anna Zaksdd6060e2011-08-23 23:47:36 +0000269
270 os << "Deallocator doesn't match the allocator: '"
271 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
272 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000273 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Anna Zaksdd6060e2011-08-23 23:47:36 +0000274 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000275 markInteresting(Report, AP);
Jordan Rose785950e2012-11-02 01:53:40 +0000276 C.emitReport(Report);
Anna Zaksdd6060e2011-08-23 23:47:36 +0000277}
278
Anna Zaksf57be282011-08-01 22:40:01 +0000279void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
280 CheckerContext &C) const {
Anna Zaksca0b57e2011-08-05 00:37:00 +0000281 unsigned idx = InvalidIdx;
Ted Kremenek8bef8232012-01-26 21:29:00 +0000282 ProgramStateRef State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000283
Jordan Rose5ef6e942012-07-10 23:13:01 +0000284 const FunctionDecl *FD = C.getCalleeDecl(CE);
285 if (!FD || FD->getKind() != Decl::Function)
286 return;
287
288 StringRef funName = C.getCalleeName(FD);
Anna Zaksb805c8f2011-12-01 05:57:37 +0000289 if (funName.empty())
Anna Zaksf57be282011-08-01 22:40:01 +0000290 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000291
Anna Zaksca0b57e2011-08-05 00:37:00 +0000292 // If it is a call to an allocator function, it could be a double allocation.
293 idx = getTrackedFunctionIndex(funName, true);
294 if (idx != InvalidIdx) {
295 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000296 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000297 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000298 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000299 // Remove the value from the state. The new symbol will be added for
300 // tracking when the second allocator is processed in checkPostStmt().
301 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000302 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000303 if (!N)
304 return;
305 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000306 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000307 llvm::raw_svector_ostream os(sbuf);
308 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
309 os << "Allocated data should be released before another call to "
310 << "the allocator: missing a call to '"
311 << FunctionsToTrack[DIdx].Name
312 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000313 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks6b7aad92011-08-25 00:32:42 +0000314 Report->addVisitor(new SecKeychainBugVisitor(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000315 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000316 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000317 C.emitReport(Report);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000318 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000319 }
320 return;
321 }
322
323 // Is it a call to one of deallocator functions?
324 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000325 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000326 return;
327
Anna Zaks864d2522011-08-12 21:14:26 +0000328 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000329 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000330 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000331
332 // Undef is reported by another checker.
333 if (ArgSVal.isUndef())
334 return;
335
Jordy Rose3e678142012-03-11 00:08:24 +0000336 SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
Anna Zaks864d2522011-08-12 21:14:26 +0000337
Anna Zaks864d2522011-08-12 21:14:26 +0000338 // If the argument is coming from the heap, globals, or unknown, do not
339 // report it.
Jordy Rose3e678142012-03-11 00:08:24 +0000340 bool RegionArgIsBad = false;
341 if (!ArgSM) {
342 if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
343 return;
344 RegionArgIsBad = true;
345 }
Anna Zaks08551b52011-08-04 00:31:38 +0000346
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000347 // Is the argument to the call being tracked?
348 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
349 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
350 return;
351 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000352 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000353 // TODO: We might want a more precise diagnostic for double free
354 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000355 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000356 // It is possible that this is a false positive - the argument might
357 // have entered as an enclosing function parameter.
358 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000359 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000360
Anna Zaks0bd6b112011-10-26 21:06:34 +0000361 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000362 if (!N)
363 return;
364 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000365 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000366 "Trying to free data which has not been allocated.", N);
367 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000368 if (AS)
369 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000370 C.emitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000371 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000372 }
Anna Zaks08551b52011-08-04 00:31:38 +0000373
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000374 // Process functions which might deallocate.
375 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
376
377 if (funName == "CFStringCreateWithBytesNoCopy") {
378 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
379 // NULL ~ default deallocator, so warn.
380 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
381 Expr::NPC_ValueDependentIsNotNull)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000382 const AllocationPair AP = std::make_pair(ArgSM, AS);
383 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000384 return;
385 }
386 // One of the default allocators, so warn.
387 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
388 StringRef DeallocatorName = DE->getFoundDecl()->getName();
389 if (DeallocatorName == "kCFAllocatorDefault" ||
390 DeallocatorName == "kCFAllocatorSystemDefault" ||
391 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000392 const AllocationPair AP = std::make_pair(ArgSM, AS);
393 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000394 return;
395 }
396 // If kCFAllocatorNull, which does not deallocate, we still have to
Anna Zaks0b67c752013-01-07 19:13:00 +0000397 // find the deallocator.
398 if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000399 return;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000400 }
Anna Zaks0b67c752013-01-07 19:13:00 +0000401 // In all other cases, assume the user supplied a correct deallocator
402 // that will free memory so stop tracking.
403 State = State->remove<AllocatedData>(ArgSM);
404 C.addTransition(State);
405 return;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000406 }
Anna Zaks0b67c752013-01-07 19:13:00 +0000407
408 llvm_unreachable("We know of no other possible APIs.");
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000409 }
410
Anna Zaks7d458b02011-08-15 23:23:15 +0000411 // The call is deallocating a value we previously allocated, so remove it
412 // from the next state.
413 State = State->remove<AllocatedData>(ArgSM);
414
Anna Zaksdd6060e2011-08-23 23:47:36 +0000415 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000416 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000417 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000418 const AllocationPair AP = std::make_pair(ArgSM, AS);
419 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000420 return;
421 }
422
Anna Zaksee5a21f2011-12-01 16:41:58 +0000423 // If the buffer can be null and the return status can be an error,
424 // report a bad call to free.
David Blaikie5251abe2013-02-20 05:52:05 +0000425 if (State->assume(ArgSVal.castAs<DefinedSVal>(), false) &&
Anna Zaksee5a21f2011-12-01 16:41:58 +0000426 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000427 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000428 if (!N)
429 return;
430 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000431 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000432 "Only call free if a valid (non-NULL) buffer was returned.", 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());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000435 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000436 C.emitReport(Report);
Anna Zaks703ffb12011-08-12 21:56:43 +0000437 return;
438 }
439
Anna Zaks0bd6b112011-10-26 21:06:34 +0000440 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000441}
442
443void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
444 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000445 ProgramStateRef State = C.getState();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000446 const FunctionDecl *FD = C.getCalleeDecl(CE);
447 if (!FD || FD->getKind() != Decl::Function)
448 return;
449
450 StringRef funName = C.getCalleeName(FD);
Anna Zaksf57be282011-08-01 22:40:01 +0000451
452 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000453 unsigned idx = getTrackedFunctionIndex(funName, true);
454 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000455 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000456
Anna Zaks083fcb22011-08-04 17:28:06 +0000457 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000458 // If the argument entered as an enclosing function parameter, skip it to
459 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000460 if (isEnclosingFunctionParam(ArgExpr) &&
461 C.getLocationContext()->getParent() == 0)
Anna Zaks79c9c752011-08-12 22:47:22 +0000462 return;
463
Anna Zaks864d2522011-08-12 21:14:26 +0000464 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
465 // If the argument points to something that's not a symbolic region, it
466 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000467 // - unknown (cannot reason about it)
468 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000469 // - constant (null - should not be tracked,
470 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000471 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000472
473 // The call return value symbol should stay alive for as long as the
474 // allocated value symbol, since our diagnostics depend on the value
475 // returned by the call. Ex: Data should only be freed if noErr was
476 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000477 SymbolRef RetStatusSymbol =
478 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000479 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
480
481 // Track the allocated value in the checker state.
482 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000483 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000484 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000485 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000486 }
487}
488
Anna Zaks721aa372012-02-28 03:07:06 +0000489// TODO: This logic is the same as in Malloc checker.
Anna Zaks97bfb552013-01-08 00:25:29 +0000490const ExplodedNode *
491MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
Anna Zaksd708bac2012-02-23 22:53:29 +0000492 SymbolRef Sym,
493 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000494 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000495 // Walk the ExplodedGraph backwards and find the first node that referred to
496 // the tracked symbol.
497 const ExplodedNode *AllocNode = N;
498
499 while (N) {
500 if (!N->getState()->get<AllocatedData>(Sym))
501 break;
Anna Zaks721aa372012-02-28 03:07:06 +0000502 // Allocation node, is the last node in the current context in which the
503 // symbol was tracked.
504 if (N->getLocationContext() == LeakContext)
505 AllocNode = N;
Anna Zaksd708bac2012-02-23 22:53:29 +0000506 N = N->pred_empty() ? NULL : *(N->pred_begin());
507 }
508
Anna Zaks97bfb552013-01-08 00:25:29 +0000509 return AllocNode;
Anna Zaksd708bac2012-02-23 22:53:29 +0000510}
511
Anna Zakse172e8b2011-08-17 23:00:25 +0000512BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000513 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000514 ExplodedNode *N,
515 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000516 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000517 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000518 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000519 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000520 os << "Allocated data is not released: missing a call to '"
521 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000522
523 // Most bug reports are cached at the location where they occurred.
524 // With leaks, we want to unique them by the location where they were
525 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000526 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +0000527 const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
528 const Stmt *AllocStmt = 0;
529 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +0000530 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +0000531 AllocStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +0000532 else if (Optional<clang::PostStmt> PS = P.getAs<clang::PostStmt>())
Anna Zaks97bfb552013-01-08 00:25:29 +0000533 AllocStmt = PS->getStmt();
Anna Zaksd708bac2012-02-23 22:53:29 +0000534
Anna Zaks97bfb552013-01-08 00:25:29 +0000535 if (AllocStmt)
536 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
537 C.getSourceManager(),
538 AllocNode->getLocationContext());
539
540 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing,
541 AllocNode->getLocationContext()->getDecl());
542
Anna Zaks98401112011-08-24 20:52:46 +0000543 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
Ted Kremenek76aadc32012-03-09 01:13:14 +0000544 markInteresting(Report, AP);
Anna Zaks703ffb12011-08-12 21:56:43 +0000545 return Report;
546}
547
548void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
549 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000550 ProgramStateRef State = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +0000551 AllocatedDataTy ASet = State->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000552 if (ASet.isEmpty())
553 return;
554
555 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000556 AllocationPairVec Errors;
Jordan Rose166d5022012-11-02 01:54:06 +0000557 for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000558 if (SR.isLive(I->first))
559 continue;
560
561 Changed = true;
562 State = State->remove<AllocatedData>(I->first);
563 // If the allocated symbol is null or if the allocation call might have
564 // returned an error, do not report.
Jordan Roseec8d4202012-11-01 00:18:27 +0000565 ConstraintManager &CMgr = State->getConstraintManager();
566 ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
567 if (AllocFailed.isConstrainedTrue() ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000568 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000569 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000570 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000571 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000572 if (!Changed) {
573 // Generate the new, cleaned up state.
574 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000575 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000576 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000577
Anna Zaksd708bac2012-02-23 22:53:29 +0000578 static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
579 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000580
581 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000582 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
583 I != E; ++I) {
Jordan Rose785950e2012-11-02 01:53:40 +0000584 C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000585 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000586
587 // Generate the new, cleaned up state.
588 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000589}
590
Anna Zaks98401112011-08-24 20:52:46 +0000591
592PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
593 const ExplodedNode *N,
594 const ExplodedNode *PrevN,
595 BugReporterContext &BRC,
596 BugReport &BR) {
597 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
598 if (!AS)
599 return 0;
600 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
601 if (ASPrev)
602 return 0;
603
604 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
605 // allocation site.
David Blaikie7a95de62013-02-21 22:23:56 +0000606 const CallExpr *CE =
607 cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
Anna Zaks98401112011-08-24 20:52:46 +0000608 const FunctionDecl *funDecl = CE->getDirectCallee();
609 assert(funDecl && "We do not support indirect function calls as of now.");
610 StringRef funName = funDecl->getName();
611
612 // Get the expression of the corresponding argument.
613 unsigned Idx = getTrackedFunctionIndex(funName, true);
614 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
615 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000616 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
617 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000618 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000619}
620
621void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
622 mgr.registerChecker<MacOSKeychainAPIChecker>();
623}