MacOSKeychainAPIChecker.cpp revision 243830
1226586Sdim//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
2226586Sdim//
3226586Sdim//                     The LLVM Compiler Infrastructure
4226586Sdim//
5226586Sdim// This file is distributed under the University of Illinois Open Source
6226586Sdim// License. See LICENSE.TXT for details.
7226586Sdim//
8226586Sdim//===----------------------------------------------------------------------===//
9226586Sdim// This checker flags misuses of KeyChainAPI. In particular, the password data
10226586Sdim// allocated/returned by SecKeychainItemCopyContent,
11226586Sdim// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
12226586Sdim// to be freed using a call to SecKeychainItemFreeContent.
13226586Sdim//===----------------------------------------------------------------------===//
14226586Sdim
15226586Sdim#include "ClangSACheckers.h"
16226586Sdim#include "clang/StaticAnalyzer/Core/Checker.h"
17226586Sdim#include "clang/StaticAnalyzer/Core/CheckerManager.h"
18226586Sdim#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21226586Sdim#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
22234353Sdim#include "llvm/ADT/SmallString.h"
23226586Sdim
24226586Sdimusing namespace clang;
25226586Sdimusing namespace ento;
26226586Sdim
27226586Sdimnamespace {
28226586Sdimclass MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
29226586Sdim                                               check::PreStmt<ReturnStmt>,
30226586Sdim                                               check::PostStmt<CallExpr>,
31226586Sdim                                               check::EndPath,
32226586Sdim                                               check::DeadSymbols> {
33234353Sdim  mutable OwningPtr<BugType> BT;
34226586Sdim
35226586Sdimpublic:
36226586Sdim  /// AllocationState is a part of the checker specific state together with the
37226586Sdim  /// MemRegion corresponding to the allocated data.
38226586Sdim  struct AllocationState {
39226586Sdim    /// The index of the allocator function.
40226586Sdim    unsigned int AllocatorIdx;
41226586Sdim    SymbolRef Region;
42226586Sdim
43226586Sdim    AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
44226586Sdim      AllocatorIdx(Idx),
45226586Sdim      Region(R) {}
46226586Sdim
47226586Sdim    bool operator==(const AllocationState &X) const {
48226586Sdim      return (AllocatorIdx == X.AllocatorIdx &&
49226586Sdim              Region == X.Region);
50226586Sdim    }
51226586Sdim
52226586Sdim    void Profile(llvm::FoldingSetNodeID &ID) const {
53226586Sdim      ID.AddInteger(AllocatorIdx);
54226586Sdim      ID.AddPointer(Region);
55226586Sdim    }
56226586Sdim  };
57226586Sdim
58226586Sdim  void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
59226586Sdim  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
60226586Sdim  void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
61226586Sdim  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
62234353Sdim  void checkEndPath(CheckerContext &C) const;
63226586Sdim
64226586Sdimprivate:
65226586Sdim  typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
66226586Sdim  typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
67226586Sdim
68226586Sdim  enum APIKind {
69226586Sdim    /// Denotes functions tracked by this checker.
70226586Sdim    ValidAPI = 0,
71226586Sdim    /// The functions commonly/mistakenly used in place of the given API.
72226586Sdim    ErrorAPI = 1,
73226586Sdim    /// The functions which may allocate the data. These are tracked to reduce
74226586Sdim    /// the false alarm rate.
75226586Sdim    PossibleAPI = 2
76226586Sdim  };
77226586Sdim  /// Stores the information about the allocator and deallocator functions -
78226586Sdim  /// these are the functions the checker is tracking.
79226586Sdim  struct ADFunctionInfo {
80226586Sdim    const char* Name;
81226586Sdim    unsigned int Param;
82226586Sdim    unsigned int DeallocatorIdx;
83226586Sdim    APIKind Kind;
84226586Sdim  };
85226586Sdim  static const unsigned InvalidIdx = 100000;
86226586Sdim  static const unsigned FunctionsToTrackSize = 8;
87226586Sdim  static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
88226586Sdim  /// The value, which represents no error return value for allocator functions.
89226586Sdim  static const unsigned NoErr = 0;
90226586Sdim
91226586Sdim  /// Given the function name, returns the index of the allocator/deallocator
92226586Sdim  /// function.
93226586Sdim  static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
94226586Sdim
95226586Sdim  inline void initBugType() const {
96226586Sdim    if (!BT)
97226586Sdim      BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
98226586Sdim  }
99226586Sdim
100226586Sdim  void generateDeallocatorMismatchReport(const AllocationPair &AP,
101226586Sdim                                         const Expr *ArgExpr,
102226586Sdim                                         CheckerContext &C) const;
103226586Sdim
104234353Sdim  /// Find the allocation site for Sym on the path leading to the node N.
105234353Sdim  const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
106234353Sdim                                CheckerContext &C) const;
107234353Sdim
108226586Sdim  BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
109234353Sdim                                                    ExplodedNode *N,
110234353Sdim                                                    CheckerContext &C) const;
111226586Sdim
112226586Sdim  /// Check if RetSym evaluates to an error value in the current state.
113226586Sdim  bool definitelyReturnedError(SymbolRef RetSym,
114234353Sdim                               ProgramStateRef State,
115226586Sdim                               SValBuilder &Builder,
116226586Sdim                               bool noError = false) const;
117226586Sdim
118226586Sdim  /// Check if RetSym evaluates to a NoErr value in the current state.
119226586Sdim  bool definitelyDidnotReturnError(SymbolRef RetSym,
120234353Sdim                                   ProgramStateRef State,
121226586Sdim                                   SValBuilder &Builder) const {
122226586Sdim    return definitelyReturnedError(RetSym, State, Builder, true);
123226586Sdim  }
124234353Sdim
125234353Sdim  /// Mark an AllocationPair interesting for diagnostic reporting.
126234353Sdim  void markInteresting(BugReport *R, const AllocationPair &AP) const {
127234353Sdim    R->markInteresting(AP.first);
128234353Sdim    R->markInteresting(AP.second->Region);
129234353Sdim  }
130226586Sdim
131226586Sdim  /// The bug visitor which allows us to print extra diagnostics along the
132226586Sdim  /// BugReport path. For example, showing the allocation site of the leaked
133226586Sdim  /// region.
134234353Sdim  class SecKeychainBugVisitor
135234353Sdim    : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
136226586Sdim  protected:
137226586Sdim    // The allocated region symbol tracked by the main analysis.
138226586Sdim    SymbolRef Sym;
139226586Sdim
140226586Sdim  public:
141226586Sdim    SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
142226586Sdim    virtual ~SecKeychainBugVisitor() {}
143226586Sdim
144226586Sdim    void Profile(llvm::FoldingSetNodeID &ID) const {
145226586Sdim      static int X = 0;
146226586Sdim      ID.AddPointer(&X);
147226586Sdim      ID.AddPointer(Sym);
148226586Sdim    }
149226586Sdim
150226586Sdim    PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
151226586Sdim                                   const ExplodedNode *PrevN,
152226586Sdim                                   BugReporterContext &BRC,
153226586Sdim                                   BugReport &BR);
154226586Sdim  };
155226586Sdim};
156226586Sdim}
157226586Sdim
158226586Sdim/// ProgramState traits to store the currently allocated (and not yet freed)
159226586Sdim/// symbols. This is a map from the allocated content symbol to the
160226586Sdim/// corresponding AllocationState.
161243830SdimREGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
162243830Sdim                               SymbolRef,
163243830Sdim                               MacOSKeychainAPIChecker::AllocationState)
164226586Sdim
165226586Sdimstatic bool isEnclosingFunctionParam(const Expr *E) {
166226586Sdim  E = E->IgnoreParenCasts();
167226586Sdim  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
168226586Sdim    const ValueDecl *VD = DRE->getDecl();
169226586Sdim    if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
170226586Sdim      return true;
171226586Sdim  }
172226586Sdim  return false;
173226586Sdim}
174226586Sdim
175226586Sdimconst MacOSKeychainAPIChecker::ADFunctionInfo
176226586Sdim  MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
177226586Sdim    {"SecKeychainItemCopyContent", 4, 3, ValidAPI},                       // 0
178226586Sdim    {"SecKeychainFindGenericPassword", 6, 3, ValidAPI},                   // 1
179226586Sdim    {"SecKeychainFindInternetPassword", 13, 3, ValidAPI},                 // 2
180226586Sdim    {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI},              // 3
181226586Sdim    {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI},             // 4
182226586Sdim    {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI},    // 5
183226586Sdim    {"free", 0, InvalidIdx, ErrorAPI},                                    // 6
184226586Sdim    {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI},        // 7
185226586Sdim};
186226586Sdim
187226586Sdimunsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
188226586Sdim                                                          bool IsAllocator) {
189226586Sdim  for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
190226586Sdim    ADFunctionInfo FI = FunctionsToTrack[I];
191226586Sdim    if (FI.Name != Name)
192226586Sdim      continue;
193226586Sdim    // Make sure the function is of the right type (allocator vs deallocator).
194226586Sdim    if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
195226586Sdim      return InvalidIdx;
196226586Sdim    if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
197226586Sdim      return InvalidIdx;
198226586Sdim
199226586Sdim    return I;
200226586Sdim  }
201226586Sdim  // The function is not tracked.
202226586Sdim  return InvalidIdx;
203226586Sdim}
204226586Sdim
205226586Sdimstatic bool isBadDeallocationArgument(const MemRegion *Arg) {
206234353Sdim  if (!Arg)
207234353Sdim    return false;
208226586Sdim  if (isa<AllocaRegion>(Arg) ||
209226586Sdim      isa<BlockDataRegion>(Arg) ||
210226586Sdim      isa<TypedRegion>(Arg)) {
211226586Sdim    return true;
212226586Sdim  }
213226586Sdim  return false;
214226586Sdim}
215234353Sdim
216226586Sdim/// Given the address expression, retrieve the value it's pointing to. Assume
217226586Sdim/// that value is itself an address, and return the corresponding symbol.
218226586Sdimstatic SymbolRef getAsPointeeSymbol(const Expr *Expr,
219226586Sdim                                    CheckerContext &C) {
220234353Sdim  ProgramStateRef State = C.getState();
221234353Sdim  SVal ArgV = State->getSVal(Expr, C.getLocationContext());
222226586Sdim
223226586Sdim  if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
224226586Sdim    StoreManager& SM = C.getStoreManager();
225234353Sdim    SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
226234353Sdim    if (sym)
227234353Sdim      return sym;
228226586Sdim  }
229226586Sdim  return 0;
230226586Sdim}
231226586Sdim
232226586Sdim// When checking for error code, we need to consider the following cases:
233226586Sdim// 1) noErr / [0]
234226586Sdim// 2) someErr / [1, inf]
235226586Sdim// 3) unknown
236226586Sdim// If noError, returns true iff (1).
237226586Sdim// If !noError, returns true iff (2).
238226586Sdimbool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
239234353Sdim                                                      ProgramStateRef State,
240226586Sdim                                                      SValBuilder &Builder,
241226586Sdim                                                      bool noError) const {
242226586Sdim  DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
243226586Sdim    Builder.getSymbolManager().getType(RetSym));
244226586Sdim  DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
245226586Sdim                                                     nonloc::SymbolVal(RetSym));
246234353Sdim  ProgramStateRef ErrState = State->assume(NoErr, noError);
247226586Sdim  if (ErrState == State) {
248226586Sdim    return true;
249226586Sdim  }
250226586Sdim
251226586Sdim  return false;
252226586Sdim}
253226586Sdim
254226586Sdim// Report deallocator mismatch. Remove the region from tracking - reporting a
255226586Sdim// missing free error after this one is redundant.
256226586Sdimvoid MacOSKeychainAPIChecker::
257226586Sdim  generateDeallocatorMismatchReport(const AllocationPair &AP,
258226586Sdim                                    const Expr *ArgExpr,
259226586Sdim                                    CheckerContext &C) const {
260234353Sdim  ProgramStateRef State = C.getState();
261226586Sdim  State = State->remove<AllocatedData>(AP.first);
262234353Sdim  ExplodedNode *N = C.addTransition(State);
263226586Sdim
264226586Sdim  if (!N)
265226586Sdim    return;
266226586Sdim  initBugType();
267234353Sdim  SmallString<80> sbuf;
268226586Sdim  llvm::raw_svector_ostream os(sbuf);
269226586Sdim  unsigned int PDeallocIdx =
270226586Sdim               FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
271226586Sdim
272226586Sdim  os << "Deallocator doesn't match the allocator: '"
273226586Sdim     << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
274226586Sdim  BugReport *Report = new BugReport(*BT, os.str(), N);
275226586Sdim  Report->addVisitor(new SecKeychainBugVisitor(AP.first));
276226586Sdim  Report->addRange(ArgExpr->getSourceRange());
277234353Sdim  markInteresting(Report, AP);
278243830Sdim  C.emitReport(Report);
279226586Sdim}
280226586Sdim
281226586Sdimvoid MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
282226586Sdim                                           CheckerContext &C) const {
283226586Sdim  unsigned idx = InvalidIdx;
284234353Sdim  ProgramStateRef State = C.getState();
285226586Sdim
286239462Sdim  const FunctionDecl *FD = C.getCalleeDecl(CE);
287239462Sdim  if (!FD || FD->getKind() != Decl::Function)
288239462Sdim    return;
289239462Sdim
290239462Sdim  StringRef funName = C.getCalleeName(FD);
291234353Sdim  if (funName.empty())
292226586Sdim    return;
293226586Sdim
294226586Sdim  // If it is a call to an allocator function, it could be a double allocation.
295226586Sdim  idx = getTrackedFunctionIndex(funName, true);
296226586Sdim  if (idx != InvalidIdx) {
297226586Sdim    const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
298226586Sdim    if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
299226586Sdim      if (const AllocationState *AS = State->get<AllocatedData>(V)) {
300226586Sdim        if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
301226586Sdim          // Remove the value from the state. The new symbol will be added for
302226586Sdim          // tracking when the second allocator is processed in checkPostStmt().
303226586Sdim          State = State->remove<AllocatedData>(V);
304234353Sdim          ExplodedNode *N = C.addTransition(State);
305226586Sdim          if (!N)
306226586Sdim            return;
307226586Sdim          initBugType();
308234353Sdim          SmallString<128> sbuf;
309226586Sdim          llvm::raw_svector_ostream os(sbuf);
310226586Sdim          unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
311226586Sdim          os << "Allocated data should be released before another call to "
312226586Sdim              << "the allocator: missing a call to '"
313226586Sdim              << FunctionsToTrack[DIdx].Name
314226586Sdim              << "'.";
315226586Sdim          BugReport *Report = new BugReport(*BT, os.str(), N);
316226586Sdim          Report->addVisitor(new SecKeychainBugVisitor(V));
317226586Sdim          Report->addRange(ArgExpr->getSourceRange());
318234353Sdim          Report->markInteresting(AS->Region);
319243830Sdim          C.emitReport(Report);
320226586Sdim        }
321226586Sdim      }
322226586Sdim    return;
323226586Sdim  }
324226586Sdim
325226586Sdim  // Is it a call to one of deallocator functions?
326226586Sdim  idx = getTrackedFunctionIndex(funName, false);
327226586Sdim  if (idx == InvalidIdx)
328226586Sdim    return;
329226586Sdim
330226586Sdim  // Check the argument to the deallocator.
331226586Sdim  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
332234353Sdim  SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
333226586Sdim
334226586Sdim  // Undef is reported by another checker.
335226586Sdim  if (ArgSVal.isUndef())
336226586Sdim    return;
337226586Sdim
338234353Sdim  SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
339226586Sdim
340226586Sdim  // If the argument is coming from the heap, globals, or unknown, do not
341226586Sdim  // report it.
342234353Sdim  bool RegionArgIsBad = false;
343234353Sdim  if (!ArgSM) {
344234353Sdim    if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
345234353Sdim      return;
346234353Sdim    RegionArgIsBad = true;
347234353Sdim  }
348226586Sdim
349226586Sdim  // Is the argument to the call being tracked?
350226586Sdim  const AllocationState *AS = State->get<AllocatedData>(ArgSM);
351226586Sdim  if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
352226586Sdim    return;
353226586Sdim  }
354226586Sdim  // If trying to free data which has not been allocated yet, report as a bug.
355226586Sdim  // TODO: We might want a more precise diagnostic for double free
356226586Sdim  // (that would involve tracking all the freed symbols in the checker state).
357226586Sdim  if (!AS || RegionArgIsBad) {
358226586Sdim    // It is possible that this is a false positive - the argument might
359226586Sdim    // have entered as an enclosing function parameter.
360226586Sdim    if (isEnclosingFunctionParam(ArgExpr))
361226586Sdim      return;
362226586Sdim
363234353Sdim    ExplodedNode *N = C.addTransition(State);
364226586Sdim    if (!N)
365226586Sdim      return;
366226586Sdim    initBugType();
367226586Sdim    BugReport *Report = new BugReport(*BT,
368226586Sdim        "Trying to free data which has not been allocated.", N);
369226586Sdim    Report->addRange(ArgExpr->getSourceRange());
370234353Sdim    if (AS)
371234353Sdim      Report->markInteresting(AS->Region);
372243830Sdim    C.emitReport(Report);
373226586Sdim    return;
374226586Sdim  }
375226586Sdim
376226586Sdim  // Process functions which might deallocate.
377226586Sdim  if (FunctionsToTrack[idx].Kind == PossibleAPI) {
378226586Sdim
379226586Sdim    if (funName == "CFStringCreateWithBytesNoCopy") {
380226586Sdim      const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
381226586Sdim      // NULL ~ default deallocator, so warn.
382226586Sdim      if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
383226586Sdim          Expr::NPC_ValueDependentIsNotNull)) {
384226586Sdim        const AllocationPair AP = std::make_pair(ArgSM, AS);
385226586Sdim        generateDeallocatorMismatchReport(AP, ArgExpr, C);
386226586Sdim        return;
387226586Sdim      }
388226586Sdim      // One of the default allocators, so warn.
389226586Sdim      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
390226586Sdim        StringRef DeallocatorName = DE->getFoundDecl()->getName();
391226586Sdim        if (DeallocatorName == "kCFAllocatorDefault" ||
392226586Sdim            DeallocatorName == "kCFAllocatorSystemDefault" ||
393226586Sdim            DeallocatorName == "kCFAllocatorMalloc") {
394226586Sdim          const AllocationPair AP = std::make_pair(ArgSM, AS);
395226586Sdim          generateDeallocatorMismatchReport(AP, ArgExpr, C);
396226586Sdim          return;
397226586Sdim        }
398226586Sdim        // If kCFAllocatorNull, which does not deallocate, we still have to
399226586Sdim        // find the deallocator. Otherwise, assume that the user had written a
400226586Sdim        // custom deallocator which does the right thing.
401226586Sdim        if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
402226586Sdim          State = State->remove<AllocatedData>(ArgSM);
403226586Sdim          C.addTransition(State);
404226586Sdim          return;
405226586Sdim        }
406226586Sdim      }
407226586Sdim    }
408226586Sdim    return;
409226586Sdim  }
410226586Sdim
411226586Sdim  // The call is deallocating a value we previously allocated, so remove it
412226586Sdim  // from the next state.
413226586Sdim  State = State->remove<AllocatedData>(ArgSM);
414226586Sdim
415226586Sdim  // Check if the proper deallocator is used.
416226586Sdim  unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
417226586Sdim  if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
418226586Sdim    const AllocationPair AP = std::make_pair(ArgSM, AS);
419226586Sdim    generateDeallocatorMismatchReport(AP, ArgExpr, C);
420226586Sdim    return;
421226586Sdim  }
422226586Sdim
423234353Sdim  // If the buffer can be null and the return status can be an error,
424234353Sdim  // report a bad call to free.
425234353Sdim  if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
426234353Sdim      !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
427234353Sdim    ExplodedNode *N = C.addTransition(State);
428226586Sdim    if (!N)
429226586Sdim      return;
430226586Sdim    initBugType();
431226586Sdim    BugReport *Report = new BugReport(*BT,
432234353Sdim        "Only call free if a valid (non-NULL) buffer was returned.", N);
433226586Sdim    Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
434226586Sdim    Report->addRange(ArgExpr->getSourceRange());
435234353Sdim    Report->markInteresting(AS->Region);
436243830Sdim    C.emitReport(Report);
437226586Sdim    return;
438226586Sdim  }
439226586Sdim
440226586Sdim  C.addTransition(State);
441226586Sdim}
442226586Sdim
443226586Sdimvoid MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
444226586Sdim                                            CheckerContext &C) const {
445234353Sdim  ProgramStateRef State = C.getState();
446239462Sdim  const FunctionDecl *FD = C.getCalleeDecl(CE);
447239462Sdim  if (!FD || FD->getKind() != Decl::Function)
448239462Sdim    return;
449226586Sdim
450239462Sdim  StringRef funName = C.getCalleeName(FD);
451239462Sdim
452226586Sdim  // If a value has been allocated, add it to the set for tracking.
453226586Sdim  unsigned idx = getTrackedFunctionIndex(funName, true);
454226586Sdim  if (idx == InvalidIdx)
455226586Sdim    return;
456226586Sdim
457226586Sdim  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
458226586Sdim  // If the argument entered as an enclosing function parameter, skip it to
459226586Sdim  // avoid false positives.
460234353Sdim  if (isEnclosingFunctionParam(ArgExpr) &&
461234353Sdim      C.getLocationContext()->getParent() == 0)
462226586Sdim    return;
463226586Sdim
464226586Sdim  if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
465226586Sdim    // If the argument points to something that's not a symbolic region, it
466226586Sdim    // can be:
467226586Sdim    //  - unknown (cannot reason about it)
468226586Sdim    //  - undefined (already reported by other checker)
469226586Sdim    //  - constant (null - should not be tracked,
470226586Sdim    //              other constant will generate a compiler warning)
471226586Sdim    //  - goto (should be reported by other checker)
472226586Sdim
473226586Sdim    // The call return value symbol should stay alive for as long as the
474226586Sdim    // allocated value symbol, since our diagnostics depend on the value
475226586Sdim    // returned by the call. Ex: Data should only be freed if noErr was
476226586Sdim    // returned during allocation.)
477234353Sdim    SymbolRef RetStatusSymbol =
478234353Sdim      State->getSVal(CE, C.getLocationContext()).getAsSymbol();
479226586Sdim    C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
480226586Sdim
481226586Sdim    // Track the allocated value in the checker state.
482226586Sdim    State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
483226586Sdim                                                         RetStatusSymbol));
484226586Sdim    assert(State);
485226586Sdim    C.addTransition(State);
486226586Sdim  }
487226586Sdim}
488226586Sdim
489226586Sdimvoid MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
490226586Sdim                                           CheckerContext &C) const {
491226586Sdim  const Expr *retExpr = S->getRetValue();
492226586Sdim  if (!retExpr)
493226586Sdim    return;
494226586Sdim
495234353Sdim  // If inside inlined call, skip it.
496234353Sdim  const LocationContext *LC = C.getLocationContext();
497234353Sdim  if (LC->getParent() != 0)
498234353Sdim    return;
499234353Sdim
500226586Sdim  // Check  if the value is escaping through the return.
501234353Sdim  ProgramStateRef state = C.getState();
502234353Sdim  SymbolRef sym = state->getSVal(retExpr, LC).getAsLocSymbol();
503234353Sdim  if (!sym)
504226586Sdim    return;
505234353Sdim  state = state->remove<AllocatedData>(sym);
506226586Sdim
507226586Sdim  // Proceed from the new state.
508226586Sdim  C.addTransition(state);
509226586Sdim}
510226586Sdim
511234353Sdim// TODO: This logic is the same as in Malloc checker.
512234353Sdimconst Stmt *
513234353SdimMacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
514234353Sdim                                           SymbolRef Sym,
515234353Sdim                                           CheckerContext &C) const {
516234353Sdim  const LocationContext *LeakContext = N->getLocationContext();
517234353Sdim  // Walk the ExplodedGraph backwards and find the first node that referred to
518234353Sdim  // the tracked symbol.
519234353Sdim  const ExplodedNode *AllocNode = N;
520234353Sdim
521234353Sdim  while (N) {
522234353Sdim    if (!N->getState()->get<AllocatedData>(Sym))
523234353Sdim      break;
524234353Sdim    // Allocation node, is the last node in the current context in which the
525234353Sdim    // symbol was tracked.
526234353Sdim    if (N->getLocationContext() == LeakContext)
527234353Sdim      AllocNode = N;
528234353Sdim    N = N->pred_empty() ? NULL : *(N->pred_begin());
529234353Sdim  }
530234353Sdim
531234353Sdim  ProgramPoint P = AllocNode->getLocation();
532239462Sdim  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
533239462Sdim    return Exit->getCalleeContext()->getCallSite();
534239462Sdim  if (clang::PostStmt *PS = dyn_cast<clang::PostStmt>(&P))
535239462Sdim    return PS->getStmt();
536239462Sdim  return 0;
537234353Sdim}
538234353Sdim
539226586SdimBugReport *MacOSKeychainAPIChecker::
540226586Sdim  generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
541234353Sdim                                         ExplodedNode *N,
542234353Sdim                                         CheckerContext &C) const {
543226586Sdim  const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
544226586Sdim  initBugType();
545234353Sdim  SmallString<70> sbuf;
546226586Sdim  llvm::raw_svector_ostream os(sbuf);
547226586Sdim  os << "Allocated data is not released: missing a call to '"
548226586Sdim      << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
549234353Sdim
550234353Sdim  // Most bug reports are cached at the location where they occurred.
551234353Sdim  // With leaks, we want to unique them by the location where they were
552234353Sdim  // allocated, and only report a single path.
553234353Sdim  PathDiagnosticLocation LocUsedForUniqueing;
554234353Sdim  if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
555234353Sdim    LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
556234353Sdim                            C.getSourceManager(), N->getLocationContext());
557234353Sdim
558234353Sdim  BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
559226586Sdim  Report->addVisitor(new SecKeychainBugVisitor(AP.first));
560234353Sdim  markInteresting(Report, AP);
561226586Sdim  return Report;
562226586Sdim}
563226586Sdim
564226586Sdimvoid MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
565226586Sdim                                               CheckerContext &C) const {
566234353Sdim  ProgramStateRef State = C.getState();
567243830Sdim  AllocatedDataTy ASet = State->get<AllocatedData>();
568226586Sdim  if (ASet.isEmpty())
569226586Sdim    return;
570226586Sdim
571226586Sdim  bool Changed = false;
572226586Sdim  AllocationPairVec Errors;
573243830Sdim  for (AllocatedDataTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
574226586Sdim    if (SR.isLive(I->first))
575226586Sdim      continue;
576226586Sdim
577226586Sdim    Changed = true;
578226586Sdim    State = State->remove<AllocatedData>(I->first);
579226586Sdim    // If the allocated symbol is null or if the allocation call might have
580226586Sdim    // returned an error, do not report.
581243830Sdim    ConstraintManager &CMgr = State->getConstraintManager();
582243830Sdim    ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
583243830Sdim    if (AllocFailed.isConstrainedTrue() ||
584226586Sdim        definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
585226586Sdim      continue;
586226586Sdim    Errors.push_back(std::make_pair(I->first, &I->second));
587226586Sdim  }
588234353Sdim  if (!Changed) {
589234353Sdim    // Generate the new, cleaned up state.
590234353Sdim    C.addTransition(State);
591226586Sdim    return;
592234353Sdim  }
593226586Sdim
594234353Sdim  static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
595234353Sdim  ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
596226586Sdim
597226586Sdim  // Generate the error reports.
598226586Sdim  for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
599226586Sdim                                                       I != E; ++I) {
600243830Sdim    C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
601226586Sdim  }
602234353Sdim
603234353Sdim  // Generate the new, cleaned up state.
604234353Sdim  C.addTransition(State, N);
605226586Sdim}
606226586Sdim
607226586Sdim// TODO: Remove this after we ensure that checkDeadSymbols are always called.
608234353Sdimvoid MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
609234353Sdim  ProgramStateRef state = C.getState();
610234353Sdim
611234353Sdim  // If inside inlined call, skip it.
612234353Sdim  if (C.getLocationContext()->getParent() != 0)
613234353Sdim    return;
614234353Sdim
615243830Sdim  AllocatedDataTy AS = state->get<AllocatedData>();
616226586Sdim  if (AS.isEmpty())
617226586Sdim    return;
618226586Sdim
619226586Sdim  // Anything which has been allocated but not freed (nor escaped) will be
620226586Sdim  // found here, so report it.
621226586Sdim  bool Changed = false;
622226586Sdim  AllocationPairVec Errors;
623243830Sdim  for (AllocatedDataTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
624226586Sdim    Changed = true;
625226586Sdim    state = state->remove<AllocatedData>(I->first);
626226586Sdim    // If the allocated symbol is null or if error code was returned at
627226586Sdim    // allocation, do not report.
628243830Sdim    ConstraintManager &CMgr = state->getConstraintManager();
629243830Sdim    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
630243830Sdim    if (AllocFailed.isConstrainedTrue() ||
631226586Sdim        definitelyReturnedError(I->second.Region, state,
632234353Sdim                                C.getSValBuilder())) {
633226586Sdim      continue;
634226586Sdim    }
635226586Sdim    Errors.push_back(std::make_pair(I->first, &I->second));
636226586Sdim  }
637226586Sdim
638226586Sdim  // If no change, do not generate a new state.
639234353Sdim  if (!Changed) {
640234353Sdim    C.addTransition(state);
641226586Sdim    return;
642234353Sdim  }
643226586Sdim
644234353Sdim  static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
645234353Sdim  ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
646226586Sdim
647226586Sdim  // Generate the error reports.
648226586Sdim  for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
649226586Sdim                                                       I != E; ++I) {
650243830Sdim    C.emitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
651226586Sdim  }
652234353Sdim
653234353Sdim  C.addTransition(state, N);
654226586Sdim}
655226586Sdim
656226586Sdim
657226586SdimPathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
658226586Sdim                                                      const ExplodedNode *N,
659226586Sdim                                                      const ExplodedNode *PrevN,
660226586Sdim                                                      BugReporterContext &BRC,
661226586Sdim                                                      BugReport &BR) {
662226586Sdim  const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
663226586Sdim  if (!AS)
664226586Sdim    return 0;
665226586Sdim  const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
666226586Sdim  if (ASPrev)
667226586Sdim    return 0;
668226586Sdim
669226586Sdim  // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
670226586Sdim  // allocation site.
671226586Sdim  const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
672226586Sdim                                                            .getStmt());
673226586Sdim  const FunctionDecl *funDecl = CE->getDirectCallee();
674226586Sdim  assert(funDecl && "We do not support indirect function calls as of now.");
675226586Sdim  StringRef funName = funDecl->getName();
676226586Sdim
677226586Sdim  // Get the expression of the corresponding argument.
678226586Sdim  unsigned Idx = getTrackedFunctionIndex(funName, true);
679226586Sdim  assert(Idx != InvalidIdx && "This should be a call to an allocator.");
680226586Sdim  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
681226586Sdim  PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
682226586Sdim                             N->getLocationContext());
683226586Sdim  return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
684226586Sdim}
685226586Sdim
686226586Sdimvoid ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
687226586Sdim  mgr.registerChecker<MacOSKeychainAPIChecker>();
688226586Sdim}
689