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