blob: 52e29368cea380e180b89e440c3b2c625a8daa10 [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> {
Stephen Hines651f13c2014-04-23 16:59:28 -070032 mutable std::unique_ptr<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)
Stephen Hines651f13c2014-04-23 16:59:28 -070094 BT.reset(new BugType(this, "Improper use of SecKeychain API",
Anna Zaks88530f82013-04-03 19:28:22 +000095 "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) {}
Pirama Arumuga Nainar58878f82015-05-06 11:48:57 -0700140 ~SecKeychainBugVisitor() override {}
Anna Zaks98401112011-08-24 20:52:46 +0000141
Stephen Hines651f13c2014-04-23 16:59:28 -0700142 void Profile(llvm::FoldingSetNodeID &ID) const override {
Anna Zaks98401112011-08-24 20:52:46 +0000143 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,
Stephen Hines651f13c2014-04-23 16:59:28 -0700151 BugReport &BR) override;
Anna Zaks98401112011-08-24 20:52:46 +0000152 };
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 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700227 return nullptr;
Anna Zaksca0b57e2011-08-05 00:37:00 +0000228}
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);
Stephen Hines176edba2014-12-01 14:53:08 -0800273 Report->addVisitor(llvm::make_unique<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) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700295 unsigned paramIdx = FunctionsToTrack[idx].Param;
296 if (CE->getNumArgs() <= paramIdx)
297 return;
298
299 const Expr *ArgExpr = CE->getArg(paramIdx);
Anna Zaks864d2522011-08-12 21:14:26 +0000300 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000301 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zakseacd2b42011-08-25 00:59:06 +0000302 if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000303 // Remove the value from the state. The new symbol will be added for
304 // tracking when the second allocator is processed in checkPostStmt().
305 State = State->remove<AllocatedData>(V);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000306 ExplodedNode *N = C.addTransition(State);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000307 if (!N)
308 return;
309 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000310 SmallString<128> sbuf;
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000311 llvm::raw_svector_ostream os(sbuf);
312 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
313 os << "Allocated data should be released before another call to "
314 << "the allocator: missing a call to '"
315 << FunctionsToTrack[DIdx].Name
316 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000317 BugReport *Report = new BugReport(*BT, os.str(), N);
Stephen Hines176edba2014-12-01 14:53:08 -0800318 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(V));
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000319 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000320 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000321 C.emitReport(Report);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000322 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000323 }
324 return;
325 }
326
327 // Is it a call to one of deallocator functions?
328 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000329 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000330 return;
331
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700332 unsigned paramIdx = FunctionsToTrack[idx].Param;
333 if (CE->getNumArgs() <= paramIdx)
334 return;
335
Anna Zaks864d2522011-08-12 21:14:26 +0000336 // Check the argument to the deallocator.
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700337 const Expr *ArgExpr = CE->getArg(paramIdx);
Ted Kremenek5eca4822012-01-06 22:09:28 +0000338 SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
Anna Zaks864d2522011-08-12 21:14:26 +0000339
340 // Undef is reported by another checker.
341 if (ArgSVal.isUndef())
342 return;
343
Jordy Rose3e678142012-03-11 00:08:24 +0000344 SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
Anna Zaks864d2522011-08-12 21:14:26 +0000345
Anna Zaks864d2522011-08-12 21:14:26 +0000346 // If the argument is coming from the heap, globals, or unknown, do not
347 // report it.
Jordy Rose3e678142012-03-11 00:08:24 +0000348 bool RegionArgIsBad = false;
349 if (!ArgSM) {
350 if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
351 return;
352 RegionArgIsBad = true;
353 }
Anna Zaks08551b52011-08-04 00:31:38 +0000354
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000355 // Is the argument to the call being tracked?
356 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
357 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
358 return;
359 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000360 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000361 // TODO: We might want a more precise diagnostic for double free
362 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000363 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000364 // It is possible that this is a false positive - the argument might
365 // have entered as an enclosing function parameter.
366 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000367 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000368
Anna Zaks0bd6b112011-10-26 21:06:34 +0000369 ExplodedNode *N = C.addTransition(State);
Anna Zaks08551b52011-08-04 00:31:38 +0000370 if (!N)
371 return;
372 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000373 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000374 "Trying to free data which has not been allocated.", N);
375 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000376 if (AS)
377 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000378 C.emitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000379 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000380 }
Anna Zaks08551b52011-08-04 00:31:38 +0000381
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000382 // Process functions which might deallocate.
383 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
384
385 if (funName == "CFStringCreateWithBytesNoCopy") {
386 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
387 // NULL ~ default deallocator, so warn.
388 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
389 Expr::NPC_ValueDependentIsNotNull)) {
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 // One of the default allocators, so warn.
395 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
396 StringRef DeallocatorName = DE->getFoundDecl()->getName();
397 if (DeallocatorName == "kCFAllocatorDefault" ||
398 DeallocatorName == "kCFAllocatorSystemDefault" ||
399 DeallocatorName == "kCFAllocatorMalloc") {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000400 const AllocationPair AP = std::make_pair(ArgSM, AS);
401 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000402 return;
403 }
404 // If kCFAllocatorNull, which does not deallocate, we still have to
Anna Zaks0b67c752013-01-07 19:13:00 +0000405 // find the deallocator.
406 if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000407 return;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000408 }
Anna Zaks0b67c752013-01-07 19:13:00 +0000409 // In all other cases, assume the user supplied a correct deallocator
410 // that will free memory so stop tracking.
411 State = State->remove<AllocatedData>(ArgSM);
412 C.addTransition(State);
413 return;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000414 }
Anna Zaks0b67c752013-01-07 19:13:00 +0000415
416 llvm_unreachable("We know of no other possible APIs.");
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000417 }
418
Anna Zaks7d458b02011-08-15 23:23:15 +0000419 // The call is deallocating a value we previously allocated, so remove it
420 // from the next state.
421 State = State->remove<AllocatedData>(ArgSM);
422
Anna Zaksdd6060e2011-08-23 23:47:36 +0000423 // Check if the proper deallocator is used.
Anna Zaks76cbb752011-08-04 21:53:01 +0000424 unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000425 if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
Anna Zaks6b7aad92011-08-25 00:32:42 +0000426 const AllocationPair AP = std::make_pair(ArgSM, AS);
427 generateDeallocatorMismatchReport(AP, ArgExpr, C);
Anna Zaks76cbb752011-08-04 21:53:01 +0000428 return;
429 }
430
Anna Zaksee5a21f2011-12-01 16:41:58 +0000431 // If the buffer can be null and the return status can be an error,
432 // report a bad call to free.
David Blaikie5251abe2013-02-20 05:52:05 +0000433 if (State->assume(ArgSVal.castAs<DefinedSVal>(), false) &&
Anna Zaksee5a21f2011-12-01 16:41:58 +0000434 !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
Anna Zaks0bd6b112011-10-26 21:06:34 +0000435 ExplodedNode *N = C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000436 if (!N)
437 return;
438 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000439 BugReport *Report = new BugReport(*BT,
Anna Zaksee5a21f2011-12-01 16:41:58 +0000440 "Only call free if a valid (non-NULL) buffer was returned.", N);
Stephen Hines176edba2014-12-01 14:53:08 -0800441 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(ArgSM));
Anna Zaks703ffb12011-08-12 21:56:43 +0000442 Report->addRange(ArgExpr->getSourceRange());
Ted Kremenek76aadc32012-03-09 01:13:14 +0000443 Report->markInteresting(AS->Region);
Jordan Rose785950e2012-11-02 01:53:40 +0000444 C.emitReport(Report);
Anna Zaks703ffb12011-08-12 21:56:43 +0000445 return;
446 }
447
Anna Zaks0bd6b112011-10-26 21:06:34 +0000448 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000449}
450
451void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
452 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000453 ProgramStateRef State = C.getState();
Jordan Rose5ef6e942012-07-10 23:13:01 +0000454 const FunctionDecl *FD = C.getCalleeDecl(CE);
455 if (!FD || FD->getKind() != Decl::Function)
456 return;
457
458 StringRef funName = C.getCalleeName(FD);
Anna Zaksf57be282011-08-01 22:40:01 +0000459
460 // If a value has been allocated, add it to the set for tracking.
Anna Zaks083fcb22011-08-04 17:28:06 +0000461 unsigned idx = getTrackedFunctionIndex(funName, true);
462 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000463 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000464
Anna Zaks083fcb22011-08-04 17:28:06 +0000465 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks79c9c752011-08-12 22:47:22 +0000466 // If the argument entered as an enclosing function parameter, skip it to
467 // avoid false positives.
Anna Zaks9c1e1bd2012-02-21 00:00:44 +0000468 if (isEnclosingFunctionParam(ArgExpr) &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700469 C.getLocationContext()->getParent() == nullptr)
Anna Zaks79c9c752011-08-12 22:47:22 +0000470 return;
471
Anna Zaks864d2522011-08-12 21:14:26 +0000472 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
473 // If the argument points to something that's not a symbolic region, it
474 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000475 // - unknown (cannot reason about it)
476 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000477 // - constant (null - should not be tracked,
478 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000479 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000480
481 // The call return value symbol should stay alive for as long as the
482 // allocated value symbol, since our diagnostics depend on the value
483 // returned by the call. Ex: Data should only be freed if noErr was
484 // returned during allocation.)
Ted Kremenek5eca4822012-01-06 22:09:28 +0000485 SymbolRef RetStatusSymbol =
486 State->getSVal(CE, C.getLocationContext()).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000487 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
488
489 // Track the allocated value in the checker state.
490 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000491 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000492 assert(State);
Anna Zaks0bd6b112011-10-26 21:06:34 +0000493 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000494 }
495}
496
Anna Zaks721aa372012-02-28 03:07:06 +0000497// TODO: This logic is the same as in Malloc checker.
Anna Zaks97bfb552013-01-08 00:25:29 +0000498const ExplodedNode *
499MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
Anna Zaksd708bac2012-02-23 22:53:29 +0000500 SymbolRef Sym,
501 CheckerContext &C) const {
Anna Zaks721aa372012-02-28 03:07:06 +0000502 const LocationContext *LeakContext = N->getLocationContext();
Anna Zaksd708bac2012-02-23 22:53:29 +0000503 // Walk the ExplodedGraph backwards and find the first node that referred to
504 // the tracked symbol.
505 const ExplodedNode *AllocNode = N;
506
507 while (N) {
508 if (!N->getState()->get<AllocatedData>(Sym))
509 break;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700510 // Allocation node, is the last node in the current or parent context in
511 // which the symbol was tracked.
512 const LocationContext *NContext = N->getLocationContext();
513 if (NContext == LeakContext ||
514 NContext->isParentOf(LeakContext))
Anna Zaks721aa372012-02-28 03:07:06 +0000515 AllocNode = N;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700516 N = N->pred_empty() ? nullptr : *(N->pred_begin());
Anna Zaksd708bac2012-02-23 22:53:29 +0000517 }
518
Anna Zaks97bfb552013-01-08 00:25:29 +0000519 return AllocNode;
Anna Zaksd708bac2012-02-23 22:53:29 +0000520}
521
Anna Zakse172e8b2011-08-17 23:00:25 +0000522BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000523 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaksd708bac2012-02-23 22:53:29 +0000524 ExplodedNode *N,
525 CheckerContext &C) const {
Anna Zaks5eb7d822011-08-24 21:58:55 +0000526 const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
Anna Zaks703ffb12011-08-12 21:56:43 +0000527 initBugType();
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000528 SmallString<70> sbuf;
Anna Zaks67f7fa42011-08-15 18:42:00 +0000529 llvm::raw_svector_ostream os(sbuf);
Anna Zaks703ffb12011-08-12 21:56:43 +0000530 os << "Allocated data is not released: missing a call to '"
531 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zaksd708bac2012-02-23 22:53:29 +0000532
533 // Most bug reports are cached at the location where they occurred.
534 // With leaks, we want to unique them by the location where they were
535 // allocated, and only report a single path.
Anna Zaks721aa372012-02-28 03:07:06 +0000536 PathDiagnosticLocation LocUsedForUniqueing;
Anna Zaks97bfb552013-01-08 00:25:29 +0000537 const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700538 const Stmt *AllocStmt = nullptr;
Anna Zaks97bfb552013-01-08 00:25:29 +0000539 ProgramPoint P = AllocNode->getLocation();
David Blaikie7a95de62013-02-21 22:23:56 +0000540 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
Anna Zaks97bfb552013-01-08 00:25:29 +0000541 AllocStmt = Exit->getCalleeContext()->getCallSite();
David Blaikie7a95de62013-02-21 22:23:56 +0000542 else if (Optional<clang::PostStmt> PS = P.getAs<clang::PostStmt>())
Anna Zaks97bfb552013-01-08 00:25:29 +0000543 AllocStmt = PS->getStmt();
Anna Zaksd708bac2012-02-23 22:53:29 +0000544
Anna Zaks97bfb552013-01-08 00:25:29 +0000545 if (AllocStmt)
546 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
547 C.getSourceManager(),
548 AllocNode->getLocationContext());
549
550 BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing,
551 AllocNode->getLocationContext()->getDecl());
552
Stephen Hines176edba2014-12-01 14:53:08 -0800553 Report->addVisitor(llvm::make_unique<SecKeychainBugVisitor>(AP.first));
Ted Kremenek76aadc32012-03-09 01:13:14 +0000554 markInteresting(Report, AP);
Anna Zaks703ffb12011-08-12 21:56:43 +0000555 return Report;
556}
557
558void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
559 CheckerContext &C) const {
Ted Kremenek8bef8232012-01-26 21:29:00 +0000560 ProgramStateRef State = C.getState();
Jordan Rose166d5022012-11-02 01:54:06 +0000561 AllocatedDataTy ASet = State->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000562 if (ASet.isEmpty())
563 return;
564
565 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000566 AllocationPairVec Errors;
Jordan Rose166d5022012-11-02 01:54:06 +0000567 for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000568 if (SR.isLive(I->first))
569 continue;
570
571 Changed = true;
572 State = State->remove<AllocatedData>(I->first);
573 // If the allocated symbol is null or if the allocation call might have
574 // returned an error, do not report.
Jordan Roseec8d4202012-11-01 00:18:27 +0000575 ConstraintManager &CMgr = State->getConstraintManager();
576 ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
577 if (AllocFailed.isConstrainedTrue() ||
Anna Zakseacd2b42011-08-25 00:59:06 +0000578 definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
Anna Zaks703ffb12011-08-12 21:56:43 +0000579 continue;
Anna Zaks5eb7d822011-08-24 21:58:55 +0000580 Errors.push_back(std::make_pair(I->first, &I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000581 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000582 if (!Changed) {
583 // Generate the new, cleaned up state.
584 C.addTransition(State);
Anna Zaks703ffb12011-08-12 21:56:43 +0000585 return;
Anna Zaksd708bac2012-02-23 22:53:29 +0000586 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000587
Stephen Hines651f13c2014-04-23 16:59:28 -0700588 static CheckerProgramPointTag Tag(this, "DeadSymbolsLeak");
Anna Zaksd708bac2012-02-23 22:53:29 +0000589 ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
Anna Zaks703ffb12011-08-12 21:56:43 +0000590
591 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000592 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
593 I != E; ++I) {
Jordan Rose785950e2012-11-02 01:53:40 +0000594 C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
Anna Zaks703ffb12011-08-12 21:56:43 +0000595 }
Anna Zaksd708bac2012-02-23 22:53:29 +0000596
597 // Generate the new, cleaned up state.
598 C.addTransition(State, N);
Anna Zaks703ffb12011-08-12 21:56:43 +0000599}
600
Anna Zaks98401112011-08-24 20:52:46 +0000601
602PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
603 const ExplodedNode *N,
604 const ExplodedNode *PrevN,
605 BugReporterContext &BRC,
606 BugReport &BR) {
607 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
608 if (!AS)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700609 return nullptr;
Anna Zaks98401112011-08-24 20:52:46 +0000610 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
611 if (ASPrev)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700612 return nullptr;
Anna Zaks98401112011-08-24 20:52:46 +0000613
614 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
615 // allocation site.
David Blaikie7a95de62013-02-21 22:23:56 +0000616 const CallExpr *CE =
617 cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
Anna Zaks98401112011-08-24 20:52:46 +0000618 const FunctionDecl *funDecl = CE->getDirectCallee();
619 assert(funDecl && "We do not support indirect function calls as of now.");
620 StringRef funName = funDecl->getName();
621
622 // Get the expression of the corresponding argument.
623 unsigned Idx = getTrackedFunctionIndex(funName, true);
624 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
625 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
Anna Zaks220ac8c2011-09-15 01:08:34 +0000626 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
627 N->getLocationContext());
Anna Zaks98401112011-08-24 20:52:46 +0000628 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000629}
630
631void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
632 mgr.registerChecker<MacOSKeychainAPIChecker>();
633}