1e5dd7070Spatrick //==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick // This checker flags misuses of KeyChainAPI. In particular, the password data
9e5dd7070Spatrick // allocated/returned by SecKeychainItemCopyContent,
10e5dd7070Spatrick // SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
11e5dd7070Spatrick // to be freed using a call to SecKeychainItemFreeContent.
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick
14e5dd7070Spatrick #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
15e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
16e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/Checker.h"
17e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/CheckerManager.h"
18e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
19e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
21e5dd7070Spatrick #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
22e5dd7070Spatrick #include "llvm/ADT/SmallString.h"
23e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
24*12c85518Srobert #include <optional>
25e5dd7070Spatrick
26e5dd7070Spatrick using namespace clang;
27e5dd7070Spatrick using namespace ento;
28e5dd7070Spatrick
29e5dd7070Spatrick namespace {
30e5dd7070Spatrick class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
31e5dd7070Spatrick check::PostStmt<CallExpr>,
32e5dd7070Spatrick check::DeadSymbols,
33e5dd7070Spatrick check::PointerEscape,
34e5dd7070Spatrick eval::Assume> {
35e5dd7070Spatrick mutable std::unique_ptr<BugType> BT;
36e5dd7070Spatrick
37e5dd7070Spatrick public:
38e5dd7070Spatrick /// AllocationState is a part of the checker specific state together with the
39e5dd7070Spatrick /// MemRegion corresponding to the allocated data.
40e5dd7070Spatrick struct AllocationState {
41e5dd7070Spatrick /// The index of the allocator function.
42e5dd7070Spatrick unsigned int AllocatorIdx;
43e5dd7070Spatrick SymbolRef Region;
44e5dd7070Spatrick
AllocationState__anone23b33b30111::MacOSKeychainAPIChecker::AllocationState45e5dd7070Spatrick AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
46e5dd7070Spatrick AllocatorIdx(Idx),
47e5dd7070Spatrick Region(R) {}
48e5dd7070Spatrick
operator ==__anone23b33b30111::MacOSKeychainAPIChecker::AllocationState49e5dd7070Spatrick bool operator==(const AllocationState &X) const {
50e5dd7070Spatrick return (AllocatorIdx == X.AllocatorIdx &&
51e5dd7070Spatrick Region == X.Region);
52e5dd7070Spatrick }
53e5dd7070Spatrick
Profile__anone23b33b30111::MacOSKeychainAPIChecker::AllocationState54e5dd7070Spatrick void Profile(llvm::FoldingSetNodeID &ID) const {
55e5dd7070Spatrick ID.AddInteger(AllocatorIdx);
56e5dd7070Spatrick ID.AddPointer(Region);
57e5dd7070Spatrick }
58e5dd7070Spatrick };
59e5dd7070Spatrick
60e5dd7070Spatrick void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
61e5dd7070Spatrick void checkPostStmt(const CallExpr *S, CheckerContext &C) const;
62e5dd7070Spatrick void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const;
63e5dd7070Spatrick ProgramStateRef checkPointerEscape(ProgramStateRef State,
64e5dd7070Spatrick const InvalidatedSymbols &Escaped,
65e5dd7070Spatrick const CallEvent *Call,
66e5dd7070Spatrick PointerEscapeKind Kind) const;
67e5dd7070Spatrick ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
68e5dd7070Spatrick bool Assumption) const;
69e5dd7070Spatrick void printState(raw_ostream &Out, ProgramStateRef State,
70ec727ea7Spatrick const char *NL, const char *Sep) const override;
71e5dd7070Spatrick
72e5dd7070Spatrick private:
73e5dd7070Spatrick typedef std::pair<SymbolRef, const AllocationState*> AllocationPair;
74e5dd7070Spatrick typedef SmallVector<AllocationPair, 2> AllocationPairVec;
75e5dd7070Spatrick
76e5dd7070Spatrick enum APIKind {
77e5dd7070Spatrick /// Denotes functions tracked by this checker.
78e5dd7070Spatrick ValidAPI = 0,
79e5dd7070Spatrick /// The functions commonly/mistakenly used in place of the given API.
80e5dd7070Spatrick ErrorAPI = 1,
81e5dd7070Spatrick /// The functions which may allocate the data. These are tracked to reduce
82e5dd7070Spatrick /// the false alarm rate.
83e5dd7070Spatrick PossibleAPI = 2
84e5dd7070Spatrick };
85e5dd7070Spatrick /// Stores the information about the allocator and deallocator functions -
86e5dd7070Spatrick /// these are the functions the checker is tracking.
87e5dd7070Spatrick struct ADFunctionInfo {
88e5dd7070Spatrick const char* Name;
89e5dd7070Spatrick unsigned int Param;
90e5dd7070Spatrick unsigned int DeallocatorIdx;
91e5dd7070Spatrick APIKind Kind;
92e5dd7070Spatrick };
93e5dd7070Spatrick static const unsigned InvalidIdx = 100000;
94e5dd7070Spatrick static const unsigned FunctionsToTrackSize = 8;
95e5dd7070Spatrick static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
96e5dd7070Spatrick /// The value, which represents no error return value for allocator functions.
97e5dd7070Spatrick static const unsigned NoErr = 0;
98e5dd7070Spatrick
99e5dd7070Spatrick /// Given the function name, returns the index of the allocator/deallocator
100e5dd7070Spatrick /// function.
101e5dd7070Spatrick static unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator);
102e5dd7070Spatrick
initBugType() const103e5dd7070Spatrick inline void initBugType() const {
104e5dd7070Spatrick if (!BT)
105e5dd7070Spatrick BT.reset(new BugType(this, "Improper use of SecKeychain API",
106e5dd7070Spatrick "API Misuse (Apple)"));
107e5dd7070Spatrick }
108e5dd7070Spatrick
109e5dd7070Spatrick void generateDeallocatorMismatchReport(const AllocationPair &AP,
110e5dd7070Spatrick const Expr *ArgExpr,
111e5dd7070Spatrick CheckerContext &C) const;
112e5dd7070Spatrick
113e5dd7070Spatrick /// Find the allocation site for Sym on the path leading to the node N.
114e5dd7070Spatrick const ExplodedNode *getAllocationNode(const ExplodedNode *N, SymbolRef Sym,
115e5dd7070Spatrick CheckerContext &C) const;
116e5dd7070Spatrick
117e5dd7070Spatrick std::unique_ptr<PathSensitiveBugReport>
118e5dd7070Spatrick generateAllocatedDataNotReleasedReport(const AllocationPair &AP,
119e5dd7070Spatrick ExplodedNode *N,
120e5dd7070Spatrick CheckerContext &C) const;
121e5dd7070Spatrick
122e5dd7070Spatrick /// Mark an AllocationPair interesting for diagnostic reporting.
markInteresting(PathSensitiveBugReport * R,const AllocationPair & AP) const123e5dd7070Spatrick void markInteresting(PathSensitiveBugReport *R,
124e5dd7070Spatrick const AllocationPair &AP) const {
125e5dd7070Spatrick R->markInteresting(AP.first);
126e5dd7070Spatrick R->markInteresting(AP.second->Region);
127e5dd7070Spatrick }
128e5dd7070Spatrick
129e5dd7070Spatrick /// The bug visitor which allows us to print extra diagnostics along the
130e5dd7070Spatrick /// BugReport path. For example, showing the allocation site of the leaked
131e5dd7070Spatrick /// region.
132e5dd7070Spatrick class SecKeychainBugVisitor : public BugReporterVisitor {
133e5dd7070Spatrick protected:
134e5dd7070Spatrick // The allocated region symbol tracked by the main analysis.
135e5dd7070Spatrick SymbolRef Sym;
136e5dd7070Spatrick
137e5dd7070Spatrick public:
SecKeychainBugVisitor(SymbolRef S)138e5dd7070Spatrick SecKeychainBugVisitor(SymbolRef S) : Sym(S) {}
139e5dd7070Spatrick
Profile(llvm::FoldingSetNodeID & ID) const140e5dd7070Spatrick void Profile(llvm::FoldingSetNodeID &ID) const override {
141e5dd7070Spatrick static int X = 0;
142e5dd7070Spatrick ID.AddPointer(&X);
143e5dd7070Spatrick ID.AddPointer(Sym);
144e5dd7070Spatrick }
145e5dd7070Spatrick
146e5dd7070Spatrick PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
147e5dd7070Spatrick BugReporterContext &BRC,
148e5dd7070Spatrick PathSensitiveBugReport &BR) override;
149e5dd7070Spatrick };
150e5dd7070Spatrick };
151e5dd7070Spatrick }
152e5dd7070Spatrick
153e5dd7070Spatrick /// ProgramState traits to store the currently allocated (and not yet freed)
154e5dd7070Spatrick /// symbols. This is a map from the allocated content symbol to the
155e5dd7070Spatrick /// corresponding AllocationState.
REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,SymbolRef,MacOSKeychainAPIChecker::AllocationState)156e5dd7070Spatrick REGISTER_MAP_WITH_PROGRAMSTATE(AllocatedData,
157e5dd7070Spatrick SymbolRef,
158e5dd7070Spatrick MacOSKeychainAPIChecker::AllocationState)
159e5dd7070Spatrick
160e5dd7070Spatrick static bool isEnclosingFunctionParam(const Expr *E) {
161e5dd7070Spatrick E = E->IgnoreParenCasts();
162e5dd7070Spatrick if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
163e5dd7070Spatrick const ValueDecl *VD = DRE->getDecl();
164*12c85518Srobert if (isa<ImplicitParamDecl, ParmVarDecl>(VD))
165e5dd7070Spatrick return true;
166e5dd7070Spatrick }
167e5dd7070Spatrick return false;
168e5dd7070Spatrick }
169e5dd7070Spatrick
170e5dd7070Spatrick const MacOSKeychainAPIChecker::ADFunctionInfo
171e5dd7070Spatrick MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
172e5dd7070Spatrick {"SecKeychainItemCopyContent", 4, 3, ValidAPI}, // 0
173e5dd7070Spatrick {"SecKeychainFindGenericPassword", 6, 3, ValidAPI}, // 1
174e5dd7070Spatrick {"SecKeychainFindInternetPassword", 13, 3, ValidAPI}, // 2
175e5dd7070Spatrick {"SecKeychainItemFreeContent", 1, InvalidIdx, ValidAPI}, // 3
176e5dd7070Spatrick {"SecKeychainItemCopyAttributesAndData", 5, 5, ValidAPI}, // 4
177e5dd7070Spatrick {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx, ValidAPI}, // 5
178e5dd7070Spatrick {"free", 0, InvalidIdx, ErrorAPI}, // 6
179e5dd7070Spatrick {"CFStringCreateWithBytesNoCopy", 1, InvalidIdx, PossibleAPI}, // 7
180e5dd7070Spatrick };
181e5dd7070Spatrick
getTrackedFunctionIndex(StringRef Name,bool IsAllocator)182e5dd7070Spatrick unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
183e5dd7070Spatrick bool IsAllocator) {
184e5dd7070Spatrick for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
185e5dd7070Spatrick ADFunctionInfo FI = FunctionsToTrack[I];
186e5dd7070Spatrick if (FI.Name != Name)
187e5dd7070Spatrick continue;
188e5dd7070Spatrick // Make sure the function is of the right type (allocator vs deallocator).
189e5dd7070Spatrick if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
190e5dd7070Spatrick return InvalidIdx;
191e5dd7070Spatrick if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
192e5dd7070Spatrick return InvalidIdx;
193e5dd7070Spatrick
194e5dd7070Spatrick return I;
195e5dd7070Spatrick }
196e5dd7070Spatrick // The function is not tracked.
197e5dd7070Spatrick return InvalidIdx;
198e5dd7070Spatrick }
199e5dd7070Spatrick
isBadDeallocationArgument(const MemRegion * Arg)200e5dd7070Spatrick static bool isBadDeallocationArgument(const MemRegion *Arg) {
201e5dd7070Spatrick if (!Arg)
202e5dd7070Spatrick return false;
203*12c85518Srobert return isa<AllocaRegion, BlockDataRegion, TypedRegion>(Arg);
204e5dd7070Spatrick }
205e5dd7070Spatrick
206e5dd7070Spatrick /// Given the address expression, retrieve the value it's pointing to. Assume
207e5dd7070Spatrick /// that value is itself an address, and return the corresponding symbol.
getAsPointeeSymbol(const Expr * Expr,CheckerContext & C)208e5dd7070Spatrick static SymbolRef getAsPointeeSymbol(const Expr *Expr,
209e5dd7070Spatrick CheckerContext &C) {
210e5dd7070Spatrick ProgramStateRef State = C.getState();
211e5dd7070Spatrick SVal ArgV = C.getSVal(Expr);
212e5dd7070Spatrick
213*12c85518Srobert if (std::optional<loc::MemRegionVal> X = ArgV.getAs<loc::MemRegionVal>()) {
214e5dd7070Spatrick StoreManager& SM = C.getStoreManager();
215e5dd7070Spatrick SymbolRef sym = SM.getBinding(State->getStore(), *X).getAsLocSymbol();
216e5dd7070Spatrick if (sym)
217e5dd7070Spatrick return sym;
218e5dd7070Spatrick }
219e5dd7070Spatrick return nullptr;
220e5dd7070Spatrick }
221e5dd7070Spatrick
222e5dd7070Spatrick // Report deallocator mismatch. Remove the region from tracking - reporting a
223e5dd7070Spatrick // missing free error after this one is redundant.
224e5dd7070Spatrick void MacOSKeychainAPIChecker::
generateDeallocatorMismatchReport(const AllocationPair & AP,const Expr * ArgExpr,CheckerContext & C) const225e5dd7070Spatrick generateDeallocatorMismatchReport(const AllocationPair &AP,
226e5dd7070Spatrick const Expr *ArgExpr,
227e5dd7070Spatrick CheckerContext &C) const {
228e5dd7070Spatrick ProgramStateRef State = C.getState();
229e5dd7070Spatrick State = State->remove<AllocatedData>(AP.first);
230e5dd7070Spatrick ExplodedNode *N = C.generateNonFatalErrorNode(State);
231e5dd7070Spatrick
232e5dd7070Spatrick if (!N)
233e5dd7070Spatrick return;
234e5dd7070Spatrick initBugType();
235e5dd7070Spatrick SmallString<80> sbuf;
236e5dd7070Spatrick llvm::raw_svector_ostream os(sbuf);
237e5dd7070Spatrick unsigned int PDeallocIdx =
238e5dd7070Spatrick FunctionsToTrack[AP.second->AllocatorIdx].DeallocatorIdx;
239e5dd7070Spatrick
240e5dd7070Spatrick os << "Deallocator doesn't match the allocator: '"
241e5dd7070Spatrick << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
242e5dd7070Spatrick auto Report = std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
243e5dd7070Spatrick Report->addVisitor(std::make_unique<SecKeychainBugVisitor>(AP.first));
244e5dd7070Spatrick Report->addRange(ArgExpr->getSourceRange());
245e5dd7070Spatrick markInteresting(Report.get(), AP);
246e5dd7070Spatrick C.emitReport(std::move(Report));
247e5dd7070Spatrick }
248e5dd7070Spatrick
checkPreStmt(const CallExpr * CE,CheckerContext & C) const249e5dd7070Spatrick void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
250e5dd7070Spatrick CheckerContext &C) const {
251e5dd7070Spatrick unsigned idx = InvalidIdx;
252e5dd7070Spatrick ProgramStateRef State = C.getState();
253e5dd7070Spatrick
254e5dd7070Spatrick const FunctionDecl *FD = C.getCalleeDecl(CE);
255e5dd7070Spatrick if (!FD || FD->getKind() != Decl::Function)
256e5dd7070Spatrick return;
257e5dd7070Spatrick
258e5dd7070Spatrick StringRef funName = C.getCalleeName(FD);
259e5dd7070Spatrick if (funName.empty())
260e5dd7070Spatrick return;
261e5dd7070Spatrick
262e5dd7070Spatrick // If it is a call to an allocator function, it could be a double allocation.
263e5dd7070Spatrick idx = getTrackedFunctionIndex(funName, true);
264e5dd7070Spatrick if (idx != InvalidIdx) {
265e5dd7070Spatrick unsigned paramIdx = FunctionsToTrack[idx].Param;
266e5dd7070Spatrick if (CE->getNumArgs() <= paramIdx)
267e5dd7070Spatrick return;
268e5dd7070Spatrick
269e5dd7070Spatrick const Expr *ArgExpr = CE->getArg(paramIdx);
270e5dd7070Spatrick if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
271e5dd7070Spatrick if (const AllocationState *AS = State->get<AllocatedData>(V)) {
272e5dd7070Spatrick // Remove the value from the state. The new symbol will be added for
273e5dd7070Spatrick // tracking when the second allocator is processed in checkPostStmt().
274e5dd7070Spatrick State = State->remove<AllocatedData>(V);
275e5dd7070Spatrick ExplodedNode *N = C.generateNonFatalErrorNode(State);
276e5dd7070Spatrick if (!N)
277e5dd7070Spatrick return;
278e5dd7070Spatrick initBugType();
279e5dd7070Spatrick SmallString<128> sbuf;
280e5dd7070Spatrick llvm::raw_svector_ostream os(sbuf);
281e5dd7070Spatrick unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
282e5dd7070Spatrick os << "Allocated data should be released before another call to "
283e5dd7070Spatrick << "the allocator: missing a call to '"
284e5dd7070Spatrick << FunctionsToTrack[DIdx].Name
285e5dd7070Spatrick << "'.";
286e5dd7070Spatrick auto Report =
287e5dd7070Spatrick std::make_unique<PathSensitiveBugReport>(*BT, os.str(), N);
288e5dd7070Spatrick Report->addVisitor(std::make_unique<SecKeychainBugVisitor>(V));
289e5dd7070Spatrick Report->addRange(ArgExpr->getSourceRange());
290e5dd7070Spatrick Report->markInteresting(AS->Region);
291e5dd7070Spatrick C.emitReport(std::move(Report));
292e5dd7070Spatrick }
293e5dd7070Spatrick return;
294e5dd7070Spatrick }
295e5dd7070Spatrick
296e5dd7070Spatrick // Is it a call to one of deallocator functions?
297e5dd7070Spatrick idx = getTrackedFunctionIndex(funName, false);
298e5dd7070Spatrick if (idx == InvalidIdx)
299e5dd7070Spatrick return;
300e5dd7070Spatrick
301e5dd7070Spatrick unsigned paramIdx = FunctionsToTrack[idx].Param;
302e5dd7070Spatrick if (CE->getNumArgs() <= paramIdx)
303e5dd7070Spatrick return;
304e5dd7070Spatrick
305e5dd7070Spatrick // Check the argument to the deallocator.
306e5dd7070Spatrick const Expr *ArgExpr = CE->getArg(paramIdx);
307e5dd7070Spatrick SVal ArgSVal = C.getSVal(ArgExpr);
308e5dd7070Spatrick
309e5dd7070Spatrick // Undef is reported by another checker.
310e5dd7070Spatrick if (ArgSVal.isUndef())
311e5dd7070Spatrick return;
312e5dd7070Spatrick
313e5dd7070Spatrick SymbolRef ArgSM = ArgSVal.getAsLocSymbol();
314e5dd7070Spatrick
315e5dd7070Spatrick // If the argument is coming from the heap, globals, or unknown, do not
316e5dd7070Spatrick // report it.
317e5dd7070Spatrick bool RegionArgIsBad = false;
318e5dd7070Spatrick if (!ArgSM) {
319e5dd7070Spatrick if (!isBadDeallocationArgument(ArgSVal.getAsRegion()))
320e5dd7070Spatrick return;
321e5dd7070Spatrick RegionArgIsBad = true;
322e5dd7070Spatrick }
323e5dd7070Spatrick
324e5dd7070Spatrick // Is the argument to the call being tracked?
325e5dd7070Spatrick const AllocationState *AS = State->get<AllocatedData>(ArgSM);
326e5dd7070Spatrick if (!AS)
327e5dd7070Spatrick return;
328e5dd7070Spatrick
329e5dd7070Spatrick // TODO: We might want to report double free here.
330e5dd7070Spatrick // (that would involve tracking all the freed symbols in the checker state).
331e5dd7070Spatrick if (RegionArgIsBad) {
332e5dd7070Spatrick // It is possible that this is a false positive - the argument might
333e5dd7070Spatrick // have entered as an enclosing function parameter.
334e5dd7070Spatrick if (isEnclosingFunctionParam(ArgExpr))
335e5dd7070Spatrick return;
336e5dd7070Spatrick
337e5dd7070Spatrick ExplodedNode *N = C.generateNonFatalErrorNode(State);
338e5dd7070Spatrick if (!N)
339e5dd7070Spatrick return;
340e5dd7070Spatrick initBugType();
341e5dd7070Spatrick auto Report = std::make_unique<PathSensitiveBugReport>(
342e5dd7070Spatrick *BT, "Trying to free data which has not been allocated.", N);
343e5dd7070Spatrick Report->addRange(ArgExpr->getSourceRange());
344e5dd7070Spatrick if (AS)
345e5dd7070Spatrick Report->markInteresting(AS->Region);
346e5dd7070Spatrick C.emitReport(std::move(Report));
347e5dd7070Spatrick return;
348e5dd7070Spatrick }
349e5dd7070Spatrick
350e5dd7070Spatrick // Process functions which might deallocate.
351e5dd7070Spatrick if (FunctionsToTrack[idx].Kind == PossibleAPI) {
352e5dd7070Spatrick
353e5dd7070Spatrick if (funName == "CFStringCreateWithBytesNoCopy") {
354e5dd7070Spatrick const Expr *DeallocatorExpr = CE->getArg(5)->IgnoreParenCasts();
355e5dd7070Spatrick // NULL ~ default deallocator, so warn.
356e5dd7070Spatrick if (DeallocatorExpr->isNullPointerConstant(C.getASTContext(),
357e5dd7070Spatrick Expr::NPC_ValueDependentIsNotNull)) {
358e5dd7070Spatrick const AllocationPair AP = std::make_pair(ArgSM, AS);
359e5dd7070Spatrick generateDeallocatorMismatchReport(AP, ArgExpr, C);
360e5dd7070Spatrick return;
361e5dd7070Spatrick }
362e5dd7070Spatrick // One of the default allocators, so warn.
363e5dd7070Spatrick if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(DeallocatorExpr)) {
364e5dd7070Spatrick StringRef DeallocatorName = DE->getFoundDecl()->getName();
365e5dd7070Spatrick if (DeallocatorName == "kCFAllocatorDefault" ||
366e5dd7070Spatrick DeallocatorName == "kCFAllocatorSystemDefault" ||
367e5dd7070Spatrick DeallocatorName == "kCFAllocatorMalloc") {
368e5dd7070Spatrick const AllocationPair AP = std::make_pair(ArgSM, AS);
369e5dd7070Spatrick generateDeallocatorMismatchReport(AP, ArgExpr, C);
370e5dd7070Spatrick return;
371e5dd7070Spatrick }
372e5dd7070Spatrick // If kCFAllocatorNull, which does not deallocate, we still have to
373e5dd7070Spatrick // find the deallocator.
374e5dd7070Spatrick if (DE->getFoundDecl()->getName() == "kCFAllocatorNull")
375e5dd7070Spatrick return;
376e5dd7070Spatrick }
377e5dd7070Spatrick // In all other cases, assume the user supplied a correct deallocator
378e5dd7070Spatrick // that will free memory so stop tracking.
379e5dd7070Spatrick State = State->remove<AllocatedData>(ArgSM);
380e5dd7070Spatrick C.addTransition(State);
381e5dd7070Spatrick return;
382e5dd7070Spatrick }
383e5dd7070Spatrick
384e5dd7070Spatrick llvm_unreachable("We know of no other possible APIs.");
385e5dd7070Spatrick }
386e5dd7070Spatrick
387e5dd7070Spatrick // The call is deallocating a value we previously allocated, so remove it
388e5dd7070Spatrick // from the next state.
389e5dd7070Spatrick State = State->remove<AllocatedData>(ArgSM);
390e5dd7070Spatrick
391e5dd7070Spatrick // Check if the proper deallocator is used.
392e5dd7070Spatrick unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
393e5dd7070Spatrick if (PDeallocIdx != idx || (FunctionsToTrack[idx].Kind == ErrorAPI)) {
394e5dd7070Spatrick const AllocationPair AP = std::make_pair(ArgSM, AS);
395e5dd7070Spatrick generateDeallocatorMismatchReport(AP, ArgExpr, C);
396e5dd7070Spatrick return;
397e5dd7070Spatrick }
398e5dd7070Spatrick
399e5dd7070Spatrick C.addTransition(State);
400e5dd7070Spatrick }
401e5dd7070Spatrick
checkPostStmt(const CallExpr * CE,CheckerContext & C) const402e5dd7070Spatrick void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
403e5dd7070Spatrick CheckerContext &C) const {
404e5dd7070Spatrick ProgramStateRef State = C.getState();
405e5dd7070Spatrick const FunctionDecl *FD = C.getCalleeDecl(CE);
406e5dd7070Spatrick if (!FD || FD->getKind() != Decl::Function)
407e5dd7070Spatrick return;
408e5dd7070Spatrick
409e5dd7070Spatrick StringRef funName = C.getCalleeName(FD);
410e5dd7070Spatrick
411e5dd7070Spatrick // If a value has been allocated, add it to the set for tracking.
412e5dd7070Spatrick unsigned idx = getTrackedFunctionIndex(funName, true);
413e5dd7070Spatrick if (idx == InvalidIdx)
414e5dd7070Spatrick return;
415e5dd7070Spatrick
416e5dd7070Spatrick const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
417e5dd7070Spatrick // If the argument entered as an enclosing function parameter, skip it to
418e5dd7070Spatrick // avoid false positives.
419e5dd7070Spatrick if (isEnclosingFunctionParam(ArgExpr) &&
420e5dd7070Spatrick C.getLocationContext()->getParent() == nullptr)
421e5dd7070Spatrick return;
422e5dd7070Spatrick
423e5dd7070Spatrick if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
424e5dd7070Spatrick // If the argument points to something that's not a symbolic region, it
425e5dd7070Spatrick // can be:
426e5dd7070Spatrick // - unknown (cannot reason about it)
427e5dd7070Spatrick // - undefined (already reported by other checker)
428e5dd7070Spatrick // - constant (null - should not be tracked,
429e5dd7070Spatrick // other constant will generate a compiler warning)
430e5dd7070Spatrick // - goto (should be reported by other checker)
431e5dd7070Spatrick
432e5dd7070Spatrick // The call return value symbol should stay alive for as long as the
433e5dd7070Spatrick // allocated value symbol, since our diagnostics depend on the value
434e5dd7070Spatrick // returned by the call. Ex: Data should only be freed if noErr was
435e5dd7070Spatrick // returned during allocation.)
436e5dd7070Spatrick SymbolRef RetStatusSymbol = C.getSVal(CE).getAsSymbol();
437e5dd7070Spatrick C.getSymbolManager().addSymbolDependency(V, RetStatusSymbol);
438e5dd7070Spatrick
439e5dd7070Spatrick // Track the allocated value in the checker state.
440e5dd7070Spatrick State = State->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
441e5dd7070Spatrick RetStatusSymbol));
442e5dd7070Spatrick assert(State);
443e5dd7070Spatrick C.addTransition(State);
444e5dd7070Spatrick }
445e5dd7070Spatrick }
446e5dd7070Spatrick
447e5dd7070Spatrick // TODO: This logic is the same as in Malloc checker.
448e5dd7070Spatrick const ExplodedNode *
getAllocationNode(const ExplodedNode * N,SymbolRef Sym,CheckerContext & C) const449e5dd7070Spatrick MacOSKeychainAPIChecker::getAllocationNode(const ExplodedNode *N,
450e5dd7070Spatrick SymbolRef Sym,
451e5dd7070Spatrick CheckerContext &C) const {
452e5dd7070Spatrick const LocationContext *LeakContext = N->getLocationContext();
453e5dd7070Spatrick // Walk the ExplodedGraph backwards and find the first node that referred to
454e5dd7070Spatrick // the tracked symbol.
455e5dd7070Spatrick const ExplodedNode *AllocNode = N;
456e5dd7070Spatrick
457e5dd7070Spatrick while (N) {
458e5dd7070Spatrick if (!N->getState()->get<AllocatedData>(Sym))
459e5dd7070Spatrick break;
460e5dd7070Spatrick // Allocation node, is the last node in the current or parent context in
461e5dd7070Spatrick // which the symbol was tracked.
462e5dd7070Spatrick const LocationContext *NContext = N->getLocationContext();
463e5dd7070Spatrick if (NContext == LeakContext ||
464e5dd7070Spatrick NContext->isParentOf(LeakContext))
465e5dd7070Spatrick AllocNode = N;
466e5dd7070Spatrick N = N->pred_empty() ? nullptr : *(N->pred_begin());
467e5dd7070Spatrick }
468e5dd7070Spatrick
469e5dd7070Spatrick return AllocNode;
470e5dd7070Spatrick }
471e5dd7070Spatrick
472e5dd7070Spatrick std::unique_ptr<PathSensitiveBugReport>
generateAllocatedDataNotReleasedReport(const AllocationPair & AP,ExplodedNode * N,CheckerContext & C) const473e5dd7070Spatrick MacOSKeychainAPIChecker::generateAllocatedDataNotReleasedReport(
474e5dd7070Spatrick const AllocationPair &AP, ExplodedNode *N, CheckerContext &C) const {
475e5dd7070Spatrick const ADFunctionInfo &FI = FunctionsToTrack[AP.second->AllocatorIdx];
476e5dd7070Spatrick initBugType();
477e5dd7070Spatrick SmallString<70> sbuf;
478e5dd7070Spatrick llvm::raw_svector_ostream os(sbuf);
479e5dd7070Spatrick os << "Allocated data is not released: missing a call to '"
480e5dd7070Spatrick << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
481e5dd7070Spatrick
482e5dd7070Spatrick // Most bug reports are cached at the location where they occurred.
483e5dd7070Spatrick // With leaks, we want to unique them by the location where they were
484e5dd7070Spatrick // allocated, and only report a single path.
485e5dd7070Spatrick PathDiagnosticLocation LocUsedForUniqueing;
486e5dd7070Spatrick const ExplodedNode *AllocNode = getAllocationNode(N, AP.first, C);
487e5dd7070Spatrick const Stmt *AllocStmt = AllocNode->getStmtForDiagnostics();
488e5dd7070Spatrick
489e5dd7070Spatrick if (AllocStmt)
490e5dd7070Spatrick LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocStmt,
491e5dd7070Spatrick C.getSourceManager(),
492e5dd7070Spatrick AllocNode->getLocationContext());
493e5dd7070Spatrick
494e5dd7070Spatrick auto Report = std::make_unique<PathSensitiveBugReport>(
495e5dd7070Spatrick *BT, os.str(), N, LocUsedForUniqueing,
496e5dd7070Spatrick AllocNode->getLocationContext()->getDecl());
497e5dd7070Spatrick
498e5dd7070Spatrick Report->addVisitor(std::make_unique<SecKeychainBugVisitor>(AP.first));
499e5dd7070Spatrick markInteresting(Report.get(), AP);
500e5dd7070Spatrick return Report;
501e5dd7070Spatrick }
502e5dd7070Spatrick
503e5dd7070Spatrick /// If the return symbol is assumed to be error, remove the allocated info
504e5dd7070Spatrick /// from consideration.
evalAssume(ProgramStateRef State,SVal Cond,bool Assumption) const505e5dd7070Spatrick ProgramStateRef MacOSKeychainAPIChecker::evalAssume(ProgramStateRef State,
506e5dd7070Spatrick SVal Cond,
507e5dd7070Spatrick bool Assumption) const {
508e5dd7070Spatrick AllocatedDataTy AMap = State->get<AllocatedData>();
509e5dd7070Spatrick if (AMap.isEmpty())
510e5dd7070Spatrick return State;
511e5dd7070Spatrick
512a9ac8606Spatrick auto *CondBSE = dyn_cast_or_null<BinarySymExpr>(Cond.getAsSymbol());
513e5dd7070Spatrick if (!CondBSE)
514e5dd7070Spatrick return State;
515e5dd7070Spatrick BinaryOperator::Opcode OpCode = CondBSE->getOpcode();
516e5dd7070Spatrick if (OpCode != BO_EQ && OpCode != BO_NE)
517e5dd7070Spatrick return State;
518e5dd7070Spatrick
519e5dd7070Spatrick // Match for a restricted set of patterns for cmparison of error codes.
520e5dd7070Spatrick // Note, the comparisons of type '0 == st' are transformed into SymIntExpr.
521e5dd7070Spatrick SymbolRef ReturnSymbol = nullptr;
522e5dd7070Spatrick if (auto *SIE = dyn_cast<SymIntExpr>(CondBSE)) {
523e5dd7070Spatrick const llvm::APInt &RHS = SIE->getRHS();
524e5dd7070Spatrick bool ErrorIsReturned = (OpCode == BO_EQ && RHS != NoErr) ||
525e5dd7070Spatrick (OpCode == BO_NE && RHS == NoErr);
526e5dd7070Spatrick if (!Assumption)
527e5dd7070Spatrick ErrorIsReturned = !ErrorIsReturned;
528e5dd7070Spatrick if (ErrorIsReturned)
529e5dd7070Spatrick ReturnSymbol = SIE->getLHS();
530e5dd7070Spatrick }
531e5dd7070Spatrick
532e5dd7070Spatrick if (ReturnSymbol)
533e5dd7070Spatrick for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
534e5dd7070Spatrick if (ReturnSymbol == I->second.Region)
535e5dd7070Spatrick State = State->remove<AllocatedData>(I->first);
536e5dd7070Spatrick }
537e5dd7070Spatrick
538e5dd7070Spatrick return State;
539e5dd7070Spatrick }
540e5dd7070Spatrick
checkDeadSymbols(SymbolReaper & SR,CheckerContext & C) const541e5dd7070Spatrick void MacOSKeychainAPIChecker::checkDeadSymbols(SymbolReaper &SR,
542e5dd7070Spatrick CheckerContext &C) const {
543e5dd7070Spatrick ProgramStateRef State = C.getState();
544e5dd7070Spatrick AllocatedDataTy AMap = State->get<AllocatedData>();
545e5dd7070Spatrick if (AMap.isEmpty())
546e5dd7070Spatrick return;
547e5dd7070Spatrick
548e5dd7070Spatrick bool Changed = false;
549e5dd7070Spatrick AllocationPairVec Errors;
550e5dd7070Spatrick for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
551e5dd7070Spatrick if (!SR.isDead(I->first))
552e5dd7070Spatrick continue;
553e5dd7070Spatrick
554e5dd7070Spatrick Changed = true;
555e5dd7070Spatrick State = State->remove<AllocatedData>(I->first);
556e5dd7070Spatrick // If the allocated symbol is null do not report.
557e5dd7070Spatrick ConstraintManager &CMgr = State->getConstraintManager();
558e5dd7070Spatrick ConditionTruthVal AllocFailed = CMgr.isNull(State, I.getKey());
559e5dd7070Spatrick if (AllocFailed.isConstrainedTrue())
560e5dd7070Spatrick continue;
561e5dd7070Spatrick Errors.push_back(std::make_pair(I->first, &I->second));
562e5dd7070Spatrick }
563e5dd7070Spatrick if (!Changed) {
564e5dd7070Spatrick // Generate the new, cleaned up state.
565e5dd7070Spatrick C.addTransition(State);
566e5dd7070Spatrick return;
567e5dd7070Spatrick }
568e5dd7070Spatrick
569e5dd7070Spatrick static CheckerProgramPointTag Tag(this, "DeadSymbolsLeak");
570e5dd7070Spatrick ExplodedNode *N = C.generateNonFatalErrorNode(C.getState(), &Tag);
571e5dd7070Spatrick if (!N)
572e5dd7070Spatrick return;
573e5dd7070Spatrick
574e5dd7070Spatrick // Generate the error reports.
575e5dd7070Spatrick for (const auto &P : Errors)
576e5dd7070Spatrick C.emitReport(generateAllocatedDataNotReleasedReport(P, N, C));
577e5dd7070Spatrick
578e5dd7070Spatrick // Generate the new, cleaned up state.
579e5dd7070Spatrick C.addTransition(State, N);
580e5dd7070Spatrick }
581e5dd7070Spatrick
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const582e5dd7070Spatrick ProgramStateRef MacOSKeychainAPIChecker::checkPointerEscape(
583e5dd7070Spatrick ProgramStateRef State, const InvalidatedSymbols &Escaped,
584e5dd7070Spatrick const CallEvent *Call, PointerEscapeKind Kind) const {
585e5dd7070Spatrick // FIXME: This branch doesn't make any sense at all, but it is an overfitted
586e5dd7070Spatrick // replacement for a previous overfitted code that was making even less sense.
587e5dd7070Spatrick if (!Call || Call->getDecl())
588e5dd7070Spatrick return State;
589e5dd7070Spatrick
590e5dd7070Spatrick for (auto I : State->get<AllocatedData>()) {
591e5dd7070Spatrick SymbolRef Sym = I.first;
592e5dd7070Spatrick if (Escaped.count(Sym))
593e5dd7070Spatrick State = State->remove<AllocatedData>(Sym);
594e5dd7070Spatrick
595e5dd7070Spatrick // This checker is special. Most checkers in fact only track symbols of
596e5dd7070Spatrick // SymbolConjured type, eg. symbols returned from functions such as
597e5dd7070Spatrick // malloc(). This checker tracks symbols returned as out-parameters.
598e5dd7070Spatrick //
599e5dd7070Spatrick // When a function is evaluated conservatively, the out-parameter's pointee
600e5dd7070Spatrick // base region gets invalidated with a SymbolConjured. If the base region is
601e5dd7070Spatrick // larger than the region we're interested in, the value we're interested in
602e5dd7070Spatrick // would be SymbolDerived based on that SymbolConjured. However, such
603e5dd7070Spatrick // SymbolDerived will never be listed in the Escaped set when the base
604e5dd7070Spatrick // region is invalidated because ExprEngine doesn't know which symbols
605e5dd7070Spatrick // were derived from a given symbol, while there can be infinitely many
606e5dd7070Spatrick // valid symbols derived from any given symbol.
607e5dd7070Spatrick //
608e5dd7070Spatrick // Hence the extra boilerplate: remove the derived symbol when its parent
609e5dd7070Spatrick // symbol escapes.
610e5dd7070Spatrick //
611e5dd7070Spatrick if (const auto *SD = dyn_cast<SymbolDerived>(Sym)) {
612e5dd7070Spatrick SymbolRef ParentSym = SD->getParentSymbol();
613e5dd7070Spatrick if (Escaped.count(ParentSym))
614e5dd7070Spatrick State = State->remove<AllocatedData>(Sym);
615e5dd7070Spatrick }
616e5dd7070Spatrick }
617e5dd7070Spatrick return State;
618e5dd7070Spatrick }
619e5dd7070Spatrick
620e5dd7070Spatrick PathDiagnosticPieceRef
VisitNode(const ExplodedNode * N,BugReporterContext & BRC,PathSensitiveBugReport & BR)621e5dd7070Spatrick MacOSKeychainAPIChecker::SecKeychainBugVisitor::VisitNode(
622e5dd7070Spatrick const ExplodedNode *N, BugReporterContext &BRC,
623e5dd7070Spatrick PathSensitiveBugReport &BR) {
624e5dd7070Spatrick const AllocationState *AS = N->getState()->get<AllocatedData>(Sym);
625e5dd7070Spatrick if (!AS)
626e5dd7070Spatrick return nullptr;
627e5dd7070Spatrick const AllocationState *ASPrev =
628e5dd7070Spatrick N->getFirstPred()->getState()->get<AllocatedData>(Sym);
629e5dd7070Spatrick if (ASPrev)
630e5dd7070Spatrick return nullptr;
631e5dd7070Spatrick
632e5dd7070Spatrick // (!ASPrev && AS) ~ We started tracking symbol in node N, it must be the
633e5dd7070Spatrick // allocation site.
634e5dd7070Spatrick const CallExpr *CE =
635e5dd7070Spatrick cast<CallExpr>(N->getLocation().castAs<StmtPoint>().getStmt());
636e5dd7070Spatrick const FunctionDecl *funDecl = CE->getDirectCallee();
637e5dd7070Spatrick assert(funDecl && "We do not support indirect function calls as of now.");
638e5dd7070Spatrick StringRef funName = funDecl->getName();
639e5dd7070Spatrick
640e5dd7070Spatrick // Get the expression of the corresponding argument.
641e5dd7070Spatrick unsigned Idx = getTrackedFunctionIndex(funName, true);
642e5dd7070Spatrick assert(Idx != InvalidIdx && "This should be a call to an allocator.");
643e5dd7070Spatrick const Expr *ArgExpr = CE->getArg(FunctionsToTrack[Idx].Param);
644e5dd7070Spatrick PathDiagnosticLocation Pos(ArgExpr, BRC.getSourceManager(),
645e5dd7070Spatrick N->getLocationContext());
646e5dd7070Spatrick return std::make_shared<PathDiagnosticEventPiece>(Pos,
647e5dd7070Spatrick "Data is allocated here.");
648e5dd7070Spatrick }
649e5dd7070Spatrick
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const650e5dd7070Spatrick void MacOSKeychainAPIChecker::printState(raw_ostream &Out,
651e5dd7070Spatrick ProgramStateRef State,
652e5dd7070Spatrick const char *NL,
653e5dd7070Spatrick const char *Sep) const {
654e5dd7070Spatrick
655e5dd7070Spatrick AllocatedDataTy AMap = State->get<AllocatedData>();
656e5dd7070Spatrick
657e5dd7070Spatrick if (!AMap.isEmpty()) {
658e5dd7070Spatrick Out << Sep << "KeychainAPIChecker :" << NL;
659e5dd7070Spatrick for (auto I = AMap.begin(), E = AMap.end(); I != E; ++I) {
660e5dd7070Spatrick I.getKey()->dumpToStream(Out);
661e5dd7070Spatrick }
662e5dd7070Spatrick }
663e5dd7070Spatrick }
664e5dd7070Spatrick
665e5dd7070Spatrick
registerMacOSKeychainAPIChecker(CheckerManager & mgr)666e5dd7070Spatrick void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
667e5dd7070Spatrick mgr.registerChecker<MacOSKeychainAPIChecker>();
668e5dd7070Spatrick }
669e5dd7070Spatrick
shouldRegisterMacOSKeychainAPIChecker(const CheckerManager & mgr)670ec727ea7Spatrick bool ento::shouldRegisterMacOSKeychainAPIChecker(const CheckerManager &mgr) {
671e5dd7070Spatrick return true;
672e5dd7070Spatrick }
673