xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/MacOSKeychainAPIChecker.cpp (revision 1e809b4c4c526d22c8f892d870856265f940e65a)
1 //==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
2 //
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"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
22 #include "llvm/ADT/SmallString.h"
23 
24 using namespace clang;
25 using namespace ento;
26 
27 namespace {
28 class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
29                                                check::PreStmt<ReturnStmt>,
30                                                check::PostStmt<CallExpr>,
31                                                check::EndPath,
32                                                check::DeadSymbols> {
33   mutable OwningPtr<BugType> BT;
34 
35 public:
36   /// AllocationState is a part of the checker specific state together with the
37   /// MemRegion corresponding to the allocated data.
38   struct AllocationState {
39     /// The index of the allocator function.
40     unsigned int AllocatorIdx;
41     SymbolRef Region;
42 
43     AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
44       AllocatorIdx(Idx),
45       Region(R) {}
46 
47     bool operator==(const AllocationState &X) const {
48       return (AllocatorIdx == X.AllocatorIdx &&
49               Region == X.Region);
50     }
51 
52     void Profile(llvm::FoldingSetNodeID &ID) const {
53       ID.AddInteger(AllocatorIdx);
54       ID.AddPointer(Region);
55     }
56   };
57 
58   void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
59   void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
60   void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
61   void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
62   void checkEndPath(CheckerContext &C) const;
63 
64 private:
65   typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
66   typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
67 
68   enum APIKind {
69     /// 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   };
77   /// 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;
83     APIKind Kind;
84   };
85   static const unsigned InvalidIdx = 100000;
86   static const unsigned FunctionsToTrackSize = 8;
87   static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
88   /// The value, which represents no error return value for allocator functions.
89   static const unsigned NoErr = 0;
90 
91   /// Given the function name, returns the index of the allocator/deallocator
92   /// function.
93   static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
94 
95   inline void initBugType() const {
96     if (!BT)
97       BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
98   }
99 
100   void generateDeallocatorMismatchReport(const AllocationPair &AP,
101                                          const Expr *ArgExpr,
102                                          CheckerContext &C) const;
103 
104   /// Find the allocation site for Sym on the path leading to the node N.
105   const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
106                                 CheckerContext &C) const;
107 
108   BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
109                                                     ExplodedNode *N,
110                                                     CheckerContext &C) const;
111 
112   /// Check if RetSym evaluates to an error value in the current state.
113   bool definitelyReturnedError(SymbolRef RetSym,
114                                ProgramStateRef State,
115                                SValBuilder &Builder,
116                                bool noError = false) const;
117 
118   /// Check if RetSym evaluates to a NoErr value in the current state.
119   bool definitelyDidnotReturnError(SymbolRef RetSym,
120                                    ProgramStateRef State,
121                                    SValBuilder &Builder) const {
122     return definitelyReturnedError(RetSym, State, Builder, true);
123   }
124 
125   /// Mark an AllocationPair interesting for diagnostic reporting.
126   void markInteresting(BugReport *R, const AllocationPair &AP) const {
127     R->markInteresting(AP.first);
128     R->markInteresting(AP.second->Region);
129   }
130 
131   /// The bug visitor which allows us to print extra diagnostics along the
132   /// BugReport path. For example, showing the allocation site of the leaked
133   /// region.
134   class SecKeychainBugVisitor : public BugReporterVisitor {
135   protected:
136     // The allocated region symbol tracked by the main analysis.
137     SymbolRef Sym;
138 
139   public:
140     SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
141     virtual ~SecKeychainBugVisitor() {}
142 
143     void Profile(llvm::FoldingSetNodeID &ID) const {
144       static int X = 0;
145       ID.AddPointer(&X);
146       ID.AddPointer(Sym);
147     }
148 
149     PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
150                                    const ExplodedNode *PrevN,
151                                    BugReporterContext &BRC,
152                                    BugReport &BR);
153   };
154 };
155 }
156 
157 /// ProgramState traits to store the currently allocated (and not yet freed)
158 /// symbols. This is a map from the allocated content symbol to the
159 /// corresponding AllocationState.
160 typedef llvm::ImmutableMap<SymbolRef,
161                        MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
162 
163 namespace { struct AllocatedData {}; }
164 namespace clang { namespace ento {
165 template<> struct ProgramStateTrait<AllocatedData>
166     :  public ProgramStatePartialTrait<AllocatedSetTy > {
167   static void *GDMIndex() { static int index = 0; return &index; }
168 };
169 }}
170 
171 static bool isEnclosingFunctionParam(const Expr *E) {
172   E = E->IgnoreParenCasts();
173   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
174     const ValueDecl *VD = DRE->getDecl();
175     if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
176       return true;
177   }
178   return false;
179 }
180 
181 const MacOSKeychainAPIChecker::ADFunctionInfo
182   MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
183     {"SecKeychainItemCopyContent", 4, 3, ValidAPI},                       // 0
184     {"SecKeychainFindGenericPassword", 6, 3, ValidAPI},                   // 1
185     {"SecKeychainFindInternetPassword", 13, 3, ValidAPI},                 // 2
186     {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI},              // 3
187     {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI},             // 4
188     {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI},    // 5
189     {"free", 0, InvalidIdx, ErrorAPI},                                    // 6
190     {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI},        // 7
191 };
192 
193 unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
194                                                           bool IsAllocator) {
195   for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
196     ADFunctionInfo FI = FunctionsToTrack[I];
197     if (FI.Name != Name)
198       continue;
199     // Make sure the function is of the right type (allocator vs deallocator).
200     if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
201       return InvalidIdx;
202     if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
203       return InvalidIdx;
204 
205     return I;
206   }
207   // The function is not tracked.
208   return InvalidIdx;
209 }
210 
211 static SymbolRef getSymbolForRegion(CheckerContext &C,
212                                    const MemRegion *R) {
213   // Implicit casts (ex: void* -> char*) can turn Symbolic region into element
214   // region, if that is the case, get the underlining region.
215   R = R->StripCasts();
216   if (!isa<SymbolicRegion>(R)) {
217       return 0;
218   }
219   return cast<SymbolicRegion>(R)->getSymbol();
220 }
221 
222 static bool isBadDeallocationArgument(const MemRegion *Arg) {
223   if (isa<AllocaRegion>(Arg) ||
224       isa<BlockDataRegion>(Arg) ||
225       isa<TypedRegion>(Arg)) {
226     return true;
227   }
228   return false;
229 }
230 /// Given the address expression, retrieve the value it's pointing to. Assume
231 /// that value is itself an address, and return the corresponding symbol.
232 static SymbolRef getAsPointeeSymbol(const Expr *Expr,
233                                     CheckerContext &C) {
234   ProgramStateRef State = C.getState();
235   SVal ArgV = State->getSVal(Expr, C.getLocationContext());
236 
237   if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
238     StoreManager& SM = C.getStoreManager();
239     const MemRegion *V = SM.getBinding(State->getStore(), *X).getAsRegion();
240     if (V)
241       return getSymbolForRegion(C, V);
242   }
243   return 0;
244 }
245 
246 // When checking for error code, we need to consider the following cases:
247 // 1) noErr / [0]
248 // 2) someErr / [1, inf]
249 // 3) unknown
250 // If noError, returns true iff (1).
251 // If !noError, returns true iff (2).
252 bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
253                                                       ProgramStateRef State,
254                                                       SValBuilder &Builder,
255                                                       bool noError) const {
256   DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
257     Builder.getSymbolManager().getType(RetSym));
258   DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
259                                                      nonloc::SymbolVal(RetSym));
260   ProgramStateRef ErrState = State->assume(NoErr, noError);
261   if (ErrState == State) {
262     return true;
263   }
264 
265   return false;
266 }
267 
268 // Report deallocator mismatch. Remove the region from tracking - reporting a
269 // missing free error after this one is redundant.
270 void MacOSKeychainAPIChecker::
271   generateDeallocatorMismatchReport(const AllocationPair &AP,
272                                     const Expr *ArgExpr,
273                                     CheckerContext &C) const {
274   ProgramStateRef State = C.getState();
275   State = State->remove<AllocatedData>(AP.first);
276   ExplodedNode *N = C.addTransition(State);
277 
278   if (!N)
279     return;
280   initBugType();
281   SmallString<80> sbuf;
282   llvm::raw_svector_ostream os(sbuf);
283   unsigned int PDeallocIdx =
284                FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
285 
286   os << "Deallocator doesn't match the allocator: '"
287      << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
288   BugReport *Report = new BugReport(*BT, os.str(), N);
289   Report->addVisitor(new SecKeychainBugVisitor(AP.first));
290   Report->addRange(ArgExpr->getSourceRange());
291   markInteresting(Report, AP);
292   C.EmitReport(Report);
293 }
294 
295 void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
296                                            CheckerContext &C) const {
297   unsigned idx = InvalidIdx;
298   ProgramStateRef State = C.getState();
299 
300   StringRef funName = C.getCalleeName(CE);
301   if (funName.empty())
302     return;
303 
304   // If it is a call to an allocator function, it could be a double allocation.
305   idx = getTrackedFunctionIndex(funName, true);
306   if (idx != InvalidIdx) {
307     const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
308     if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
309       if (const AllocationState *AS = State->get<AllocatedData>(V)) {
310         if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
311           // Remove the value from the state. The new symbol will be added for
312           // tracking when the second allocator is processed in checkPostStmt().
313           State = State->remove<AllocatedData>(V);
314           ExplodedNode *N = C.addTransition(State);
315           if (!N)
316             return;
317           initBugType();
318           SmallString<128> sbuf;
319           llvm::raw_svector_ostream os(sbuf);
320           unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
321           os << "Allocated data should be released before another call to "
322               << "the allocator: missing a call to '"
323               << FunctionsToTrack[DIdx].Name
324               << "'.";
325           BugReport *Report = new BugReport(*BT, os.str(), N);
326           Report->addVisitor(new SecKeychainBugVisitor(V));
327           Report->addRange(ArgExpr->getSourceRange());
328           Report->markInteresting(AS->Region);
329           C.EmitReport(Report);
330         }
331       }
332     return;
333   }
334 
335   // Is it a call to one of deallocator functions?
336   idx = getTrackedFunctionIndex(funName, false);
337   if (idx == InvalidIdx)
338     return;
339 
340   // Check the argument to the deallocator.
341   const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
342   SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
343 
344   // Undef is reported by another checker.
345   if (ArgSVal.isUndef())
346     return;
347 
348   const MemRegion *Arg = ArgSVal.getAsRegion();
349   if (!Arg)
350     return;
351 
352   SymbolRef ArgSM = getSymbolForRegion(C, Arg);
353   bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
354   // If the argument is coming from the heap, globals, or unknown, do not
355   // report it.
356   if (!ArgSM && !RegionArgIsBad)
357     return;
358 
359   // Is the argument to the call being tracked?
360   const AllocationState *AS = State->get<AllocatedData>(ArgSM);
361   if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
362     return;
363   }
364   // If trying to free data which has not been allocated yet, report as a bug.
365   // TODO: We might want a more precise diagnostic for double free
366   // (that would involve tracking all the freed symbols in the checker state).
367   if (!AS || RegionArgIsBad) {
368     // It is possible that this is a false positive - the argument might
369     // have entered as an enclosing function parameter.
370     if (isEnclosingFunctionParam(ArgExpr))
371       return;
372 
373     ExplodedNode *N = C.addTransition(State);
374     if (!N)
375       return;
376     initBugType();
377     BugReport *Report = new BugReport(*BT,
378         "Trying to free data which has not been allocated.", N);
379     Report->addRange(ArgExpr->getSourceRange());
380     if (AS)
381       Report->markInteresting(AS->Region);
382     C.EmitReport(Report);
383     return;
384   }
385 
386   // Process functions which might deallocate.
387   if (FunctionsToTrack[idx].Kind == PossibleAPI) {
388 
389     if (funName == "CFStringCreateWithBytesNoCopy") {
390       const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
391       // NULL ~ default deallocator, so warn.
392       if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
393           Expr::NPC_ValueDependentIsNotNull)) {
394         const AllocationPair AP = std::make_pair(ArgSM, AS);
395         generateDeallocatorMismatchReport(AP, ArgExpr, C);
396         return;
397       }
398       // One of the default allocators, so warn.
399       if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
400         StringRef DeallocatorName = DE->getFoundDecl()->getName();
401         if (DeallocatorName == "kCFAllocatorDefault" ||
402             DeallocatorName == "kCFAllocatorSystemDefault" ||
403             DeallocatorName == "kCFAllocatorMalloc") {
404           const AllocationPair AP = std::make_pair(ArgSM, AS);
405           generateDeallocatorMismatchReport(AP, ArgExpr, C);
406           return;
407         }
408         // If kCFAllocatorNull, which does not deallocate, we still have to
409         // find the deallocator. Otherwise, assume that the user had written a
410         // custom deallocator which does the right thing.
411         if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
412           State = State->remove<AllocatedData>(ArgSM);
413           C.addTransition(State);
414           return;
415         }
416       }
417     }
418     return;
419   }
420 
421   // The call is deallocating a value we previously allocated, so remove it
422   // from the next state.
423   State = State->remove<AllocatedData>(ArgSM);
424 
425   // Check if the proper deallocator is used.
426   unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
427   if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
428     const AllocationPair AP = std::make_pair(ArgSM, AS);
429     generateDeallocatorMismatchReport(AP, ArgExpr, C);
430     return;
431   }
432 
433   // If the buffer can be null and the return status can be an error,
434   // report a bad call to free.
435   if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
436       !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
437     ExplodedNode *N = C.addTransition(State);
438     if (!N)
439       return;
440     initBugType();
441     BugReport *Report = new BugReport(*BT,
442         "Only call free if a valid (non-NULL) buffer was returned.", N);
443     Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
444     Report->addRange(ArgExpr->getSourceRange());
445     Report->markInteresting(AS->Region);
446     C.EmitReport(Report);
447     return;
448   }
449 
450   C.addTransition(State);
451 }
452 
453 void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
454                                             CheckerContext &C) const {
455   ProgramStateRef State = C.getState();
456   StringRef funName = C.getCalleeName(CE);
457 
458   // If a value has been allocated, add it to the set for tracking.
459   unsigned idx = getTrackedFunctionIndex(funName, true);
460   if (idx == InvalidIdx)
461     return;
462 
463   const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
464   // If the argument entered as an enclosing function parameter, skip it to
465   // avoid false positives.
466   if (isEnclosingFunctionParam(ArgExpr) &&
467       C.getLocationContext()->getParent() == 0)
468     return;
469 
470   if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
471     // If the argument points to something that's not a symbolic region, it
472     // can be:
473     //  - unknown (cannot reason about it)
474     //  - undefined (already reported by other checker)
475     //  - constant (null - should not be tracked,
476     //              other constant will generate a compiler warning)
477     //  - goto (should be reported by other checker)
478 
479     // The call return value symbol should stay alive for as long as the
480     // allocated value symbol, since our diagnostics depend on the value
481     // returned by the call. Ex: Data should only be freed if noErr was
482     // returned during allocation.)
483     SymbolRef RetStatusSymbol =
484       State->getSVal(CE, C.getLocationContext()).getAsSymbol();
485     C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
486 
487     // Track the allocated value in the checker state.
488     State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
489                                                          RetStatusSymbol));
490     assert(State);
491     C.addTransition(State);
492   }
493 }
494 
495 void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
496                                            CheckerContext &C) const {
497   const Expr *retExpr = S->getRetValue();
498   if (!retExpr)
499     return;
500 
501   // If inside inlined call, skip it.
502   if (C.getLocationContext()->getParent() != 0)
503     return;
504 
505   // Check  if the value is escaping through the return.
506   ProgramStateRef state = C.getState();
507   const MemRegion *V =
508     state->getSVal(retExpr, C.getLocationContext()).getAsRegion();
509   if (!V)
510     return;
511   state = state->remove<AllocatedData>(getSymbolForRegion(C, V));
512 
513   // Proceed from the new state.
514   C.addTransition(state);
515 }
516 
517 // TODO: This logic is the same as in Malloc checker.
518 const Stmt *
519 MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
520                                            SymbolRef Sym,
521                                            CheckerContext &C) const {
522   const LocationContext *LeakContext = N->getLocationContext();
523   // Walk the ExplodedGraph backwards and find the first node that referred to
524   // the tracked symbol.
525   const ExplodedNode *AllocNode = N;
526 
527   while (N) {
528     if (!N->getState()->get<AllocatedData>(Sym))
529       break;
530     // Allocation node, is the last node in the current context in which the
531     // symbol was tracked.
532     if (N->getLocationContext() == LeakContext)
533       AllocNode = N;
534     N = N->pred_empty() ? NULL : *(N->pred_begin());
535   }
536 
537   ProgramPoint P = AllocNode->getLocation();
538   if (!isa<StmtPoint>(P))
539     return 0;
540   return cast<clang::PostStmt>(P).getStmt();
541 }
542 
543 BugReport *MacOSKeychainAPIChecker::
544   generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
545                                          ExplodedNode *N,
546                                          CheckerContext &C) const {
547   const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
548   initBugType();
549   SmallString<70> sbuf;
550   llvm::raw_svector_ostream os(sbuf);
551   os << "Allocated data is not released: missing a call to '"
552       << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
553 
554   // Most bug reports are cached at the location where they occurred.
555   // With leaks, we want to unique them by the location where they were
556   // allocated, and only report a single path.
557   PathDiagnosticLocation LocUsedForUniqueing;
558   if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
559     LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
560                             C.getSourceManager(), N->getLocationContext());
561 
562   BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
563   Report->addVisitor(new SecKeychainBugVisitor(AP.first));
564   markInteresting(Report, AP);
565   return Report;
566 }
567 
568 void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
569                                                CheckerContext &C) const {
570   ProgramStateRef State = C.getState();
571   AllocatedSetTy ASet = State->get<AllocatedData>();
572   if (ASet.isEmpty())
573     return;
574 
575   bool Changed = false;
576   AllocationPairVec Errors;
577   for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
578     if (SR.isLive(I->first))
579       continue;
580 
581     Changed = true;
582     State = State->remove<AllocatedData>(I->first);
583     // If the allocated symbol is null or if the allocation call might have
584     // returned an error, do not report.
585     if (State->getSymVal(I->first) ||
586         definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
587       continue;
588     Errors.push_back(std::make_pair(I->first, &I->second));
589   }
590   if (!Changed) {
591     // Generate the new, cleaned up state.
592     C.addTransition(State);
593     return;
594   }
595 
596   static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
597   ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
598 
599   // Generate the error reports.
600   for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
601                                                        I != E; ++I) {
602     C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
603   }
604 
605   // Generate the new, cleaned up state.
606   C.addTransition(State, N);
607 }
608 
609 // TODO: Remove this after we ensure that checkDeadSymbols are always called.
610 void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
611   ProgramStateRef state = C.getState();
612 
613   // If inside inlined call, skip it.
614   if (C.getLocationContext()->getParent() != 0)
615     return;
616 
617   AllocatedSetTy AS = state->get<AllocatedData>();
618   if (AS.isEmpty())
619     return;
620 
621   // Anything which has been allocated but not freed (nor escaped) will be
622   // found here, so report it.
623   bool Changed = false;
624   AllocationPairVec Errors;
625   for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
626     Changed = true;
627     state = state->remove<AllocatedData>(I->first);
628     // If the allocated symbol is null or if error code was returned at
629     // allocation, do not report.
630     if (state->getSymVal(I.getKey()) ||
631         definitelyReturnedError(I->second.Region, state,
632                                 C.getSValBuilder())) {
633       continue;
634     }
635     Errors.push_back(std::make_pair(I->first, &I->second));
636   }
637 
638   // If no change, do not generate a new state.
639   if (!Changed) {
640     C.addTransition(state);
641     return;
642   }
643 
644   static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
645   ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
646 
647   // Generate the error reports.
648   for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
649                                                        I != E; ++I) {
650     C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
651   }
652 
653   C.addTransition(state, N);
654 }
655 
656 
657 PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
658                                                       const ExplodedNode *N,
659                                                       const ExplodedNode *PrevN,
660                                                       BugReporterContext &BRC,
661                                                       BugReport &BR) {
662   const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
663   if (!AS)
664     return 0;
665   const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
666   if (ASPrev)
667     return 0;
668 
669   // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
670   // allocation site.
671   const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
672                                                             .getStmt());
673   const FunctionDecl *funDecl = CE->getDirectCallee();
674   assert(funDecl && "We do not support indirect function calls as of now.");
675   StringRef funName = funDecl->getName();
676 
677   // Get the expression of the corresponding argument.
678   unsigned Idx = getTrackedFunctionIndex(funName, true);
679   assert(Idx != InvalidIdx && "This should be a call to an allocator.");
680   const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
681   PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
682                              N->getLocationContext());
683   return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
684 }
685 
686 void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
687   mgr.registerChecker<MacOSKeychainAPIChecker>();
688 }
689