blob: bc6663d2370268bc4897c9d5ace1965549144ac6 [file] [log] [blame]
Anna Zaks083fcb22011-08-04 17:28:06 +00001//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
Anna Zaksf57be282011-08-01 22:40:01 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// This checker flags misuses of KeyChainAPI. In particular, the password data
10// allocated/returned by SecKeychainItemCopyContent,
11// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
12// to be freed using a call to SecKeychainItemFreeContent.
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
16#include "clang/StaticAnalyzer/Core/Checker.h"
17#include "clang/StaticAnalyzer/Core/CheckerManager.h"
Anna Zaks03826aa2011-08-04 00:26:57 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Anna Zaksf57be282011-08-01 22:40:01 +000019#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek18c66fd2011-08-15 22:09:50 +000020#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
Anna Zaksf57be282011-08-01 22:40:01 +000022
23using namespace clang;
24using namespace ento;
25
26namespace {
27class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
28 check::PreStmt<ReturnStmt>,
29 check::PostStmt<CallExpr>,
Anna Zaks703ffb12011-08-12 21:56:43 +000030 check::EndPath,
31 check::DeadSymbols> {
Anna Zaks03826aa2011-08-04 00:26:57 +000032 mutable llvm::OwningPtr<BugType> BT;
33
Anna Zaksf57be282011-08-01 22:40:01 +000034public:
Anna Zaks864d2522011-08-12 21:14:26 +000035 /// AllocationState is a part of the checker specific state together with the
36 /// MemRegion corresponding to the allocated data.
37 struct AllocationState {
38 const Expr *Address;
39 /// The index of the allocator function.
40 unsigned int AllocatorIdx;
41 SymbolRef RetValue;
42
43 AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
44 Address(E),
45 AllocatorIdx(Idx),
46 RetValue(R) {}
47
48 bool operator==(const AllocationState &X) const {
49 return Address == X.Address;
50 }
51 void Profile(llvm::FoldingSetNodeID &ID) const {
52 ID.AddPointer(Address);
53 ID.AddInteger(AllocatorIdx);
54 }
55 };
56
Anna Zaksf57be282011-08-01 22:40:01 +000057 void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
58 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
59 void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
60
Anna Zaks703ffb12011-08-12 21:56:43 +000061 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
Anna Zaksf57be282011-08-01 22:40:01 +000062 void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;
63
64private:
Anna Zaks98401112011-08-24 20:52:46 +000065 typedef std::pair<SymbolRef, const AllocationState&> AllocationPair;
66 typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
67
68 enum APIKind {
Anna Zaks6cf0ed02011-08-24 00:06:27 +000069 /// Denotes functions tracked by this checker.
70 ValidAPI = 0,
71 /// The functions commonly/mistakenly used in place of the given API.
72 ErrorAPI = 1,
73 /// The functions which may allocate the data. These are tracked to reduce
74 /// the false alarm rate.
75 PossibleAPI = 2
76 };
Anna Zaks083fcb22011-08-04 17:28:06 +000077 /// Stores the information about the allocator and deallocator functions -
78 /// these are the functions the checker is tracking.
79 struct ADFunctionInfo {
80 const char* Name;
81 unsigned int Param;
82 unsigned int DeallocatorIdx;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000083 APIKind Kind;
Anna Zaks083fcb22011-08-04 17:28:06 +000084 };
85 static const unsigned InvalidIdx = 100000;
Anna Zaks6cf0ed02011-08-24 00:06:27 +000086 static const unsigned FunctionsToTrackSize = 8;
Anna Zaks083fcb22011-08-04 17:28:06 +000087 static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
Anna Zaks5a58c6d2011-08-05 23:52:45 +000088 /// The value, which represents no error return value for allocator functions.
89 static const unsigned NoErr = 0;
Anna Zaksf57be282011-08-01 22:40:01 +000090
Anna Zaks083fcb22011-08-04 17:28:06 +000091 /// Given the function name, returns the index of the allocator/deallocator
92 /// function.
Anna Zaks98401112011-08-24 20:52:46 +000093 static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
Anna Zaks03826aa2011-08-04 00:26:57 +000094
95 inline void initBugType() const {
96 if (!BT)
97 BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
98 }
Anna Zaks703ffb12011-08-12 21:56:43 +000099
Anna Zaksdd6060e2011-08-23 23:47:36 +0000100 void generateDeallocatorMismatchReport(const AllocationState &AS,
101 const Expr *ArgExpr,
102 CheckerContext &C,
103 SymbolRef ArgSM) const;
104
Anna Zaks98401112011-08-24 20:52:46 +0000105 BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zakse172e8b2011-08-17 23:00:25 +0000106 ExplodedNode *N) const;
Anna Zaks703ffb12011-08-12 21:56:43 +0000107
108 /// Check if RetSym evaluates to an error value in the current state.
109 bool definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000110 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000111 SValBuilder &Builder,
112 bool noError = false) const;
113
114 /// Check if RetSym evaluates to a NoErr value in the current state.
115 bool definitelyDidnotReturnError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000116 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000117 SValBuilder &Builder) const {
118 return definitelyReturnedError(RetSym, State, Builder, true);
119 }
120
Anna Zaks98401112011-08-24 20:52:46 +0000121 /// The bug visitor which allows us to print extra diagnostics along the
122 /// BugReport path. For example, showing the allocation site of the leaked
123 /// region.
124 class SecKeychainBugVisitor : public BugReporterVisitor {
125 protected:
126 // The allocated region symbol tracked by the main analysis.
127 SymbolRef Sym;
128
129 public:
130 SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
131 virtual ~SecKeychainBugVisitor() {}
132
133 void Profile(llvm::FoldingSetNodeID &ID) const {
134 static int X = 0;
135 ID.AddPointer(&X);
136 ID.AddPointer(Sym);
137 }
138
139 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
140 const ExplodedNode *PrevN,
141 BugReporterContext &BRC,
142 BugReport &BR);
143 };
Anna Zaksf57be282011-08-01 22:40:01 +0000144};
145}
146
Anna Zaks7d458b02011-08-15 23:23:15 +0000147/// ProgramState traits to store the currently allocated (and not yet freed)
148/// symbols. This is a map from the allocated content symbol to the
149/// corresponding AllocationState.
Anna Zaks864d2522011-08-12 21:14:26 +0000150typedef llvm::ImmutableMap<SymbolRef,
151 MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
Anna Zaksf57be282011-08-01 22:40:01 +0000152
153namespace { struct AllocatedData {}; }
154namespace clang { namespace ento {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000155template<> struct ProgramStateTrait<AllocatedData>
156 : public ProgramStatePartialTrait<AllocatedSetTy > {
Anna Zaksf57be282011-08-01 22:40:01 +0000157 static void *GDMIndex() { static int index = 0; return &index; }
158};
159}}
160
Anna Zaks03826aa2011-08-04 00:26:57 +0000161static bool isEnclosingFunctionParam(const Expr *E) {
162 E = E->IgnoreParenCasts();
163 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
164 const ValueDecl *VD = DRE->getDecl();
165 if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
166 return true;
167 }
168 return false;
169}
170
Anna Zaks083fcb22011-08-04 17:28:06 +0000171const MacOSKeychainAPIChecker::ADFunctionInfo
172 MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000173 {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
174 {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
175 {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
176 {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
177 {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
178 {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
179 {"free", 0, InvalidIdx, ErrorAPI}, // 6
180 {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
Anna Zaks083fcb22011-08-04 17:28:06 +0000181};
182
183unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
Anna Zaks98401112011-08-24 20:52:46 +0000184 bool IsAllocator) {
Anna Zaks083fcb22011-08-04 17:28:06 +0000185 for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
186 ADFunctionInfo FI = FunctionsToTrack[I];
187 if (FI.Name != Name)
188 continue;
189 // Make sure the function is of the right type (allocator vs deallocator).
190 if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
191 return InvalidIdx;
192 if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
193 return InvalidIdx;
194
195 return I;
196 }
197 // The function is not tracked.
198 return InvalidIdx;
199}
200
Anna Zaks864d2522011-08-12 21:14:26 +0000201static SymbolRef getSymbolForRegion(CheckerContext &C,
202 const MemRegion *R) {
Anna Zaks31e10282011-08-23 23:56:12 +0000203 if (!isa<SymbolicRegion>(R)) {
204 // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
205 // region, if that is the case, get the underlining region.
206 if (const ElementRegion *ER = dyn_cast<ElementRegion>(R))
207 R = ER->getAsArrayOffset().getRegion();
208 else
209 return 0;
210 }
Anna Zaks864d2522011-08-12 21:14:26 +0000211 return cast<SymbolicRegion>(R)->getSymbol();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000212}
213
Anna Zaks864d2522011-08-12 21:14:26 +0000214static bool isBadDeallocationArgument(const MemRegion *Arg) {
215 if (isa<AllocaRegion>(Arg) ||
216 isa<BlockDataRegion>(Arg) ||
217 isa<TypedRegion>(Arg)) {
218 return true;
219 }
220 return false;
221}
Anna Zaksca0b57e2011-08-05 00:37:00 +0000222/// Given the address expression, retrieve the value it's pointing to. Assume
Anna Zaks864d2522011-08-12 21:14:26 +0000223/// that value is itself an address, and return the corresponding symbol.
224static SymbolRef getAsPointeeSymbol(const Expr *Expr,
225 CheckerContext &C) {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000226 const ProgramState *State = C.getState();
Anna Zaksca0b57e2011-08-05 00:37:00 +0000227 SVal ArgV = State->getSVal(Expr);
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000228
Anna Zaksca0b57e2011-08-05 00:37:00 +0000229 if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
230 StoreManager& SM = C.getStoreManager();
231 const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
Anna Zaks5a58c6d2011-08-05 23:52:45 +0000232 if (V)
Anna Zaks864d2522011-08-12 21:14:26 +0000233 return getSymbolForRegion(C, V);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000234 }
235 return 0;
236}
237
Anna Zaks703ffb12011-08-12 21:56:43 +0000238// When checking for error code, we need to consider the following cases:
239// 1) noErr / [0]
240// 2) someErr / [1, inf]
241// 3) unknown
242// If noError, returns true iff (1).
243// If !noError, returns true iff (2).
244bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000245 const ProgramState *State,
Anna Zaks703ffb12011-08-12 21:56:43 +0000246 SValBuilder &Builder,
247 bool noError) const {
248 DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
249 Builder.getSymbolManager().getType(RetSym));
250 DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
251 nonloc::SymbolVal(RetSym));
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000252 const ProgramState *ErrState = State->assume(NoErr, noError);
Anna Zaks703ffb12011-08-12 21:56:43 +0000253 if (ErrState == State) {
254 return true;
255 }
256
257 return false;
258}
259
Anna Zaksdd6060e2011-08-23 23:47:36 +0000260// Report deallocator mismatch. Remove the region from tracking - reporting a
261// missing free error after this one is redundant.
262void MacOSKeychainAPIChecker::
263 generateDeallocatorMismatchReport(const AllocationState &AS,
264 const Expr *ArgExpr,
265 CheckerContext &C,
266 SymbolRef ArgSM) const {
267 const ProgramState *State = C.getState();
268 State = State->remove<AllocatedData>(ArgSM);
269 ExplodedNode *N = C.generateNode(State);
270
271 if (!N)
272 return;
273 initBugType();
274 llvm::SmallString<80> sbuf;
275 llvm::raw_svector_ostream os(sbuf);
276 unsigned int PDeallocIdx = FunctionsToTrack[AS.AllocatorIdx].DeallocatorIdx;
277
278 os << "Deallocator doesn't match the allocator: '"
279 << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
280 BugReport *Report = new BugReport(*BT, os.str(), N);
281 Report->addRange(ArgExpr->getSourceRange());
282 C.EmitReport(Report);
283}
284
Anna Zaksf57be282011-08-01 22:40:01 +0000285void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
286 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000287 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000288 const Expr *Callee = CE->getCallee();
289 SVal L = State->getSVal(Callee);
Anna Zaksca0b57e2011-08-05 00:37:00 +0000290 unsigned idx = InvalidIdx;
Anna Zaksf57be282011-08-01 22:40:01 +0000291
292 const FunctionDecl *funDecl = L.getAsFunctionDecl();
293 if (!funDecl)
294 return;
295 IdentifierInfo *funI = funDecl->getIdentifier();
296 if (!funI)
297 return;
298 StringRef funName = funI->getName();
299
Anna Zaksca0b57e2011-08-05 00:37:00 +0000300 // If it is a call to an allocator function, it could be a double allocation.
301 idx = getTrackedFunctionIndex(funName, true);
302 if (idx != InvalidIdx) {
303 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000304 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
Anna Zaksca0b57e2011-08-05 00:37:00 +0000305 if (const AllocationState *AS = State->get<AllocatedData>(V)) {
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000306 if (!definitelyReturnedError(AS->RetValue, State, C.getSValBuilder())) {
307 // Remove the value from the state. The new symbol will be added for
308 // tracking when the second allocator is processed in checkPostStmt().
309 State = State->remove<AllocatedData>(V);
310 ExplodedNode *N = C.generateNode(State);
311 if (!N)
312 return;
313 initBugType();
314 llvm::SmallString<128> sbuf;
315 llvm::raw_svector_ostream os(sbuf);
316 unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
317 os << "Allocated data should be released before another call to "
318 << "the allocator: missing a call to '"
319 << FunctionsToTrack[DIdx].Name
320 << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000321 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaksf0c7fe52011-08-16 16:30:24 +0000322 Report->addRange(ArgExpr->getSourceRange());
323 C.EmitReport(Report);
324 }
Anna Zaksca0b57e2011-08-05 00:37:00 +0000325 }
326 return;
327 }
328
329 // Is it a call to one of deallocator functions?
330 idx = getTrackedFunctionIndex(funName, false);
Anna Zaks083fcb22011-08-04 17:28:06 +0000331 if (idx == InvalidIdx)
Anna Zaks08551b52011-08-04 00:31:38 +0000332 return;
333
Anna Zaks864d2522011-08-12 21:14:26 +0000334 // Check the argument to the deallocator.
Anna Zaks083fcb22011-08-04 17:28:06 +0000335 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
Anna Zaks864d2522011-08-12 21:14:26 +0000336 SVal ArgSVal = State->getSVal(ArgExpr);
337
338 // Undef is reported by another checker.
339 if (ArgSVal.isUndef())
340 return;
341
342 const MemRegion *Arg = ArgSVal.getAsRegion();
Anna Zaks08551b52011-08-04 00:31:38 +0000343 if (!Arg)
344 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000345
346 SymbolRef ArgSM = getSymbolForRegion(C, Arg);
347 bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
348 // If the argument is coming from the heap, globals, or unknown, do not
349 // report it.
350 if (!ArgSM && !RegionArgIsBad)
351 return;
Anna Zaks08551b52011-08-04 00:31:38 +0000352
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000353 // Is the argument to the call being tracked?
354 const AllocationState *AS = State->get<AllocatedData>(ArgSM);
355 if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
356 return;
357 }
Anna Zaks67f7fa42011-08-15 18:42:00 +0000358 // If trying to free data which has not been allocated yet, report as a bug.
Anna Zaks7d458b02011-08-15 23:23:15 +0000359 // TODO: We might want a more precise diagnostic for double free
360 // (that would involve tracking all the freed symbols in the checker state).
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000361 if (!AS || RegionArgIsBad) {
Anna Zaks08551b52011-08-04 00:31:38 +0000362 // It is possible that this is a false positive - the argument might
363 // have entered as an enclosing function parameter.
364 if (isEnclosingFunctionParam(ArgExpr))
Anna Zaksf57be282011-08-01 22:40:01 +0000365 return;
Anna Zaks03826aa2011-08-04 00:26:57 +0000366
Anna Zaks08551b52011-08-04 00:31:38 +0000367 ExplodedNode *N = C.generateNode(State);
368 if (!N)
369 return;
370 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000371 BugReport *Report = new BugReport(*BT,
Anna Zaks08551b52011-08-04 00:31:38 +0000372 "Trying to free data which has not been allocated.", N);
373 Report->addRange(ArgExpr->getSourceRange());
374 C.EmitReport(Report);
Anna Zaks083fcb22011-08-04 17:28:06 +0000375 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000376 }
Anna Zaks08551b52011-08-04 00:31:38 +0000377
Anna Zaks6cf0ed02011-08-24 00:06:27 +0000378 // Process functions which might deallocate.
379 if (FunctionsToTrack[idx].Kind == PossibleAPI) {
380
381 if (funName == "CFStringCreateWithBytesNoCopy") {
382 const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
383 // NULL ~ default deallocator, so warn.
384 if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
385 Expr::NPC_ValueDependentIsNotNull)) {
386 generateDeallocatorMismatchReport(*AS, ArgExpr, C, ArgSM);
387 return;
388 }
389 // One of the default allocators, so warn.
390 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
391 StringRef DeallocatorName = DE->getFoundDecl()->getName();
392 if (DeallocatorName == "kCFAllocatorDefault" ||
393 DeallocatorName == "kCFAllocatorSystemDefault" ||
394 DeallocatorName == "kCFAllocatorMalloc") {
395 generateDeallocatorMismatchReport(*AS, ArgExpr, C, ArgSM);
396 return;
397 }
398 // If kCFAllocatorNull, which does not deallocate, we still have to
399 // find the deallocator. Otherwise, assume that the user had written a
400 // custom deallocator which does the right thing.
401 if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
402 State = State->remove<AllocatedData>(ArgSM);
403 C.addTransition(State);
404 return;
405 }
406 }
407 }
408 return;
409 }
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 Zaksdd6060e2011-08-23 23:47:36 +0000418 generateDeallocatorMismatchReport(*AS, ArgExpr, C, ArgSM);
Anna Zaks76cbb752011-08-04 21:53:01 +0000419 return;
420 }
421
Anna Zaks703ffb12011-08-12 21:56:43 +0000422 // If the return status is undefined or is error, report a bad call to free.
423 if (!definitelyDidnotReturnError(AS->RetValue, State, C.getSValBuilder())) {
424 ExplodedNode *N = C.generateNode(State);
425 if (!N)
426 return;
427 initBugType();
Anna Zakse172e8b2011-08-17 23:00:25 +0000428 BugReport *Report = new BugReport(*BT,
Anna Zaks703ffb12011-08-12 21:56:43 +0000429 "Call to free data when error was returned during allocation.", N);
430 Report->addRange(ArgExpr->getSourceRange());
431 C.EmitReport(Report);
432 return;
433 }
434
Anna Zaks08551b52011-08-04 00:31:38 +0000435 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000436}
437
438void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
439 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000440 const ProgramState *State = C.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000441 const Expr *Callee = CE->getCallee();
442 SVal L = State->getSVal(Callee);
Anna Zaksf57be282011-08-01 22:40:01 +0000443
444 const FunctionDecl *funDecl = L.getAsFunctionDecl();
445 if (!funDecl)
446 return;
447 IdentifierInfo *funI = funDecl->getIdentifier();
448 if (!funI)
449 return;
450 StringRef funName = funI->getName();
451
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.
460 if (isEnclosingFunctionParam(ArgExpr))
461 return;
462
Anna Zaks864d2522011-08-12 21:14:26 +0000463 if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
464 // If the argument points to something that's not a symbolic region, it
465 // can be:
Anna Zaks08551b52011-08-04 00:31:38 +0000466 // - unknown (cannot reason about it)
467 // - undefined (already reported by other checker)
Anna Zaks083fcb22011-08-04 17:28:06 +0000468 // - constant (null - should not be tracked,
469 // other constant will generate a compiler warning)
Anna Zaks08551b52011-08-04 00:31:38 +0000470 // - goto (should be reported by other checker)
Anna Zaks703ffb12011-08-12 21:56:43 +0000471
472 // The call return value symbol should stay alive for as long as the
473 // allocated value symbol, since our diagnostics depend on the value
474 // returned by the call. Ex: Data should only be freed if noErr was
475 // returned during allocation.)
Anna Zaks864d2522011-08-12 21:14:26 +0000476 SymbolRef RetStatusSymbol = State->getSVal(CE).getAsSymbol();
Anna Zaks703ffb12011-08-12 21:56:43 +0000477 C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
478
479 // Track the allocated value in the checker state.
480 State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
Anna Zaks864d2522011-08-12 21:14:26 +0000481 RetStatusSymbol));
Anna Zaks703ffb12011-08-12 21:56:43 +0000482 assert(State);
483 C.addTransition(State);
Anna Zaksf57be282011-08-01 22:40:01 +0000484 }
485}
486
487void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
488 CheckerContext &C) const {
489 const Expr *retExpr = S->getRetValue();
490 if (!retExpr)
491 return;
492
493 // Check if the value is escaping through the return.
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000494 const ProgramState *state = C.getState();
Anna Zaks03826aa2011-08-04 00:26:57 +0000495 const MemRegion *V = state->getSVal(retExpr).getAsRegion();
Anna Zaksf57be282011-08-01 22:40:01 +0000496 if (!V)
497 return;
Anna Zaks864d2522011-08-12 21:14:26 +0000498 state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
Anna Zaksf57be282011-08-01 22:40:01 +0000499
Anna Zaks03826aa2011-08-04 00:26:57 +0000500 // Proceed from the new state.
501 C.addTransition(state);
Anna Zaksf57be282011-08-01 22:40:01 +0000502}
503
Anna Zakse172e8b2011-08-17 23:00:25 +0000504BugReport *MacOSKeychainAPIChecker::
Anna Zaks98401112011-08-24 20:52:46 +0000505 generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
Anna Zaks703ffb12011-08-12 21:56:43 +0000506 ExplodedNode *N) const {
Anna Zaks98401112011-08-24 20:52:46 +0000507 const AllocationState &AS = AP.second;
Anna Zaks703ffb12011-08-12 21:56:43 +0000508 const ADFunctionInfo &FI = FunctionsToTrack[AS.AllocatorIdx];
509 initBugType();
Anna Zaks67f7fa42011-08-15 18:42:00 +0000510 llvm::SmallString<70> sbuf;
511 llvm::raw_svector_ostream os(sbuf);
Anna Zaks98401112011-08-24 20:52:46 +0000512
Anna Zaks703ffb12011-08-12 21:56:43 +0000513 os << "Allocated data is not released: missing a call to '"
514 << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
Anna Zakse172e8b2011-08-17 23:00:25 +0000515 BugReport *Report = new BugReport(*BT, os.str(), N);
Anna Zaks98401112011-08-24 20:52:46 +0000516 Report->addVisitor(new SecKeychainBugVisitor(AP.first));
517 Report->addRange(SourceRange());
Anna Zaks703ffb12011-08-12 21:56:43 +0000518 return Report;
519}
520
521void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
522 CheckerContext &C) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000523 const ProgramState *State = C.getState();
Anna Zaks703ffb12011-08-12 21:56:43 +0000524 AllocatedSetTy ASet = State->get<AllocatedData>();
525 if (ASet.isEmpty())
526 return;
527
528 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000529 AllocationPairVec Errors;
Anna Zaks703ffb12011-08-12 21:56:43 +0000530 for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
531 if (SR.isLive(I->first))
532 continue;
533
534 Changed = true;
535 State = State->remove<AllocatedData>(I->first);
536 // If the allocated symbol is null or if the allocation call might have
537 // returned an error, do not report.
538 if (State->getSymVal(I->first) ||
539 definitelyReturnedError(I->second.RetValue, State, C.getSValBuilder()))
540 continue;
Anna Zaks98401112011-08-24 20:52:46 +0000541 Errors.push_back(std::make_pair(I->first, I->second));
Anna Zaks703ffb12011-08-12 21:56:43 +0000542 }
543 if (!Changed)
544 return;
545
546 // Generate the new, cleaned up state.
547 ExplodedNode *N = C.generateNode(State);
548 if (!N)
549 return;
550
551 // Generate the error reports.
Anna Zaks98401112011-08-24 20:52:46 +0000552 for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
553 I != E; ++I) {
554 C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000555 }
556}
557
558// TODO: Remove this after we ensure that checkDeadSymbols are always called.
Anna Zaksf57be282011-08-01 22:40:01 +0000559void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
Anna Zaks03826aa2011-08-04 00:26:57 +0000560 ExprEngine &Eng) const {
Ted Kremenek18c66fd2011-08-15 22:09:50 +0000561 const ProgramState *state = B.getState();
Anna Zaksf57be282011-08-01 22:40:01 +0000562 AllocatedSetTy AS = state->get<AllocatedData>();
Anna Zaks703ffb12011-08-12 21:56:43 +0000563 if (AS.isEmpty())
Anna Zaks03826aa2011-08-04 00:26:57 +0000564 return;
Anna Zaksf57be282011-08-01 22:40:01 +0000565
566 // Anything which has been allocated but not freed (nor escaped) will be
567 // found here, so report it.
Anna Zaks703ffb12011-08-12 21:56:43 +0000568 bool Changed = false;
Anna Zaks98401112011-08-24 20:52:46 +0000569 AllocationPairVec Errors;
Anna Zaks03826aa2011-08-04 00:26:57 +0000570 for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000571 Changed = true;
572 state = state->remove<AllocatedData>(I->first);
573 // If the allocated symbol is null or if error code was returned at
574 // allocation, do not report.
575 if (state->getSymVal(I.getKey()) ||
576 definitelyReturnedError(I->second.RetValue, state,
577 Eng.getSValBuilder())) {
578 continue;
579 }
Anna Zaks98401112011-08-24 20:52:46 +0000580 Errors.push_back(std::make_pair(I->first, I->second));
Anna Zaksf57be282011-08-01 22:40:01 +0000581 }
Anna Zaks703ffb12011-08-12 21:56:43 +0000582
583 // If no change, do not generate a new state.
584 if (!Changed)
585 return;
586
587 ExplodedNode *N = B.generateNode(state);
588 if (!N)
589 return;
590
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) {
Anna Zaks703ffb12011-08-12 21:56:43 +0000594 Eng.getBugReporter().EmitReport(
Anna Zaks98401112011-08-24 20:52:46 +0000595 generateAllocatedDataNotReleasedReport(*I, N));
Anna Zaks703ffb12011-08-12 21:56:43 +0000596 }
Anna Zaks98401112011-08-24 20:52:46 +0000597}
Anna Zaks703ffb12011-08-12 21:56:43 +0000598
Anna Zaks98401112011-08-24 20:52:46 +0000599
600PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
601 const ExplodedNode *N,
602 const ExplodedNode *PrevN,
603 BugReporterContext &BRC,
604 BugReport &BR) {
605 const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
606 if (!AS)
607 return 0;
608 const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
609 if (ASPrev)
610 return 0;
611
612 // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
613 // allocation site.
614 const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
615 .getStmt());
616 const FunctionDecl *funDecl = CE->getDirectCallee();
617 assert(funDecl && "We do not support indirect function calls as of now.");
618 StringRef funName = funDecl->getName();
619
620 // Get the expression of the corresponding argument.
621 unsigned Idx = getTrackedFunctionIndex(funName, true);
622 assert(Idx != InvalidIdx && "This should be a call to an allocator.");
623 const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
624 PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager());
625 return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
Anna Zaksf57be282011-08-01 22:40:01 +0000626}
627
628void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
629 mgr.registerChecker<MacOSKeychainAPIChecker>();
630}