MacOSKeychainAPIChecker.cpp revision 5ef6e94b294cc47750d8ab220858a36726caba59
19b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
29b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//
39b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//                     The LLVM Compiler Infrastructure
49b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//
59b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com// This file is distributed under the University of Illinois Open Source
69b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com// License. See LICENSE.TXT for details.
79b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//
89b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//===----------------------------------------------------------------------===//
99b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com// This checker flags misuses of KeyChainAPI. In particular, the password data
109b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com// allocated/returned by SecKeychainItemCopyContent,
119b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
129b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com// to be freed using a call to SecKeychainItemFreeContent.
139b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com//===----------------------------------------------------------------------===//
149b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
159b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "ClangSACheckers.h"
169b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "clang/StaticAnalyzer/Core/Checker.h"
179b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "clang/StaticAnalyzer/Core/CheckerManager.h"
189b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
199b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
209b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
219b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
229b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com#include "llvm/ADT/SmallString.h"
239b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
249b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comusing namespace clang;
259b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comusing namespace ento;
269b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
279b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comnamespace {
289b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comclass MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
299b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                               check::PreStmt<ReturnStmt>,
309b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                               check::PostStmt<CallExpr>,
319b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                               check::EndPath,
329b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                               check::DeadSymbols> {
339b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  mutable OwningPtr<BugType> BT;
349b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
359b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.compublic:
369b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// AllocationState is a part of the checker specific state together with the
379b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// MemRegion corresponding to the allocated data.
389b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  struct AllocationState {
399b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    /// The index of the allocator function.
409b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    unsigned int AllocatorIdx;
419b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    SymbolRef Region;
429b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
439b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
449b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      AllocatorIdx(Idx),
459b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      Region(R) {}
469b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
479b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    bool operator==(const AllocationState &X) const {
489b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      return (AllocatorIdx == X.AllocatorIdx &&
499b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com              Region == X.Region);
509b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    }
519b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
529b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    void Profile(llvm::FoldingSetNodeID &ID) const {
539b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      ID.AddInteger(AllocatorIdx);
549b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      ID.AddPointer(Region);
559b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    }
569b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  };
579b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
589b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
599b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
609b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
619b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
629b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void checkEndPath(CheckerContext &C) const;
639b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
649b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comprivate:
659b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
669b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  typedef llvm::SmallVector<AllocationPair, 2> AllocationPairVec;
679b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
689b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  enum APIKind {
699b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    /// Denotes functions tracked by this checker.
709b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    ValidAPI = 0,
719b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    /// The functions commonly/mistakenly used in place of the given API.
729b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    ErrorAPI = 1,
739b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    /// The functions which may allocate the data. These are tracked to reduce
749b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    /// the false alarm rate.
759b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    PossibleAPI = 2
769b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  };
779b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// Stores the information about the allocator and deallocator functions -
789b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// these are the functions the checker is tracking.
799b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  struct ADFunctionInfo {
809b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    const char* Name;
819b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    unsigned int Param;
829b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    unsigned int DeallocatorIdx;
839b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    APIKind Kind;
849b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  };
859b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  static const unsigned InvalidIdx = 100000;
869b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  static const unsigned FunctionsToTrackSize = 8;
879b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
889b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// The value, which represents no error return value for allocator functions.
899b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  static const unsigned NoErr = 0;
909b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
919b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// Given the function name, returns the index of the allocator/deallocator
929b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// function.
939b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
949b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
959b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  inline void initBugType() const {
969b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    if (!BT)
979b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
989b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  }
999b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1009b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void generateDeallocatorMismatchReport(const AllocationPair &AP,
1019b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                         const Expr *ArgExpr,
1029b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                         CheckerContext &C) const;
1039b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1049b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// Find the allocation site for Sym on the path leading to the node N.
1059b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  const Stmt *getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1069b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                CheckerContext &C) const;
1079b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1089b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  BugReport *generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
1099b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                                    ExplodedNode *N,
1109b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                                    CheckerContext &C) const;
1119b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1129b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// Check if RetSym evaluates to an error value in the current state.
1139b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  bool definitelyReturnedError(SymbolRef RetSym,
1149b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                               ProgramStateRef State,
1159b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                               SValBuilder &Builder,
1169b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                               bool noError = false) const;
1179b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1189b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// Check if RetSym evaluates to a NoErr value in the current state.
1199b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  bool definitelyDidnotReturnError(SymbolRef RetSym,
1209b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                   ProgramStateRef State,
1219b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                   SValBuilder &Builder) const {
1229b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    return definitelyReturnedError(RetSym, State, Builder, true);
1239b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  }
1249b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1259b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// Mark an AllocationPair interesting for diagnostic reporting.
1269b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  void markInteresting(BugReport *R, const AllocationPair &AP) const {
1279b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    R->markInteresting(AP.first);
1289b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    R->markInteresting(AP.second->Region);
1299b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  }
1309b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1319b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// The bug visitor which allows us to print extra diagnostics along the
1329b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// BugReport path. For example, showing the allocation site of the leaked
1339b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  /// region.
1349b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  class SecKeychainBugVisitor
1359b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    : public BugReporterVisitorImpl<SecKeychainBugVisitor> {
1369b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  protected:
1379b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    // The allocated region symbol tracked by the main analysis.
1389b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    SymbolRef Sym;
1399b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1409b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  public:
1419b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
1429b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    virtual ~SecKeychainBugVisitor() {}
1439b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1449b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    void Profile(llvm::FoldingSetNodeID &ID) const {
1459b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      static int X = 0;
1469b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      ID.AddPointer(&X);
1479b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      ID.AddPointer(Sym);
1489b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    }
1499b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1509b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1519b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                   const ExplodedNode *PrevN,
1529b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                   BugReporterContext &BRC,
1539b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                   BugReport &BR);
1549b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  };
1559b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com};
1569b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com}
1579b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1589b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com/// ProgramState traits to store the currently allocated (and not yet freed)
1599b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com/// symbols. This is a map from the allocated content symbol to the
1609b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com/// corresponding AllocationState.
1619b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comtypedef llvm::ImmutableMap<SymbolRef,
1629b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                       MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;
1639b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1649b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comnamespace { struct AllocatedData {}; }
1659b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comnamespace clang { namespace ento {
1669b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comtemplate<> struct ProgramStateTrait<AllocatedData>
1679b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    :  public ProgramStatePartialTrait<AllocatedSetTy > {
1689b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  static void *GDMIndex() { static int index = 0; return &index; }
1699b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com};
1709b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com}}
1719b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1729b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comstatic bool isEnclosingFunctionParam(const Expr *E) {
1739b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  E = E->IgnoreParenCasts();
1749b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1759b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    const ValueDecl *VD = DRE->getDecl();
1769b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
1779b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      return true;
1789b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  }
1799b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  return false;
1809b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com}
1819b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1829b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comconst MacOSKeychainAPIChecker::ADFunctionInfo
1839b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
1849b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"SecKeychainItemCopyContent", 4, 3, ValidAPI},                       // 0
1859b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"SecKeychainFindGenericPassword", 6, 3, ValidAPI},                   // 1
1869b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"SecKeychainFindInternetPassword", 13, 3, ValidAPI},                 // 2
1879b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI},              // 3
1889b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI},             // 4
1899b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI},    // 5
1909b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"free", 0, InvalidIdx, ErrorAPI},                                    // 6
1919b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI},        // 7
1929b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com};
1939b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
1949b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comunsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
1959b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com                                                          bool IsAllocator) {
1969b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
1979b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    ADFunctionInfo FI = FunctionsToTrack[I];
1989b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    if (FI.Name != Name)
1999b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      continue;
2009b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    // Make sure the function is of the right type (allocator vs deallocator).
2019b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
2029b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      return InvalidIdx;
2039b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
2049b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      return InvalidIdx;
2059b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
2069b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    return I;
2079b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  }
2089b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  // The function is not tracked.
2099b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  return InvalidIdx;
2109b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com}
2119b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com
2129b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.comstatic bool isBadDeallocationArgument(const MemRegion *Arg) {
2139b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  if (!Arg)
2149b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com    return false;
2159b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com  if (isa<AllocaRegion>(Arg) ||
2169b80e34391ebd835244aea31bd2fb427e209fa0fphilip.liard@gmail.com      isa<BlockDataRegion>(Arg) ||
217      isa<TypedRegion>(Arg)) {
218    return true;
219  }
220  return false;
221}
222
223/// Given the address expression, retrieve the value it's pointing to. Assume
224/// that value is itself an address, and return the corresponding symbol.
225static SymbolRef getAsPointeeSymbol(const Expr *Expr,
226                                    CheckerContext &C) {
227  ProgramStateRef State = C.getState();
228  SVal ArgV = State->getSVal(Expr, C.getLocationContext());
229
230  if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
231    StoreManager& SM = C.getStoreManager();
232    SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
233    if (sym)
234      return sym;
235  }
236  return 0;
237}
238
239// When checking for error code, we need to consider the following cases:
240// 1) noErr / [0]
241// 2) someErr / [1, inf]
242// 3) unknown
243// If noError, returns true iff (1).
244// If !noError, returns true iff (2).
245bool MacOSKeychainAPIChecker::definitelyReturnedError(SymbolRef RetSym,
246                                                      ProgramStateRef State,
247                                                      SValBuilder &Builder,
248                                                      bool noError) const {
249  DefinedOrUnknownSVal NoErrVal = Builder.makeIntVal(NoErr,
250    Builder.getSymbolManager().getType(RetSym));
251  DefinedOrUnknownSVal NoErr = Builder.evalEQ(State, NoErrVal,
252                                                     nonloc::SymbolVal(RetSym));
253  ProgramStateRef ErrState = State->assume(NoErr, noError);
254  if (ErrState == State) {
255    return true;
256  }
257
258  return false;
259}
260
261// Report deallocator mismatch. Remove the region from tracking - reporting a
262// missing free error after this one is redundant.
263void MacOSKeychainAPIChecker::
264  generateDeallocatorMismatchReport(const AllocationPair &AP,
265                                    const Expr *ArgExpr,
266                                    CheckerContext &C) const {
267  ProgramStateRef State = C.getState();
268  State = State->remove<AllocatedData>(AP.first);
269  ExplodedNode *N = C.addTransition(State);
270
271  if (!N)
272    return;
273  initBugType();
274  SmallString<80> sbuf;
275  llvm::raw_svector_ostream os(sbuf);
276  unsigned int PDeallocIdx =
277               FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
278
279  os << "Deallocator doesn't match the allocator: '"
280     << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
281  BugReport *Report = new BugReport(*BT, os.str(), N);
282  Report->addVisitor(new SecKeychainBugVisitor(AP.first));
283  Report->addRange(ArgExpr->getSourceRange());
284  markInteresting(Report, AP);
285  C.EmitReport(Report);
286}
287
288void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
289                                           CheckerContext &C) const {
290  unsigned idx = InvalidIdx;
291  ProgramStateRef State = C.getState();
292
293  const FunctionDecl *FD = C.getCalleeDecl(CE);
294  if (!FD || FD->getKind() != Decl::Function)
295    return;
296
297  StringRef funName = C.getCalleeName(FD);
298  if (funName.empty())
299    return;
300
301  // If it is a call to an allocator function, it could be a double allocation.
302  idx = getTrackedFunctionIndex(funName, true);
303  if (idx != InvalidIdx) {
304    const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
305    if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
306      if (const AllocationState *AS = State->get<AllocatedData>(V)) {
307        if (!definitelyReturnedError(AS->Region, State, C.getSValBuilder())) {
308          // Remove the value from the state. The new symbol will be added for
309          // tracking when the second allocator is processed in checkPostStmt().
310          State = State->remove<AllocatedData>(V);
311          ExplodedNode *N = C.addTransition(State);
312          if (!N)
313            return;
314          initBugType();
315          SmallString<128> sbuf;
316          llvm::raw_svector_ostream os(sbuf);
317          unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
318          os << "Allocated data should be released before another call to "
319              << "the allocator: missing a call to '"
320              << FunctionsToTrack[DIdx].Name
321              << "'.";
322          BugReport *Report = new BugReport(*BT, os.str(), N);
323          Report->addVisitor(new SecKeychainBugVisitor(V));
324          Report->addRange(ArgExpr->getSourceRange());
325          Report->markInteresting(AS->Region);
326          C.EmitReport(Report);
327        }
328      }
329    return;
330  }
331
332  // Is it a call to one of deallocator functions?
333  idx = getTrackedFunctionIndex(funName, false);
334  if (idx == InvalidIdx)
335    return;
336
337  // Check the argument to the deallocator.
338  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
339  SVal ArgSVal = State->getSVal(ArgExpr, C.getLocationContext());
340
341  // Undef is reported by another checker.
342  if (ArgSVal.isUndef())
343    return;
344
345  SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
346
347  // If the argument is coming from the heap, globals, or unknown, do not
348  // report it.
349  bool RegionArgIsBad = false;
350  if (!ArgSM) {
351    if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
352      return;
353    RegionArgIsBad = true;
354  }
355
356  // Is the argument to the call being tracked?
357  const AllocationState *AS = State->get<AllocatedData>(ArgSM);
358  if (!AS && FunctionsToTrack[idx].Kind != ValidAPI) {
359    return;
360  }
361  // If trying to free data which has not been allocated yet, report as a bug.
362  // TODO: We might want a more precise diagnostic for double free
363  // (that would involve tracking all the freed symbols in the checker state).
364  if (!AS || RegionArgIsBad) {
365    // It is possible that this is a false positive - the argument might
366    // have entered as an enclosing function parameter.
367    if (isEnclosingFunctionParam(ArgExpr))
368      return;
369
370    ExplodedNode *N = C.addTransition(State);
371    if (!N)
372      return;
373    initBugType();
374    BugReport *Report = new BugReport(*BT,
375        "Trying to free data which has not been allocated.", N);
376    Report->addRange(ArgExpr->getSourceRange());
377    if (AS)
378      Report->markInteresting(AS->Region);
379    C.EmitReport(Report);
380    return;
381  }
382
383  // Process functions which might deallocate.
384  if (FunctionsToTrack[idx].Kind == PossibleAPI) {
385
386    if (funName == "CFStringCreateWithBytesNoCopy") {
387      const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
388      // NULL ~ default deallocator, so warn.
389      if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
390          Expr::NPC_ValueDependentIsNotNull)) {
391        const AllocationPair AP = std::make_pair(ArgSM, AS);
392        generateDeallocatorMismatchReport(AP, ArgExpr, C);
393        return;
394      }
395      // One of the default allocators, so warn.
396      if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
397        StringRef DeallocatorName = DE->getFoundDecl()->getName();
398        if (DeallocatorName == "kCFAllocatorDefault" ||
399            DeallocatorName == "kCFAllocatorSystemDefault" ||
400            DeallocatorName == "kCFAllocatorMalloc") {
401          const AllocationPair AP = std::make_pair(ArgSM, AS);
402          generateDeallocatorMismatchReport(AP, ArgExpr, C);
403          return;
404        }
405        // If kCFAllocatorNull, which does not deallocate, we still have to
406        // find the deallocator. Otherwise, assume that the user had written a
407        // custom deallocator which does the right thing.
408        if (DE->getFoundDecl()->getName() != "kCFAllocatorNull") {
409          State = State->remove<AllocatedData>(ArgSM);
410          C.addTransition(State);
411          return;
412        }
413      }
414    }
415    return;
416  }
417
418  // The call is deallocating a value we previously allocated, so remove it
419  // from the next state.
420  State = State->remove<AllocatedData>(ArgSM);
421
422  // Check if the proper deallocator is used.
423  unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
424  if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
425    const AllocationPair AP = std::make_pair(ArgSM, AS);
426    generateDeallocatorMismatchReport(AP, ArgExpr, C);
427    return;
428  }
429
430  // If the buffer can be null and the return status can be an error,
431  // report a bad call to free.
432  if (State->assume(cast<DefinedSVal>(ArgSVal), false) &&
433      !definitelyDidnotReturnError(AS->Region, State, C.getSValBuilder())) {
434    ExplodedNode *N = C.addTransition(State);
435    if (!N)
436      return;
437    initBugType();
438    BugReport *Report = new BugReport(*BT,
439        "Only call free if a valid (non-NULL) buffer was returned.", N);
440    Report->addVisitor(new SecKeychainBugVisitor(ArgSM));
441    Report->addRange(ArgExpr->getSourceRange());
442    Report->markInteresting(AS->Region);
443    C.EmitReport(Report);
444    return;
445  }
446
447  C.addTransition(State);
448}
449
450void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
451                                            CheckerContext &C) const {
452  ProgramStateRef State = C.getState();
453  const FunctionDecl *FD = C.getCalleeDecl(CE);
454  if (!FD || FD->getKind() != Decl::Function)
455    return;
456
457  StringRef funName = C.getCalleeName(FD);
458
459  // If a value has been allocated, add it to the set for tracking.
460  unsigned idx = getTrackedFunctionIndex(funName, true);
461  if (idx == InvalidIdx)
462    return;
463
464  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
465  // If the argument entered as an enclosing function parameter, skip it to
466  // avoid false positives.
467  if (isEnclosingFunctionParam(ArgExpr) &&
468      C.getLocationContext()->getParent() == 0)
469    return;
470
471  if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
472    // If the argument points to something that's not a symbolic region, it
473    // can be:
474    //  - unknown (cannot reason about it)
475    //  - undefined (already reported by other checker)
476    //  - constant (null - should not be tracked,
477    //              other constant will generate a compiler warning)
478    //  - goto (should be reported by other checker)
479
480    // The call return value symbol should stay alive for as long as the
481    // allocated value symbol, since our diagnostics depend on the value
482    // returned by the call. Ex: Data should only be freed if noErr was
483    // returned during allocation.)
484    SymbolRef RetStatusSymbol =
485      State->getSVal(CE, C.getLocationContext()).getAsSymbol();
486    C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
487
488    // Track the allocated value in the checker state.
489    State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
490                                                         RetStatusSymbol));
491    assert(State);
492    C.addTransition(State);
493  }
494}
495
496void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
497                                           CheckerContext &C) const {
498  const Expr *retExpr = S->getRetValue();
499  if (!retExpr)
500    return;
501
502  // If inside inlined call, skip it.
503  const LocationContext *LC = C.getLocationContext();
504  if (LC->getParent() != 0)
505    return;
506
507  // Check  if the value is escaping through the return.
508  ProgramStateRef state = C.getState();
509  SymbolRef sym = state->getSVal(retExpr, LC).getAsLocSymbol();
510  if (!sym)
511    return;
512  state = state->remove<AllocatedData>(sym);
513
514  // Proceed from the new state.
515  C.addTransition(state);
516}
517
518// TODO: This logic is the same as in Malloc checker.
519const Stmt *
520MacOSKeychainAPIChecker::getAllocationSite(const ExplodedNode *N,
521                                           SymbolRef Sym,
522                                           CheckerContext &C) const {
523  const LocationContext *LeakContext = N->getLocationContext();
524  // Walk the ExplodedGraph backwards and find the first node that referred to
525  // the tracked symbol.
526  const ExplodedNode *AllocNode = N;
527
528  while (N) {
529    if (!N->getState()->get<AllocatedData>(Sym))
530      break;
531    // Allocation node, is the last node in the current context in which the
532    // symbol was tracked.
533    if (N->getLocationContext() == LeakContext)
534      AllocNode = N;
535    N = N->pred_empty() ? NULL : *(N->pred_begin());
536  }
537
538  ProgramPoint P = AllocNode->getLocation();
539  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
540    return Exit->getCalleeContext()->getCallSite();
541  if (clang::PostStmt *PS = dyn_cast<clang::PostStmt>(&P))
542    return PS->getStmt();
543  return 0;
544}
545
546BugReport *MacOSKeychainAPIChecker::
547  generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
548                                         ExplodedNode *N,
549                                         CheckerContext &C) const {
550  const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
551  initBugType();
552  SmallString<70> sbuf;
553  llvm::raw_svector_ostream os(sbuf);
554  os << "Allocated data is not released: missing a call to '"
555      << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
556
557  // Most bug reports are cached at the location where they occurred.
558  // With leaks, we want to unique them by the location where they were
559  // allocated, and only report a single path.
560  PathDiagnosticLocation LocUsedForUniqueing;
561  if (const Stmt *AllocStmt = getAllocationSite(N, AP.first, C))
562    LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
563                            C.getSourceManager(), N->getLocationContext());
564
565  BugReport *Report = new BugReport(*BT, os.str(), N, LocUsedForUniqueing);
566  Report->addVisitor(new SecKeychainBugVisitor(AP.first));
567  markInteresting(Report, AP);
568  return Report;
569}
570
571void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
572                                               CheckerContext &C) const {
573  ProgramStateRef State = C.getState();
574  AllocatedSetTy ASet = State->get<AllocatedData>();
575  if (ASet.isEmpty())
576    return;
577
578  bool Changed = false;
579  AllocationPairVec Errors;
580  for (AllocatedSetTy::iterator I = ASet.begin(), E = ASet.end(); I != E; ++I) {
581    if (SR.isLive(I->first))
582      continue;
583
584    Changed = true;
585    State = State->remove<AllocatedData>(I->first);
586    // If the allocated symbol is null or if the allocation call might have
587    // returned an error, do not report.
588    if (State->getSymVal(I->first) ||
589        definitelyReturnedError(I->second.Region, State, C.getSValBuilder()))
590      continue;
591    Errors.push_back(std::make_pair(I->first, &I->second));
592  }
593  if (!Changed) {
594    // Generate the new, cleaned up state.
595    C.addTransition(State);
596    return;
597  }
598
599  static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : DeadSymbolsLeak");
600  ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
601
602  // Generate the error reports.
603  for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
604                                                       I != E; ++I) {
605    C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
606  }
607
608  // Generate the new, cleaned up state.
609  C.addTransition(State, N);
610}
611
612// TODO: Remove this after we ensure that checkDeadSymbols are always called.
613void MacOSKeychainAPIChecker::checkEndPath(CheckerContext &C) const {
614  ProgramStateRef state = C.getState();
615
616  // If inside inlined call, skip it.
617  if (C.getLocationContext()->getParent() != 0)
618    return;
619
620  AllocatedSetTy AS = state->get<AllocatedData>();
621  if (AS.isEmpty())
622    return;
623
624  // Anything which has been allocated but not freed (nor escaped) will be
625  // found here, so report it.
626  bool Changed = false;
627  AllocationPairVec Errors;
628  for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
629    Changed = true;
630    state = state->remove<AllocatedData>(I->first);
631    // If the allocated symbol is null or if error code was returned at
632    // allocation, do not report.
633    if (state->getSymVal(I.getKey()) ||
634        definitelyReturnedError(I->second.Region, state,
635                                C.getSValBuilder())) {
636      continue;
637    }
638    Errors.push_back(std::make_pair(I->first, &I->second));
639  }
640
641  // If no change, do not generate a new state.
642  if (!Changed) {
643    C.addTransition(state);
644    return;
645  }
646
647  static SimpleProgramPointTag Tag("MacOSKeychainAPIChecker : EndPathLeak");
648  ExplodedNode *N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
649
650  // Generate the error reports.
651  for (AllocationPairVec::iterator I = Errors.begin(), E = Errors.end();
652                                                       I != E; ++I) {
653    C.EmitReport(generateAllocatedDataNotReleasedReport(*I, N, C));
654  }
655
656  C.addTransition(state, N);
657}
658
659
660PathDiagnosticPiece *MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
661                                                      const ExplodedNode *N,
662                                                      const ExplodedNode *PrevN,
663                                                      BugReporterContext &BRC,
664                                                      BugReport &BR) {
665  const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
666  if (!AS)
667    return 0;
668  const AllocationState *ASPrev = PrevN->getState()->get<AllocatedData>(Sym);
669  if (ASPrev)
670    return 0;
671
672  // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
673  // allocation site.
674  const CallExpr *CE = cast<CallExpr>(cast<StmtPoint>(N->getLocation())
675                                                            .getStmt());
676  const FunctionDecl *funDecl = CE->getDirectCallee();
677  assert(funDecl && "We do not support indirect function calls as of now.");
678  StringRef funName = funDecl->getName();
679
680  // Get the expression of the corresponding argument.
681  unsigned Idx = getTrackedFunctionIndex(funName, true);
682  assert(Idx != InvalidIdx && "This should be a call to an allocator.");
683  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
684  PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
685                             N->getLocationContext());
686  return new PathDiagnosticEventPiece(Pos, "Data is allocated here.");
687}
688
689void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
690  mgr.registerChecker<MacOSKeychainAPIChecker>();
691}
692