1f4a2713aSLionel Sambuc //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file defines malloc/free checker, which checks for potential memory
11f4a2713aSLionel Sambuc // leaks, double free, and use-after-free problems.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc
15f4a2713aSLionel Sambuc #include "ClangSACheckers.h"
16f4a2713aSLionel Sambuc #include "InterCheckerAPI.h"
17f4a2713aSLionel Sambuc #include "clang/AST/Attr.h"
18*0a6a1f1dSLionel Sambuc #include "clang/AST/ParentMap.h"
19f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
20*0a6a1f1dSLionel Sambuc #include "clang/Basic/TargetInfo.h"
21f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/Checker.h"
23f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
26f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
28f4a2713aSLionel Sambuc #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
29f4a2713aSLionel Sambuc #include "llvm/ADT/ImmutableMap.h"
30f4a2713aSLionel Sambuc #include "llvm/ADT/STLExtras.h"
31f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
32f4a2713aSLionel Sambuc #include "llvm/ADT/StringExtras.h"
33f4a2713aSLionel Sambuc #include <climits>
34f4a2713aSLionel Sambuc
35f4a2713aSLionel Sambuc using namespace clang;
36f4a2713aSLionel Sambuc using namespace ento;
37f4a2713aSLionel Sambuc
38f4a2713aSLionel Sambuc namespace {
39f4a2713aSLionel Sambuc
40f4a2713aSLionel Sambuc // Used to check correspondence between allocators and deallocators.
41f4a2713aSLionel Sambuc enum AllocationFamily {
42f4a2713aSLionel Sambuc AF_None,
43f4a2713aSLionel Sambuc AF_Malloc,
44f4a2713aSLionel Sambuc AF_CXXNew,
45*0a6a1f1dSLionel Sambuc AF_CXXNewArray,
46*0a6a1f1dSLionel Sambuc AF_IfNameIndex
47f4a2713aSLionel Sambuc };
48f4a2713aSLionel Sambuc
49f4a2713aSLionel Sambuc class RefState {
50f4a2713aSLionel Sambuc enum Kind { // Reference to allocated memory.
51f4a2713aSLionel Sambuc Allocated,
52f4a2713aSLionel Sambuc // Reference to released/freed memory.
53f4a2713aSLionel Sambuc Released,
54*0a6a1f1dSLionel Sambuc // The responsibility for freeing resources has transferred from
55f4a2713aSLionel Sambuc // this reference. A relinquished symbol should not be freed.
56f4a2713aSLionel Sambuc Relinquished,
57f4a2713aSLionel Sambuc // We are no longer guaranteed to have observed all manipulations
58f4a2713aSLionel Sambuc // of this pointer/memory. For example, it could have been
59f4a2713aSLionel Sambuc // passed as a parameter to an opaque function.
60f4a2713aSLionel Sambuc Escaped
61f4a2713aSLionel Sambuc };
62f4a2713aSLionel Sambuc
63f4a2713aSLionel Sambuc const Stmt *S;
64f4a2713aSLionel Sambuc unsigned K : 2; // Kind enum, but stored as a bitfield.
65f4a2713aSLionel Sambuc unsigned Family : 30; // Rest of 32-bit word, currently just an allocation
66f4a2713aSLionel Sambuc // family.
67f4a2713aSLionel Sambuc
RefState(Kind k,const Stmt * s,unsigned family)68f4a2713aSLionel Sambuc RefState(Kind k, const Stmt *s, unsigned family)
69f4a2713aSLionel Sambuc : S(s), K(k), Family(family) {
70f4a2713aSLionel Sambuc assert(family != AF_None);
71f4a2713aSLionel Sambuc }
72f4a2713aSLionel Sambuc public:
isAllocated() const73f4a2713aSLionel Sambuc bool isAllocated() const { return K == Allocated; }
isReleased() const74f4a2713aSLionel Sambuc bool isReleased() const { return K == Released; }
isRelinquished() const75f4a2713aSLionel Sambuc bool isRelinquished() const { return K == Relinquished; }
isEscaped() const76f4a2713aSLionel Sambuc bool isEscaped() const { return K == Escaped; }
getAllocationFamily() const77f4a2713aSLionel Sambuc AllocationFamily getAllocationFamily() const {
78f4a2713aSLionel Sambuc return (AllocationFamily)Family;
79f4a2713aSLionel Sambuc }
getStmt() const80f4a2713aSLionel Sambuc const Stmt *getStmt() const { return S; }
81f4a2713aSLionel Sambuc
operator ==(const RefState & X) const82f4a2713aSLionel Sambuc bool operator==(const RefState &X) const {
83f4a2713aSLionel Sambuc return K == X.K && S == X.S && Family == X.Family;
84f4a2713aSLionel Sambuc }
85f4a2713aSLionel Sambuc
getAllocated(unsigned family,const Stmt * s)86f4a2713aSLionel Sambuc static RefState getAllocated(unsigned family, const Stmt *s) {
87f4a2713aSLionel Sambuc return RefState(Allocated, s, family);
88f4a2713aSLionel Sambuc }
getReleased(unsigned family,const Stmt * s)89f4a2713aSLionel Sambuc static RefState getReleased(unsigned family, const Stmt *s) {
90f4a2713aSLionel Sambuc return RefState(Released, s, family);
91f4a2713aSLionel Sambuc }
getRelinquished(unsigned family,const Stmt * s)92f4a2713aSLionel Sambuc static RefState getRelinquished(unsigned family, const Stmt *s) {
93f4a2713aSLionel Sambuc return RefState(Relinquished, s, family);
94f4a2713aSLionel Sambuc }
getEscaped(const RefState * RS)95f4a2713aSLionel Sambuc static RefState getEscaped(const RefState *RS) {
96f4a2713aSLionel Sambuc return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
97f4a2713aSLionel Sambuc }
98f4a2713aSLionel Sambuc
Profile(llvm::FoldingSetNodeID & ID) const99f4a2713aSLionel Sambuc void Profile(llvm::FoldingSetNodeID &ID) const {
100f4a2713aSLionel Sambuc ID.AddInteger(K);
101f4a2713aSLionel Sambuc ID.AddPointer(S);
102f4a2713aSLionel Sambuc ID.AddInteger(Family);
103f4a2713aSLionel Sambuc }
104f4a2713aSLionel Sambuc
dump(raw_ostream & OS) const105f4a2713aSLionel Sambuc void dump(raw_ostream &OS) const {
106*0a6a1f1dSLionel Sambuc switch (static_cast<Kind>(K)) {
107*0a6a1f1dSLionel Sambuc #define CASE(ID) case ID: OS << #ID; break;
108*0a6a1f1dSLionel Sambuc CASE(Allocated)
109*0a6a1f1dSLionel Sambuc CASE(Released)
110*0a6a1f1dSLionel Sambuc CASE(Relinquished)
111*0a6a1f1dSLionel Sambuc CASE(Escaped)
112*0a6a1f1dSLionel Sambuc }
113f4a2713aSLionel Sambuc }
114f4a2713aSLionel Sambuc
dump() const115*0a6a1f1dSLionel Sambuc LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
116f4a2713aSLionel Sambuc };
117f4a2713aSLionel Sambuc
118f4a2713aSLionel Sambuc enum ReallocPairKind {
119f4a2713aSLionel Sambuc RPToBeFreedAfterFailure,
120f4a2713aSLionel Sambuc // The symbol has been freed when reallocation failed.
121f4a2713aSLionel Sambuc RPIsFreeOnFailure,
122f4a2713aSLionel Sambuc // The symbol does not need to be freed after reallocation fails.
123f4a2713aSLionel Sambuc RPDoNotTrackAfterFailure
124f4a2713aSLionel Sambuc };
125f4a2713aSLionel Sambuc
126f4a2713aSLionel Sambuc /// \class ReallocPair
127f4a2713aSLionel Sambuc /// \brief Stores information about the symbol being reallocated by a call to
128f4a2713aSLionel Sambuc /// 'realloc' to allow modeling failed reallocation later in the path.
129f4a2713aSLionel Sambuc struct ReallocPair {
130f4a2713aSLionel Sambuc // \brief The symbol which realloc reallocated.
131f4a2713aSLionel Sambuc SymbolRef ReallocatedSym;
132f4a2713aSLionel Sambuc ReallocPairKind Kind;
133f4a2713aSLionel Sambuc
ReallocPair__anon667d994e0111::ReallocPair134f4a2713aSLionel Sambuc ReallocPair(SymbolRef S, ReallocPairKind K) :
135f4a2713aSLionel Sambuc ReallocatedSym(S), Kind(K) {}
Profile__anon667d994e0111::ReallocPair136f4a2713aSLionel Sambuc void Profile(llvm::FoldingSetNodeID &ID) const {
137f4a2713aSLionel Sambuc ID.AddInteger(Kind);
138f4a2713aSLionel Sambuc ID.AddPointer(ReallocatedSym);
139f4a2713aSLionel Sambuc }
operator ==__anon667d994e0111::ReallocPair140f4a2713aSLionel Sambuc bool operator==(const ReallocPair &X) const {
141f4a2713aSLionel Sambuc return ReallocatedSym == X.ReallocatedSym &&
142f4a2713aSLionel Sambuc Kind == X.Kind;
143f4a2713aSLionel Sambuc }
144f4a2713aSLionel Sambuc };
145f4a2713aSLionel Sambuc
146f4a2713aSLionel Sambuc typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
147f4a2713aSLionel Sambuc
148f4a2713aSLionel Sambuc class MallocChecker : public Checker<check::DeadSymbols,
149f4a2713aSLionel Sambuc check::PointerEscape,
150f4a2713aSLionel Sambuc check::ConstPointerEscape,
151f4a2713aSLionel Sambuc check::PreStmt<ReturnStmt>,
152f4a2713aSLionel Sambuc check::PreCall,
153f4a2713aSLionel Sambuc check::PostStmt<CallExpr>,
154f4a2713aSLionel Sambuc check::PostStmt<CXXNewExpr>,
155f4a2713aSLionel Sambuc check::PreStmt<CXXDeleteExpr>,
156f4a2713aSLionel Sambuc check::PostStmt<BlockExpr>,
157f4a2713aSLionel Sambuc check::PostObjCMessage,
158f4a2713aSLionel Sambuc check::Location,
159f4a2713aSLionel Sambuc eval::Assume>
160f4a2713aSLionel Sambuc {
161f4a2713aSLionel Sambuc public:
MallocChecker()162*0a6a1f1dSLionel Sambuc MallocChecker()
163*0a6a1f1dSLionel Sambuc : II_malloc(nullptr), II_free(nullptr), II_realloc(nullptr),
164*0a6a1f1dSLionel Sambuc II_calloc(nullptr), II_valloc(nullptr), II_reallocf(nullptr),
165*0a6a1f1dSLionel Sambuc II_strndup(nullptr), II_strdup(nullptr), II_kmalloc(nullptr),
166*0a6a1f1dSLionel Sambuc II_if_nameindex(nullptr), II_if_freenameindex(nullptr) {}
167f4a2713aSLionel Sambuc
168f4a2713aSLionel Sambuc /// In pessimistic mode, the checker assumes that it does not know which
169f4a2713aSLionel Sambuc /// functions might free the memory.
170*0a6a1f1dSLionel Sambuc enum CheckKind {
171*0a6a1f1dSLionel Sambuc CK_MallocPessimistic,
172*0a6a1f1dSLionel Sambuc CK_MallocOptimistic,
173*0a6a1f1dSLionel Sambuc CK_NewDeleteChecker,
174*0a6a1f1dSLionel Sambuc CK_NewDeleteLeaksChecker,
175*0a6a1f1dSLionel Sambuc CK_MismatchedDeallocatorChecker,
176*0a6a1f1dSLionel Sambuc CK_NumCheckKinds
177f4a2713aSLionel Sambuc };
178f4a2713aSLionel Sambuc
179*0a6a1f1dSLionel Sambuc enum class MemoryOperationKind {
180*0a6a1f1dSLionel Sambuc MOK_Allocate,
181*0a6a1f1dSLionel Sambuc MOK_Free,
182*0a6a1f1dSLionel Sambuc MOK_Any
183*0a6a1f1dSLionel Sambuc };
184*0a6a1f1dSLionel Sambuc
185*0a6a1f1dSLionel Sambuc DefaultBool ChecksEnabled[CK_NumCheckKinds];
186*0a6a1f1dSLionel Sambuc CheckName CheckNames[CK_NumCheckKinds];
187f4a2713aSLionel Sambuc
188f4a2713aSLionel Sambuc void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
189f4a2713aSLionel Sambuc void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
190f4a2713aSLionel Sambuc void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
191f4a2713aSLionel Sambuc void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
192f4a2713aSLionel Sambuc void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
193f4a2713aSLionel Sambuc void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
194f4a2713aSLionel Sambuc void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
195f4a2713aSLionel Sambuc void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
196f4a2713aSLionel Sambuc ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
197f4a2713aSLionel Sambuc bool Assumption) const;
198f4a2713aSLionel Sambuc void checkLocation(SVal l, bool isLoad, const Stmt *S,
199f4a2713aSLionel Sambuc CheckerContext &C) const;
200f4a2713aSLionel Sambuc
201f4a2713aSLionel Sambuc ProgramStateRef checkPointerEscape(ProgramStateRef State,
202f4a2713aSLionel Sambuc const InvalidatedSymbols &Escaped,
203f4a2713aSLionel Sambuc const CallEvent *Call,
204f4a2713aSLionel Sambuc PointerEscapeKind Kind) const;
205f4a2713aSLionel Sambuc ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
206f4a2713aSLionel Sambuc const InvalidatedSymbols &Escaped,
207f4a2713aSLionel Sambuc const CallEvent *Call,
208f4a2713aSLionel Sambuc PointerEscapeKind Kind) const;
209f4a2713aSLionel Sambuc
210f4a2713aSLionel Sambuc void printState(raw_ostream &Out, ProgramStateRef State,
211*0a6a1f1dSLionel Sambuc const char *NL, const char *Sep) const override;
212f4a2713aSLionel Sambuc
213f4a2713aSLionel Sambuc private:
214*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
215*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_DoubleDelete;
216*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
217*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
218*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
219*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
220*0a6a1f1dSLionel Sambuc mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
221*0a6a1f1dSLionel Sambuc mutable IdentifierInfo *II_malloc, *II_free, *II_realloc, *II_calloc,
222*0a6a1f1dSLionel Sambuc *II_valloc, *II_reallocf, *II_strndup, *II_strdup,
223*0a6a1f1dSLionel Sambuc *II_kmalloc, *II_if_nameindex, *II_if_freenameindex;
224*0a6a1f1dSLionel Sambuc mutable Optional<uint64_t> KernelZeroFlagVal;
225*0a6a1f1dSLionel Sambuc
226f4a2713aSLionel Sambuc void initIdentifierInfo(ASTContext &C) const;
227f4a2713aSLionel Sambuc
228f4a2713aSLionel Sambuc /// \brief Determine family of a deallocation expression.
229f4a2713aSLionel Sambuc AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
230f4a2713aSLionel Sambuc
231f4a2713aSLionel Sambuc /// \brief Print names of allocators and deallocators.
232f4a2713aSLionel Sambuc ///
233f4a2713aSLionel Sambuc /// \returns true on success.
234f4a2713aSLionel Sambuc bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
235f4a2713aSLionel Sambuc const Expr *E) const;
236f4a2713aSLionel Sambuc
237f4a2713aSLionel Sambuc /// \brief Print expected name of an allocator based on the deallocator's
238f4a2713aSLionel Sambuc /// family derived from the DeallocExpr.
239f4a2713aSLionel Sambuc void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
240f4a2713aSLionel Sambuc const Expr *DeallocExpr) const;
241f4a2713aSLionel Sambuc /// \brief Print expected name of a deallocator based on the allocator's
242f4a2713aSLionel Sambuc /// family.
243f4a2713aSLionel Sambuc void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
244f4a2713aSLionel Sambuc
245f4a2713aSLionel Sambuc ///@{
246f4a2713aSLionel Sambuc /// Check if this is one of the functions which can allocate/reallocate memory
247f4a2713aSLionel Sambuc /// pointed to by one of its arguments.
248f4a2713aSLionel Sambuc bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
249*0a6a1f1dSLionel Sambuc bool isCMemFunction(const FunctionDecl *FD,
250*0a6a1f1dSLionel Sambuc ASTContext &C,
251*0a6a1f1dSLionel Sambuc AllocationFamily Family,
252*0a6a1f1dSLionel Sambuc MemoryOperationKind MemKind) const;
253f4a2713aSLionel Sambuc bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
254f4a2713aSLionel Sambuc ///@}
255*0a6a1f1dSLionel Sambuc ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
256f4a2713aSLionel Sambuc const CallExpr *CE,
257*0a6a1f1dSLionel Sambuc const OwnershipAttr* Att) const;
MallocMemAux(CheckerContext & C,const CallExpr * CE,const Expr * SizeEx,SVal Init,ProgramStateRef State,AllocationFamily Family=AF_Malloc)258f4a2713aSLionel Sambuc static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
259f4a2713aSLionel Sambuc const Expr *SizeEx, SVal Init,
260f4a2713aSLionel Sambuc ProgramStateRef State,
261f4a2713aSLionel Sambuc AllocationFamily Family = AF_Malloc) {
262f4a2713aSLionel Sambuc return MallocMemAux(C, CE,
263f4a2713aSLionel Sambuc State->getSVal(SizeEx, C.getLocationContext()),
264f4a2713aSLionel Sambuc Init, State, Family);
265f4a2713aSLionel Sambuc }
266f4a2713aSLionel Sambuc
267f4a2713aSLionel Sambuc static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
268f4a2713aSLionel Sambuc SVal SizeEx, SVal Init,
269f4a2713aSLionel Sambuc ProgramStateRef State,
270f4a2713aSLionel Sambuc AllocationFamily Family = AF_Malloc);
271f4a2713aSLionel Sambuc
272*0a6a1f1dSLionel Sambuc // Check if this malloc() for special flags. At present that means M_ZERO or
273*0a6a1f1dSLionel Sambuc // __GFP_ZERO (in which case, treat it like calloc).
274*0a6a1f1dSLionel Sambuc llvm::Optional<ProgramStateRef>
275*0a6a1f1dSLionel Sambuc performKernelMalloc(const CallExpr *CE, CheckerContext &C,
276*0a6a1f1dSLionel Sambuc const ProgramStateRef &State) const;
277*0a6a1f1dSLionel Sambuc
278f4a2713aSLionel Sambuc /// Update the RefState to reflect the new memory allocation.
279f4a2713aSLionel Sambuc static ProgramStateRef
280f4a2713aSLionel Sambuc MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
281f4a2713aSLionel Sambuc AllocationFamily Family = AF_Malloc);
282f4a2713aSLionel Sambuc
283f4a2713aSLionel Sambuc ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
284f4a2713aSLionel Sambuc const OwnershipAttr* Att) const;
285f4a2713aSLionel Sambuc ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
286f4a2713aSLionel Sambuc ProgramStateRef state, unsigned Num,
287f4a2713aSLionel Sambuc bool Hold,
288f4a2713aSLionel Sambuc bool &ReleasedAllocated,
289f4a2713aSLionel Sambuc bool ReturnsNullOnFailure = false) const;
290f4a2713aSLionel Sambuc ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
291f4a2713aSLionel Sambuc const Expr *ParentExpr,
292f4a2713aSLionel Sambuc ProgramStateRef State,
293f4a2713aSLionel Sambuc bool Hold,
294f4a2713aSLionel Sambuc bool &ReleasedAllocated,
295f4a2713aSLionel Sambuc bool ReturnsNullOnFailure = false) const;
296f4a2713aSLionel Sambuc
297f4a2713aSLionel Sambuc ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
298f4a2713aSLionel Sambuc bool FreesMemOnFailure) const;
299f4a2713aSLionel Sambuc static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE);
300f4a2713aSLionel Sambuc
301f4a2713aSLionel Sambuc ///\brief Check if the memory associated with this symbol was released.
302f4a2713aSLionel Sambuc bool isReleased(SymbolRef Sym, CheckerContext &C) const;
303f4a2713aSLionel Sambuc
304f4a2713aSLionel Sambuc bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
305f4a2713aSLionel Sambuc
306*0a6a1f1dSLionel Sambuc bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
307*0a6a1f1dSLionel Sambuc
308f4a2713aSLionel Sambuc /// Check if the function is known free memory, or if it is
309f4a2713aSLionel Sambuc /// "interesting" and should be modeled explicitly.
310f4a2713aSLionel Sambuc ///
311f4a2713aSLionel Sambuc /// \param [out] EscapingSymbol A function might not free memory in general,
312f4a2713aSLionel Sambuc /// but could be known to free a particular symbol. In this case, false is
313f4a2713aSLionel Sambuc /// returned and the single escaping symbol is returned through the out
314f4a2713aSLionel Sambuc /// parameter.
315f4a2713aSLionel Sambuc ///
316f4a2713aSLionel Sambuc /// We assume that pointers do not escape through calls to system functions
317f4a2713aSLionel Sambuc /// not handled by this checker.
318f4a2713aSLionel Sambuc bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
319f4a2713aSLionel Sambuc ProgramStateRef State,
320f4a2713aSLionel Sambuc SymbolRef &EscapingSymbol) const;
321f4a2713aSLionel Sambuc
322f4a2713aSLionel Sambuc // Implementation of the checkPointerEscape callabcks.
323f4a2713aSLionel Sambuc ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
324f4a2713aSLionel Sambuc const InvalidatedSymbols &Escaped,
325f4a2713aSLionel Sambuc const CallEvent *Call,
326f4a2713aSLionel Sambuc PointerEscapeKind Kind,
327f4a2713aSLionel Sambuc bool(*CheckRefState)(const RefState*)) const;
328f4a2713aSLionel Sambuc
329f4a2713aSLionel Sambuc ///@{
330f4a2713aSLionel Sambuc /// Tells if a given family/call/symbol is tracked by the current checker.
331*0a6a1f1dSLionel Sambuc /// Sets CheckKind to the kind of the checker responsible for this
332*0a6a1f1dSLionel Sambuc /// family/call/symbol.
333*0a6a1f1dSLionel Sambuc Optional<CheckKind> getCheckIfTracked(AllocationFamily Family) const;
334*0a6a1f1dSLionel Sambuc Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
335f4a2713aSLionel Sambuc const Stmt *AllocDeallocStmt) const;
336*0a6a1f1dSLionel Sambuc Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const;
337f4a2713aSLionel Sambuc ///@}
338f4a2713aSLionel Sambuc static bool SummarizeValue(raw_ostream &os, SVal V);
339f4a2713aSLionel Sambuc static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
340f4a2713aSLionel Sambuc void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
341f4a2713aSLionel Sambuc const Expr *DeallocExpr) const;
342f4a2713aSLionel Sambuc void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
343f4a2713aSLionel Sambuc const Expr *DeallocExpr, const RefState *RS,
344f4a2713aSLionel Sambuc SymbolRef Sym, bool OwnershipTransferred) const;
345f4a2713aSLionel Sambuc void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
346f4a2713aSLionel Sambuc const Expr *DeallocExpr,
347*0a6a1f1dSLionel Sambuc const Expr *AllocExpr = nullptr) const;
348f4a2713aSLionel Sambuc void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
349f4a2713aSLionel Sambuc SymbolRef Sym) const;
350f4a2713aSLionel Sambuc void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
351f4a2713aSLionel Sambuc SymbolRef Sym, SymbolRef PrevSym) const;
352f4a2713aSLionel Sambuc
353*0a6a1f1dSLionel Sambuc void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
354*0a6a1f1dSLionel Sambuc
355f4a2713aSLionel Sambuc /// Find the location of the allocation for Sym on the path leading to the
356f4a2713aSLionel Sambuc /// exploded node N.
357f4a2713aSLionel Sambuc LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
358f4a2713aSLionel Sambuc CheckerContext &C) const;
359f4a2713aSLionel Sambuc
360f4a2713aSLionel Sambuc void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
361f4a2713aSLionel Sambuc
362f4a2713aSLionel Sambuc /// The bug visitor which allows us to print extra diagnostics along the
363f4a2713aSLionel Sambuc /// BugReport path. For example, showing the allocation site of the leaked
364f4a2713aSLionel Sambuc /// region.
365f4a2713aSLionel Sambuc class MallocBugVisitor : public BugReporterVisitorImpl<MallocBugVisitor> {
366f4a2713aSLionel Sambuc protected:
367f4a2713aSLionel Sambuc enum NotificationMode {
368f4a2713aSLionel Sambuc Normal,
369f4a2713aSLionel Sambuc ReallocationFailed
370f4a2713aSLionel Sambuc };
371f4a2713aSLionel Sambuc
372f4a2713aSLionel Sambuc // The allocated region symbol tracked by the main analysis.
373f4a2713aSLionel Sambuc SymbolRef Sym;
374f4a2713aSLionel Sambuc
375f4a2713aSLionel Sambuc // The mode we are in, i.e. what kind of diagnostics will be emitted.
376f4a2713aSLionel Sambuc NotificationMode Mode;
377f4a2713aSLionel Sambuc
378f4a2713aSLionel Sambuc // A symbol from when the primary region should have been reallocated.
379f4a2713aSLionel Sambuc SymbolRef FailedReallocSymbol;
380f4a2713aSLionel Sambuc
381f4a2713aSLionel Sambuc bool IsLeak;
382f4a2713aSLionel Sambuc
383f4a2713aSLionel Sambuc public:
MallocBugVisitor(SymbolRef S,bool isLeak=false)384f4a2713aSLionel Sambuc MallocBugVisitor(SymbolRef S, bool isLeak = false)
385*0a6a1f1dSLionel Sambuc : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
386f4a2713aSLionel Sambuc
~MallocBugVisitor()387f4a2713aSLionel Sambuc virtual ~MallocBugVisitor() {}
388f4a2713aSLionel Sambuc
Profile(llvm::FoldingSetNodeID & ID) const389*0a6a1f1dSLionel Sambuc void Profile(llvm::FoldingSetNodeID &ID) const override {
390f4a2713aSLionel Sambuc static int X = 0;
391f4a2713aSLionel Sambuc ID.AddPointer(&X);
392f4a2713aSLionel Sambuc ID.AddPointer(Sym);
393f4a2713aSLionel Sambuc }
394f4a2713aSLionel Sambuc
isAllocated(const RefState * S,const RefState * SPrev,const Stmt * Stmt)395f4a2713aSLionel Sambuc inline bool isAllocated(const RefState *S, const RefState *SPrev,
396f4a2713aSLionel Sambuc const Stmt *Stmt) {
397f4a2713aSLionel Sambuc // Did not track -> allocated. Other state (released) -> allocated.
398f4a2713aSLionel Sambuc return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
399f4a2713aSLionel Sambuc (S && S->isAllocated()) && (!SPrev || !SPrev->isAllocated()));
400f4a2713aSLionel Sambuc }
401f4a2713aSLionel Sambuc
isReleased(const RefState * S,const RefState * SPrev,const Stmt * Stmt)402f4a2713aSLionel Sambuc inline bool isReleased(const RefState *S, const RefState *SPrev,
403f4a2713aSLionel Sambuc const Stmt *Stmt) {
404f4a2713aSLionel Sambuc // Did not track -> released. Other state (allocated) -> released.
405f4a2713aSLionel Sambuc return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
406f4a2713aSLionel Sambuc (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
407f4a2713aSLionel Sambuc }
408f4a2713aSLionel Sambuc
isRelinquished(const RefState * S,const RefState * SPrev,const Stmt * Stmt)409f4a2713aSLionel Sambuc inline bool isRelinquished(const RefState *S, const RefState *SPrev,
410f4a2713aSLionel Sambuc const Stmt *Stmt) {
411f4a2713aSLionel Sambuc // Did not track -> relinquished. Other state (allocated) -> relinquished.
412f4a2713aSLionel Sambuc return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
413f4a2713aSLionel Sambuc isa<ObjCPropertyRefExpr>(Stmt)) &&
414f4a2713aSLionel Sambuc (S && S->isRelinquished()) &&
415f4a2713aSLionel Sambuc (!SPrev || !SPrev->isRelinquished()));
416f4a2713aSLionel Sambuc }
417f4a2713aSLionel Sambuc
isReallocFailedCheck(const RefState * S,const RefState * SPrev,const Stmt * Stmt)418f4a2713aSLionel Sambuc inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
419f4a2713aSLionel Sambuc const Stmt *Stmt) {
420f4a2713aSLionel Sambuc // If the expression is not a call, and the state change is
421f4a2713aSLionel Sambuc // released -> allocated, it must be the realloc return value
422f4a2713aSLionel Sambuc // check. If we have to handle more cases here, it might be cleaner just
423f4a2713aSLionel Sambuc // to track this extra bit in the state itself.
424f4a2713aSLionel Sambuc return ((!Stmt || !isa<CallExpr>(Stmt)) &&
425f4a2713aSLionel Sambuc (S && S->isAllocated()) && (SPrev && !SPrev->isAllocated()));
426f4a2713aSLionel Sambuc }
427f4a2713aSLionel Sambuc
428f4a2713aSLionel Sambuc PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
429f4a2713aSLionel Sambuc const ExplodedNode *PrevN,
430f4a2713aSLionel Sambuc BugReporterContext &BRC,
431*0a6a1f1dSLionel Sambuc BugReport &BR) override;
432f4a2713aSLionel Sambuc
433*0a6a1f1dSLionel Sambuc std::unique_ptr<PathDiagnosticPiece>
getEndPath(BugReporterContext & BRC,const ExplodedNode * EndPathNode,BugReport & BR)434*0a6a1f1dSLionel Sambuc getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
435*0a6a1f1dSLionel Sambuc BugReport &BR) override {
436f4a2713aSLionel Sambuc if (!IsLeak)
437*0a6a1f1dSLionel Sambuc return nullptr;
438f4a2713aSLionel Sambuc
439f4a2713aSLionel Sambuc PathDiagnosticLocation L =
440f4a2713aSLionel Sambuc PathDiagnosticLocation::createEndOfPath(EndPathNode,
441f4a2713aSLionel Sambuc BRC.getSourceManager());
442f4a2713aSLionel Sambuc // Do not add the statement itself as a range in case of leak.
443*0a6a1f1dSLionel Sambuc return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
444*0a6a1f1dSLionel Sambuc false);
445f4a2713aSLionel Sambuc }
446f4a2713aSLionel Sambuc
447f4a2713aSLionel Sambuc private:
448f4a2713aSLionel Sambuc class StackHintGeneratorForReallocationFailed
449f4a2713aSLionel Sambuc : public StackHintGeneratorForSymbol {
450f4a2713aSLionel Sambuc public:
StackHintGeneratorForReallocationFailed(SymbolRef S,StringRef M)451f4a2713aSLionel Sambuc StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
452f4a2713aSLionel Sambuc : StackHintGeneratorForSymbol(S, M) {}
453f4a2713aSLionel Sambuc
getMessageForArg(const Expr * ArgE,unsigned ArgIndex)454*0a6a1f1dSLionel Sambuc std::string getMessageForArg(const Expr *ArgE,
455*0a6a1f1dSLionel Sambuc unsigned ArgIndex) override {
456f4a2713aSLionel Sambuc // Printed parameters start at 1, not 0.
457f4a2713aSLionel Sambuc ++ArgIndex;
458f4a2713aSLionel Sambuc
459f4a2713aSLionel Sambuc SmallString<200> buf;
460f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
461f4a2713aSLionel Sambuc
462f4a2713aSLionel Sambuc os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
463f4a2713aSLionel Sambuc << " parameter failed";
464f4a2713aSLionel Sambuc
465f4a2713aSLionel Sambuc return os.str();
466f4a2713aSLionel Sambuc }
467f4a2713aSLionel Sambuc
getMessageForReturn(const CallExpr * CallExpr)468*0a6a1f1dSLionel Sambuc std::string getMessageForReturn(const CallExpr *CallExpr) override {
469f4a2713aSLionel Sambuc return "Reallocation of returned value failed";
470f4a2713aSLionel Sambuc }
471f4a2713aSLionel Sambuc };
472f4a2713aSLionel Sambuc };
473f4a2713aSLionel Sambuc };
474f4a2713aSLionel Sambuc } // end anonymous namespace
475f4a2713aSLionel Sambuc
476f4a2713aSLionel Sambuc REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
477f4a2713aSLionel Sambuc REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
478f4a2713aSLionel Sambuc
479f4a2713aSLionel Sambuc // A map from the freed symbol to the symbol representing the return value of
480f4a2713aSLionel Sambuc // the free function.
481f4a2713aSLionel Sambuc REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
482f4a2713aSLionel Sambuc
483f4a2713aSLionel Sambuc namespace {
484f4a2713aSLionel Sambuc class StopTrackingCallback : public SymbolVisitor {
485f4a2713aSLionel Sambuc ProgramStateRef state;
486f4a2713aSLionel Sambuc public:
StopTrackingCallback(ProgramStateRef st)487f4a2713aSLionel Sambuc StopTrackingCallback(ProgramStateRef st) : state(st) {}
getState() const488f4a2713aSLionel Sambuc ProgramStateRef getState() const { return state; }
489f4a2713aSLionel Sambuc
VisitSymbol(SymbolRef sym)490*0a6a1f1dSLionel Sambuc bool VisitSymbol(SymbolRef sym) override {
491f4a2713aSLionel Sambuc state = state->remove<RegionState>(sym);
492f4a2713aSLionel Sambuc return true;
493f4a2713aSLionel Sambuc }
494f4a2713aSLionel Sambuc };
495f4a2713aSLionel Sambuc } // end anonymous namespace
496f4a2713aSLionel Sambuc
initIdentifierInfo(ASTContext & Ctx) const497f4a2713aSLionel Sambuc void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
498f4a2713aSLionel Sambuc if (II_malloc)
499f4a2713aSLionel Sambuc return;
500f4a2713aSLionel Sambuc II_malloc = &Ctx.Idents.get("malloc");
501f4a2713aSLionel Sambuc II_free = &Ctx.Idents.get("free");
502f4a2713aSLionel Sambuc II_realloc = &Ctx.Idents.get("realloc");
503f4a2713aSLionel Sambuc II_reallocf = &Ctx.Idents.get("reallocf");
504f4a2713aSLionel Sambuc II_calloc = &Ctx.Idents.get("calloc");
505f4a2713aSLionel Sambuc II_valloc = &Ctx.Idents.get("valloc");
506f4a2713aSLionel Sambuc II_strdup = &Ctx.Idents.get("strdup");
507f4a2713aSLionel Sambuc II_strndup = &Ctx.Idents.get("strndup");
508*0a6a1f1dSLionel Sambuc II_kmalloc = &Ctx.Idents.get("kmalloc");
509*0a6a1f1dSLionel Sambuc II_if_nameindex = &Ctx.Idents.get("if_nameindex");
510*0a6a1f1dSLionel Sambuc II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
511f4a2713aSLionel Sambuc }
512f4a2713aSLionel Sambuc
isMemFunction(const FunctionDecl * FD,ASTContext & C) const513f4a2713aSLionel Sambuc bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
514*0a6a1f1dSLionel Sambuc if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
515f4a2713aSLionel Sambuc return true;
516f4a2713aSLionel Sambuc
517*0a6a1f1dSLionel Sambuc if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
518f4a2713aSLionel Sambuc return true;
519f4a2713aSLionel Sambuc
520f4a2713aSLionel Sambuc if (isStandardNewDelete(FD, C))
521f4a2713aSLionel Sambuc return true;
522f4a2713aSLionel Sambuc
523f4a2713aSLionel Sambuc return false;
524f4a2713aSLionel Sambuc }
525f4a2713aSLionel Sambuc
isCMemFunction(const FunctionDecl * FD,ASTContext & C,AllocationFamily Family,MemoryOperationKind MemKind) const526*0a6a1f1dSLionel Sambuc bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
527*0a6a1f1dSLionel Sambuc ASTContext &C,
528*0a6a1f1dSLionel Sambuc AllocationFamily Family,
529*0a6a1f1dSLionel Sambuc MemoryOperationKind MemKind) const {
530f4a2713aSLionel Sambuc if (!FD)
531f4a2713aSLionel Sambuc return false;
532f4a2713aSLionel Sambuc
533*0a6a1f1dSLionel Sambuc bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
534*0a6a1f1dSLionel Sambuc MemKind == MemoryOperationKind::MOK_Free);
535*0a6a1f1dSLionel Sambuc bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
536*0a6a1f1dSLionel Sambuc MemKind == MemoryOperationKind::MOK_Allocate);
537f4a2713aSLionel Sambuc
538f4a2713aSLionel Sambuc if (FD->getKind() == Decl::Function) {
539*0a6a1f1dSLionel Sambuc const IdentifierInfo *FunI = FD->getIdentifier();
540f4a2713aSLionel Sambuc initIdentifierInfo(C);
541f4a2713aSLionel Sambuc
542*0a6a1f1dSLionel Sambuc if (Family == AF_Malloc && CheckFree) {
543f4a2713aSLionel Sambuc if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
544f4a2713aSLionel Sambuc return true;
545f4a2713aSLionel Sambuc }
546f4a2713aSLionel Sambuc
547*0a6a1f1dSLionel Sambuc if (Family == AF_Malloc && CheckAlloc) {
548*0a6a1f1dSLionel Sambuc if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
549*0a6a1f1dSLionel Sambuc FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
550*0a6a1f1dSLionel Sambuc FunI == II_strndup || FunI == II_kmalloc)
551f4a2713aSLionel Sambuc return true;
552*0a6a1f1dSLionel Sambuc }
553*0a6a1f1dSLionel Sambuc
554*0a6a1f1dSLionel Sambuc if (Family == AF_IfNameIndex && CheckFree) {
555*0a6a1f1dSLionel Sambuc if (FunI == II_if_freenameindex)
556*0a6a1f1dSLionel Sambuc return true;
557*0a6a1f1dSLionel Sambuc }
558*0a6a1f1dSLionel Sambuc
559*0a6a1f1dSLionel Sambuc if (Family == AF_IfNameIndex && CheckAlloc) {
560*0a6a1f1dSLionel Sambuc if (FunI == II_if_nameindex)
561*0a6a1f1dSLionel Sambuc return true;
562*0a6a1f1dSLionel Sambuc }
563*0a6a1f1dSLionel Sambuc }
564*0a6a1f1dSLionel Sambuc
565*0a6a1f1dSLionel Sambuc if (Family != AF_Malloc)
566*0a6a1f1dSLionel Sambuc return false;
567*0a6a1f1dSLionel Sambuc
568*0a6a1f1dSLionel Sambuc if (ChecksEnabled[CK_MallocOptimistic] && FD->hasAttrs()) {
569*0a6a1f1dSLionel Sambuc for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
570*0a6a1f1dSLionel Sambuc OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
571*0a6a1f1dSLionel Sambuc if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
572*0a6a1f1dSLionel Sambuc if (CheckFree)
573*0a6a1f1dSLionel Sambuc return true;
574*0a6a1f1dSLionel Sambuc } else if (OwnKind == OwnershipAttr::Returns) {
575*0a6a1f1dSLionel Sambuc if (CheckAlloc)
576*0a6a1f1dSLionel Sambuc return true;
577*0a6a1f1dSLionel Sambuc }
578*0a6a1f1dSLionel Sambuc }
579*0a6a1f1dSLionel Sambuc }
580*0a6a1f1dSLionel Sambuc
581f4a2713aSLionel Sambuc return false;
582f4a2713aSLionel Sambuc }
583f4a2713aSLionel Sambuc
584f4a2713aSLionel Sambuc // Tells if the callee is one of the following:
585f4a2713aSLionel Sambuc // 1) A global non-placement new/delete operator function.
586f4a2713aSLionel Sambuc // 2) A global placement operator function with the single placement argument
587f4a2713aSLionel Sambuc // of type std::nothrow_t.
isStandardNewDelete(const FunctionDecl * FD,ASTContext & C) const588f4a2713aSLionel Sambuc bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
589f4a2713aSLionel Sambuc ASTContext &C) const {
590f4a2713aSLionel Sambuc if (!FD)
591f4a2713aSLionel Sambuc return false;
592f4a2713aSLionel Sambuc
593f4a2713aSLionel Sambuc OverloadedOperatorKind Kind = FD->getOverloadedOperator();
594f4a2713aSLionel Sambuc if (Kind != OO_New && Kind != OO_Array_New &&
595f4a2713aSLionel Sambuc Kind != OO_Delete && Kind != OO_Array_Delete)
596f4a2713aSLionel Sambuc return false;
597f4a2713aSLionel Sambuc
598f4a2713aSLionel Sambuc // Skip all operator new/delete methods.
599f4a2713aSLionel Sambuc if (isa<CXXMethodDecl>(FD))
600f4a2713aSLionel Sambuc return false;
601f4a2713aSLionel Sambuc
602f4a2713aSLionel Sambuc // Return true if tested operator is a standard placement nothrow operator.
603f4a2713aSLionel Sambuc if (FD->getNumParams() == 2) {
604f4a2713aSLionel Sambuc QualType T = FD->getParamDecl(1)->getType();
605f4a2713aSLionel Sambuc if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
606f4a2713aSLionel Sambuc return II->getName().equals("nothrow_t");
607f4a2713aSLionel Sambuc }
608f4a2713aSLionel Sambuc
609f4a2713aSLionel Sambuc // Skip placement operators.
610f4a2713aSLionel Sambuc if (FD->getNumParams() != 1 || FD->isVariadic())
611f4a2713aSLionel Sambuc return false;
612f4a2713aSLionel Sambuc
613f4a2713aSLionel Sambuc // One of the standard new/new[]/delete/delete[] non-placement operators.
614f4a2713aSLionel Sambuc return true;
615f4a2713aSLionel Sambuc }
616f4a2713aSLionel Sambuc
performKernelMalloc(const CallExpr * CE,CheckerContext & C,const ProgramStateRef & State) const617*0a6a1f1dSLionel Sambuc llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
618*0a6a1f1dSLionel Sambuc const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
619*0a6a1f1dSLionel Sambuc // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
620*0a6a1f1dSLionel Sambuc //
621*0a6a1f1dSLionel Sambuc // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
622*0a6a1f1dSLionel Sambuc //
623*0a6a1f1dSLionel Sambuc // One of the possible flags is M_ZERO, which means 'give me back an
624*0a6a1f1dSLionel Sambuc // allocation which is already zeroed', like calloc.
625*0a6a1f1dSLionel Sambuc
626*0a6a1f1dSLionel Sambuc // 2-argument kmalloc(), as used in the Linux kernel:
627*0a6a1f1dSLionel Sambuc //
628*0a6a1f1dSLionel Sambuc // void *kmalloc(size_t size, gfp_t flags);
629*0a6a1f1dSLionel Sambuc //
630*0a6a1f1dSLionel Sambuc // Has the similar flag value __GFP_ZERO.
631*0a6a1f1dSLionel Sambuc
632*0a6a1f1dSLionel Sambuc // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
633*0a6a1f1dSLionel Sambuc // code could be shared.
634*0a6a1f1dSLionel Sambuc
635*0a6a1f1dSLionel Sambuc ASTContext &Ctx = C.getASTContext();
636*0a6a1f1dSLionel Sambuc llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
637*0a6a1f1dSLionel Sambuc
638*0a6a1f1dSLionel Sambuc if (!KernelZeroFlagVal.hasValue()) {
639*0a6a1f1dSLionel Sambuc if (OS == llvm::Triple::FreeBSD)
640*0a6a1f1dSLionel Sambuc KernelZeroFlagVal = 0x0100;
641*0a6a1f1dSLionel Sambuc else if (OS == llvm::Triple::NetBSD)
642*0a6a1f1dSLionel Sambuc KernelZeroFlagVal = 0x0002;
643*0a6a1f1dSLionel Sambuc else if (OS == llvm::Triple::OpenBSD)
644*0a6a1f1dSLionel Sambuc KernelZeroFlagVal = 0x0008;
645*0a6a1f1dSLionel Sambuc else if (OS == llvm::Triple::Linux)
646*0a6a1f1dSLionel Sambuc // __GFP_ZERO
647*0a6a1f1dSLionel Sambuc KernelZeroFlagVal = 0x8000;
648*0a6a1f1dSLionel Sambuc else
649*0a6a1f1dSLionel Sambuc // FIXME: We need a more general way of getting the M_ZERO value.
650*0a6a1f1dSLionel Sambuc // See also: O_CREAT in UnixAPIChecker.cpp.
651*0a6a1f1dSLionel Sambuc
652*0a6a1f1dSLionel Sambuc // Fall back to normal malloc behavior on platforms where we don't
653*0a6a1f1dSLionel Sambuc // know M_ZERO.
654*0a6a1f1dSLionel Sambuc return None;
655*0a6a1f1dSLionel Sambuc }
656*0a6a1f1dSLionel Sambuc
657*0a6a1f1dSLionel Sambuc // We treat the last argument as the flags argument, and callers fall-back to
658*0a6a1f1dSLionel Sambuc // normal malloc on a None return. This works for the FreeBSD kernel malloc
659*0a6a1f1dSLionel Sambuc // as well as Linux kmalloc.
660*0a6a1f1dSLionel Sambuc if (CE->getNumArgs() < 2)
661*0a6a1f1dSLionel Sambuc return None;
662*0a6a1f1dSLionel Sambuc
663*0a6a1f1dSLionel Sambuc const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
664*0a6a1f1dSLionel Sambuc const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
665*0a6a1f1dSLionel Sambuc if (!V.getAs<NonLoc>()) {
666*0a6a1f1dSLionel Sambuc // The case where 'V' can be a location can only be due to a bad header,
667*0a6a1f1dSLionel Sambuc // so in this case bail out.
668*0a6a1f1dSLionel Sambuc return None;
669*0a6a1f1dSLionel Sambuc }
670*0a6a1f1dSLionel Sambuc
671*0a6a1f1dSLionel Sambuc NonLoc Flags = V.castAs<NonLoc>();
672*0a6a1f1dSLionel Sambuc NonLoc ZeroFlag = C.getSValBuilder()
673*0a6a1f1dSLionel Sambuc .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
674*0a6a1f1dSLionel Sambuc .castAs<NonLoc>();
675*0a6a1f1dSLionel Sambuc SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
676*0a6a1f1dSLionel Sambuc Flags, ZeroFlag,
677*0a6a1f1dSLionel Sambuc FlagsEx->getType());
678*0a6a1f1dSLionel Sambuc if (MaskedFlagsUC.isUnknownOrUndef())
679*0a6a1f1dSLionel Sambuc return None;
680*0a6a1f1dSLionel Sambuc DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
681*0a6a1f1dSLionel Sambuc
682*0a6a1f1dSLionel Sambuc // Check if maskedFlags is non-zero.
683*0a6a1f1dSLionel Sambuc ProgramStateRef TrueState, FalseState;
684*0a6a1f1dSLionel Sambuc std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
685*0a6a1f1dSLionel Sambuc
686*0a6a1f1dSLionel Sambuc // If M_ZERO is set, treat this like calloc (initialized).
687*0a6a1f1dSLionel Sambuc if (TrueState && !FalseState) {
688*0a6a1f1dSLionel Sambuc SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
689*0a6a1f1dSLionel Sambuc return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
690*0a6a1f1dSLionel Sambuc }
691*0a6a1f1dSLionel Sambuc
692*0a6a1f1dSLionel Sambuc return None;
693*0a6a1f1dSLionel Sambuc }
694*0a6a1f1dSLionel Sambuc
checkPostStmt(const CallExpr * CE,CheckerContext & C) const695f4a2713aSLionel Sambuc void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
696f4a2713aSLionel Sambuc if (C.wasInlined)
697f4a2713aSLionel Sambuc return;
698f4a2713aSLionel Sambuc
699f4a2713aSLionel Sambuc const FunctionDecl *FD = C.getCalleeDecl(CE);
700f4a2713aSLionel Sambuc if (!FD)
701f4a2713aSLionel Sambuc return;
702f4a2713aSLionel Sambuc
703f4a2713aSLionel Sambuc ProgramStateRef State = C.getState();
704f4a2713aSLionel Sambuc bool ReleasedAllocatedMemory = false;
705f4a2713aSLionel Sambuc
706f4a2713aSLionel Sambuc if (FD->getKind() == Decl::Function) {
707f4a2713aSLionel Sambuc initIdentifierInfo(C.getASTContext());
708f4a2713aSLionel Sambuc IdentifierInfo *FunI = FD->getIdentifier();
709f4a2713aSLionel Sambuc
710*0a6a1f1dSLionel Sambuc if (FunI == II_malloc) {
711*0a6a1f1dSLionel Sambuc if (CE->getNumArgs() < 1)
712*0a6a1f1dSLionel Sambuc return;
713*0a6a1f1dSLionel Sambuc if (CE->getNumArgs() < 3) {
714*0a6a1f1dSLionel Sambuc State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
715*0a6a1f1dSLionel Sambuc } else if (CE->getNumArgs() == 3) {
716*0a6a1f1dSLionel Sambuc llvm::Optional<ProgramStateRef> MaybeState =
717*0a6a1f1dSLionel Sambuc performKernelMalloc(CE, C, State);
718*0a6a1f1dSLionel Sambuc if (MaybeState.hasValue())
719*0a6a1f1dSLionel Sambuc State = MaybeState.getValue();
720*0a6a1f1dSLionel Sambuc else
721*0a6a1f1dSLionel Sambuc State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
722*0a6a1f1dSLionel Sambuc }
723*0a6a1f1dSLionel Sambuc } else if (FunI == II_kmalloc) {
724*0a6a1f1dSLionel Sambuc llvm::Optional<ProgramStateRef> MaybeState =
725*0a6a1f1dSLionel Sambuc performKernelMalloc(CE, C, State);
726*0a6a1f1dSLionel Sambuc if (MaybeState.hasValue())
727*0a6a1f1dSLionel Sambuc State = MaybeState.getValue();
728*0a6a1f1dSLionel Sambuc else
729*0a6a1f1dSLionel Sambuc State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
730*0a6a1f1dSLionel Sambuc } else if (FunI == II_valloc) {
731f4a2713aSLionel Sambuc if (CE->getNumArgs() < 1)
732f4a2713aSLionel Sambuc return;
733f4a2713aSLionel Sambuc State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
734f4a2713aSLionel Sambuc } else if (FunI == II_realloc) {
735f4a2713aSLionel Sambuc State = ReallocMem(C, CE, false);
736f4a2713aSLionel Sambuc } else if (FunI == II_reallocf) {
737f4a2713aSLionel Sambuc State = ReallocMem(C, CE, true);
738f4a2713aSLionel Sambuc } else if (FunI == II_calloc) {
739f4a2713aSLionel Sambuc State = CallocMem(C, CE);
740f4a2713aSLionel Sambuc } else if (FunI == II_free) {
741f4a2713aSLionel Sambuc State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
742f4a2713aSLionel Sambuc } else if (FunI == II_strdup) {
743f4a2713aSLionel Sambuc State = MallocUpdateRefState(C, CE, State);
744f4a2713aSLionel Sambuc } else if (FunI == II_strndup) {
745f4a2713aSLionel Sambuc State = MallocUpdateRefState(C, CE, State);
746f4a2713aSLionel Sambuc }
747f4a2713aSLionel Sambuc else if (isStandardNewDelete(FD, C.getASTContext())) {
748f4a2713aSLionel Sambuc // Process direct calls to operator new/new[]/delete/delete[] functions
749f4a2713aSLionel Sambuc // as distinct from new/new[]/delete/delete[] expressions that are
750f4a2713aSLionel Sambuc // processed by the checkPostStmt callbacks for CXXNewExpr and
751f4a2713aSLionel Sambuc // CXXDeleteExpr.
752f4a2713aSLionel Sambuc OverloadedOperatorKind K = FD->getOverloadedOperator();
753f4a2713aSLionel Sambuc if (K == OO_New)
754f4a2713aSLionel Sambuc State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
755f4a2713aSLionel Sambuc AF_CXXNew);
756f4a2713aSLionel Sambuc else if (K == OO_Array_New)
757f4a2713aSLionel Sambuc State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
758f4a2713aSLionel Sambuc AF_CXXNewArray);
759f4a2713aSLionel Sambuc else if (K == OO_Delete || K == OO_Array_Delete)
760f4a2713aSLionel Sambuc State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
761f4a2713aSLionel Sambuc else
762f4a2713aSLionel Sambuc llvm_unreachable("not a new/delete operator");
763*0a6a1f1dSLionel Sambuc } else if (FunI == II_if_nameindex) {
764*0a6a1f1dSLionel Sambuc // Should we model this differently? We can allocate a fixed number of
765*0a6a1f1dSLionel Sambuc // elements with zeros in the last one.
766*0a6a1f1dSLionel Sambuc State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
767*0a6a1f1dSLionel Sambuc AF_IfNameIndex);
768*0a6a1f1dSLionel Sambuc } else if (FunI == II_if_freenameindex) {
769*0a6a1f1dSLionel Sambuc State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
770f4a2713aSLionel Sambuc }
771f4a2713aSLionel Sambuc }
772f4a2713aSLionel Sambuc
773*0a6a1f1dSLionel Sambuc if (ChecksEnabled[CK_MallocOptimistic] ||
774*0a6a1f1dSLionel Sambuc ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
775f4a2713aSLionel Sambuc // Check all the attributes, if there are any.
776f4a2713aSLionel Sambuc // There can be multiple of these attributes.
777f4a2713aSLionel Sambuc if (FD->hasAttrs())
778*0a6a1f1dSLionel Sambuc for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
779*0a6a1f1dSLionel Sambuc switch (I->getOwnKind()) {
780f4a2713aSLionel Sambuc case OwnershipAttr::Returns:
781*0a6a1f1dSLionel Sambuc State = MallocMemReturnsAttr(C, CE, I);
782f4a2713aSLionel Sambuc break;
783f4a2713aSLionel Sambuc case OwnershipAttr::Takes:
784f4a2713aSLionel Sambuc case OwnershipAttr::Holds:
785*0a6a1f1dSLionel Sambuc State = FreeMemAttr(C, CE, I);
786f4a2713aSLionel Sambuc break;
787f4a2713aSLionel Sambuc }
788f4a2713aSLionel Sambuc }
789f4a2713aSLionel Sambuc }
790f4a2713aSLionel Sambuc C.addTransition(State);
791f4a2713aSLionel Sambuc }
792f4a2713aSLionel Sambuc
getDeepPointeeType(QualType T)793*0a6a1f1dSLionel Sambuc static QualType getDeepPointeeType(QualType T) {
794*0a6a1f1dSLionel Sambuc QualType Result = T, PointeeType = T->getPointeeType();
795*0a6a1f1dSLionel Sambuc while (!PointeeType.isNull()) {
796*0a6a1f1dSLionel Sambuc Result = PointeeType;
797*0a6a1f1dSLionel Sambuc PointeeType = PointeeType->getPointeeType();
798*0a6a1f1dSLionel Sambuc }
799*0a6a1f1dSLionel Sambuc return Result;
800*0a6a1f1dSLionel Sambuc }
801*0a6a1f1dSLionel Sambuc
treatUnusedNewEscaped(const CXXNewExpr * NE)802*0a6a1f1dSLionel Sambuc static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
803*0a6a1f1dSLionel Sambuc
804*0a6a1f1dSLionel Sambuc const CXXConstructExpr *ConstructE = NE->getConstructExpr();
805*0a6a1f1dSLionel Sambuc if (!ConstructE)
806*0a6a1f1dSLionel Sambuc return false;
807*0a6a1f1dSLionel Sambuc
808*0a6a1f1dSLionel Sambuc if (!NE->getAllocatedType()->getAsCXXRecordDecl())
809*0a6a1f1dSLionel Sambuc return false;
810*0a6a1f1dSLionel Sambuc
811*0a6a1f1dSLionel Sambuc const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
812*0a6a1f1dSLionel Sambuc
813*0a6a1f1dSLionel Sambuc // Iterate over the constructor parameters.
814*0a6a1f1dSLionel Sambuc for (const auto *CtorParam : CtorD->params()) {
815*0a6a1f1dSLionel Sambuc
816*0a6a1f1dSLionel Sambuc QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
817*0a6a1f1dSLionel Sambuc if (CtorParamPointeeT.isNull())
818*0a6a1f1dSLionel Sambuc continue;
819*0a6a1f1dSLionel Sambuc
820*0a6a1f1dSLionel Sambuc CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
821*0a6a1f1dSLionel Sambuc
822*0a6a1f1dSLionel Sambuc if (CtorParamPointeeT->getAsCXXRecordDecl())
823*0a6a1f1dSLionel Sambuc return true;
824*0a6a1f1dSLionel Sambuc }
825*0a6a1f1dSLionel Sambuc
826*0a6a1f1dSLionel Sambuc return false;
827*0a6a1f1dSLionel Sambuc }
828*0a6a1f1dSLionel Sambuc
checkPostStmt(const CXXNewExpr * NE,CheckerContext & C) const829f4a2713aSLionel Sambuc void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
830f4a2713aSLionel Sambuc CheckerContext &C) const {
831f4a2713aSLionel Sambuc
832f4a2713aSLionel Sambuc if (NE->getNumPlacementArgs())
833f4a2713aSLionel Sambuc for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
834f4a2713aSLionel Sambuc E = NE->placement_arg_end(); I != E; ++I)
835f4a2713aSLionel Sambuc if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
836f4a2713aSLionel Sambuc checkUseAfterFree(Sym, C, *I);
837f4a2713aSLionel Sambuc
838f4a2713aSLionel Sambuc if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
839f4a2713aSLionel Sambuc return;
840f4a2713aSLionel Sambuc
841*0a6a1f1dSLionel Sambuc ParentMap &PM = C.getLocationContext()->getParentMap();
842*0a6a1f1dSLionel Sambuc if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
843*0a6a1f1dSLionel Sambuc return;
844*0a6a1f1dSLionel Sambuc
845f4a2713aSLionel Sambuc ProgramStateRef State = C.getState();
846f4a2713aSLionel Sambuc // The return value from operator new is bound to a specified initialization
847f4a2713aSLionel Sambuc // value (if any) and we don't want to loose this value. So we call
848f4a2713aSLionel Sambuc // MallocUpdateRefState() instead of MallocMemAux() which breakes the
849f4a2713aSLionel Sambuc // existing binding.
850f4a2713aSLionel Sambuc State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
851f4a2713aSLionel Sambuc : AF_CXXNew);
852f4a2713aSLionel Sambuc C.addTransition(State);
853f4a2713aSLionel Sambuc }
854f4a2713aSLionel Sambuc
checkPreStmt(const CXXDeleteExpr * DE,CheckerContext & C) const855f4a2713aSLionel Sambuc void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
856f4a2713aSLionel Sambuc CheckerContext &C) const {
857f4a2713aSLionel Sambuc
858*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_NewDeleteChecker])
859f4a2713aSLionel Sambuc if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
860f4a2713aSLionel Sambuc checkUseAfterFree(Sym, C, DE->getArgument());
861f4a2713aSLionel Sambuc
862f4a2713aSLionel Sambuc if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
863f4a2713aSLionel Sambuc return;
864f4a2713aSLionel Sambuc
865f4a2713aSLionel Sambuc ProgramStateRef State = C.getState();
866f4a2713aSLionel Sambuc bool ReleasedAllocated;
867f4a2713aSLionel Sambuc State = FreeMemAux(C, DE->getArgument(), DE, State,
868f4a2713aSLionel Sambuc /*Hold*/false, ReleasedAllocated);
869f4a2713aSLionel Sambuc
870f4a2713aSLionel Sambuc C.addTransition(State);
871f4a2713aSLionel Sambuc }
872f4a2713aSLionel Sambuc
isKnownDeallocObjCMethodName(const ObjCMethodCall & Call)873f4a2713aSLionel Sambuc static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
874f4a2713aSLionel Sambuc // If the first selector piece is one of the names below, assume that the
875f4a2713aSLionel Sambuc // object takes ownership of the memory, promising to eventually deallocate it
876f4a2713aSLionel Sambuc // with free().
877f4a2713aSLionel Sambuc // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
878f4a2713aSLionel Sambuc // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
879f4a2713aSLionel Sambuc StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
880f4a2713aSLionel Sambuc if (FirstSlot == "dataWithBytesNoCopy" ||
881f4a2713aSLionel Sambuc FirstSlot == "initWithBytesNoCopy" ||
882f4a2713aSLionel Sambuc FirstSlot == "initWithCharactersNoCopy")
883f4a2713aSLionel Sambuc return true;
884f4a2713aSLionel Sambuc
885f4a2713aSLionel Sambuc return false;
886f4a2713aSLionel Sambuc }
887f4a2713aSLionel Sambuc
getFreeWhenDoneArg(const ObjCMethodCall & Call)888f4a2713aSLionel Sambuc static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
889f4a2713aSLionel Sambuc Selector S = Call.getSelector();
890f4a2713aSLionel Sambuc
891f4a2713aSLionel Sambuc // FIXME: We should not rely on fully-constrained symbols being folded.
892f4a2713aSLionel Sambuc for (unsigned i = 1; i < S.getNumArgs(); ++i)
893f4a2713aSLionel Sambuc if (S.getNameForSlot(i).equals("freeWhenDone"))
894f4a2713aSLionel Sambuc return !Call.getArgSVal(i).isZeroConstant();
895f4a2713aSLionel Sambuc
896f4a2713aSLionel Sambuc return None;
897f4a2713aSLionel Sambuc }
898f4a2713aSLionel Sambuc
checkPostObjCMessage(const ObjCMethodCall & Call,CheckerContext & C) const899f4a2713aSLionel Sambuc void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
900f4a2713aSLionel Sambuc CheckerContext &C) const {
901f4a2713aSLionel Sambuc if (C.wasInlined)
902f4a2713aSLionel Sambuc return;
903f4a2713aSLionel Sambuc
904f4a2713aSLionel Sambuc if (!isKnownDeallocObjCMethodName(Call))
905f4a2713aSLionel Sambuc return;
906f4a2713aSLionel Sambuc
907f4a2713aSLionel Sambuc if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
908f4a2713aSLionel Sambuc if (!*FreeWhenDone)
909f4a2713aSLionel Sambuc return;
910f4a2713aSLionel Sambuc
911f4a2713aSLionel Sambuc bool ReleasedAllocatedMemory;
912f4a2713aSLionel Sambuc ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
913f4a2713aSLionel Sambuc Call.getOriginExpr(), C.getState(),
914f4a2713aSLionel Sambuc /*Hold=*/true, ReleasedAllocatedMemory,
915f4a2713aSLionel Sambuc /*RetNullOnFailure=*/true);
916f4a2713aSLionel Sambuc
917f4a2713aSLionel Sambuc C.addTransition(State);
918f4a2713aSLionel Sambuc }
919f4a2713aSLionel Sambuc
920*0a6a1f1dSLionel Sambuc ProgramStateRef
MallocMemReturnsAttr(CheckerContext & C,const CallExpr * CE,const OwnershipAttr * Att) const921*0a6a1f1dSLionel Sambuc MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
922*0a6a1f1dSLionel Sambuc const OwnershipAttr *Att) const {
923*0a6a1f1dSLionel Sambuc if (Att->getModule() != II_malloc)
924*0a6a1f1dSLionel Sambuc return nullptr;
925f4a2713aSLionel Sambuc
926f4a2713aSLionel Sambuc OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
927f4a2713aSLionel Sambuc if (I != E) {
928f4a2713aSLionel Sambuc return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), C.getState());
929f4a2713aSLionel Sambuc }
930f4a2713aSLionel Sambuc return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), C.getState());
931f4a2713aSLionel Sambuc }
932f4a2713aSLionel Sambuc
MallocMemAux(CheckerContext & C,const CallExpr * CE,SVal Size,SVal Init,ProgramStateRef State,AllocationFamily Family)933f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
934f4a2713aSLionel Sambuc const CallExpr *CE,
935f4a2713aSLionel Sambuc SVal Size, SVal Init,
936f4a2713aSLionel Sambuc ProgramStateRef State,
937f4a2713aSLionel Sambuc AllocationFamily Family) {
938f4a2713aSLionel Sambuc
939*0a6a1f1dSLionel Sambuc // We expect the malloc functions to return a pointer.
940*0a6a1f1dSLionel Sambuc if (!Loc::isLocType(CE->getType()))
941*0a6a1f1dSLionel Sambuc return nullptr;
942*0a6a1f1dSLionel Sambuc
943f4a2713aSLionel Sambuc // Bind the return value to the symbolic value from the heap region.
944f4a2713aSLionel Sambuc // TODO: We could rewrite post visit to eval call; 'malloc' does not have
945f4a2713aSLionel Sambuc // side effects other than what we model here.
946f4a2713aSLionel Sambuc unsigned Count = C.blockCount();
947f4a2713aSLionel Sambuc SValBuilder &svalBuilder = C.getSValBuilder();
948f4a2713aSLionel Sambuc const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
949f4a2713aSLionel Sambuc DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
950f4a2713aSLionel Sambuc .castAs<DefinedSVal>();
951f4a2713aSLionel Sambuc State = State->BindExpr(CE, C.getLocationContext(), RetVal);
952f4a2713aSLionel Sambuc
953f4a2713aSLionel Sambuc // Fill the region with the initialization value.
954f4a2713aSLionel Sambuc State = State->bindDefault(RetVal, Init);
955f4a2713aSLionel Sambuc
956f4a2713aSLionel Sambuc // Set the region's extent equal to the Size parameter.
957f4a2713aSLionel Sambuc const SymbolicRegion *R =
958f4a2713aSLionel Sambuc dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
959f4a2713aSLionel Sambuc if (!R)
960*0a6a1f1dSLionel Sambuc return nullptr;
961f4a2713aSLionel Sambuc if (Optional<DefinedOrUnknownSVal> DefinedSize =
962f4a2713aSLionel Sambuc Size.getAs<DefinedOrUnknownSVal>()) {
963f4a2713aSLionel Sambuc SValBuilder &svalBuilder = C.getSValBuilder();
964f4a2713aSLionel Sambuc DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
965f4a2713aSLionel Sambuc DefinedOrUnknownSVal extentMatchesSize =
966f4a2713aSLionel Sambuc svalBuilder.evalEQ(State, Extent, *DefinedSize);
967f4a2713aSLionel Sambuc
968f4a2713aSLionel Sambuc State = State->assume(extentMatchesSize, true);
969f4a2713aSLionel Sambuc assert(State);
970f4a2713aSLionel Sambuc }
971f4a2713aSLionel Sambuc
972f4a2713aSLionel Sambuc return MallocUpdateRefState(C, CE, State, Family);
973f4a2713aSLionel Sambuc }
974f4a2713aSLionel Sambuc
MallocUpdateRefState(CheckerContext & C,const Expr * E,ProgramStateRef State,AllocationFamily Family)975f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
976f4a2713aSLionel Sambuc const Expr *E,
977f4a2713aSLionel Sambuc ProgramStateRef State,
978f4a2713aSLionel Sambuc AllocationFamily Family) {
979f4a2713aSLionel Sambuc // Get the return value.
980f4a2713aSLionel Sambuc SVal retVal = State->getSVal(E, C.getLocationContext());
981f4a2713aSLionel Sambuc
982f4a2713aSLionel Sambuc // We expect the malloc functions to return a pointer.
983f4a2713aSLionel Sambuc if (!retVal.getAs<Loc>())
984*0a6a1f1dSLionel Sambuc return nullptr;
985f4a2713aSLionel Sambuc
986f4a2713aSLionel Sambuc SymbolRef Sym = retVal.getAsLocSymbol();
987f4a2713aSLionel Sambuc assert(Sym);
988f4a2713aSLionel Sambuc
989f4a2713aSLionel Sambuc // Set the symbol's state to Allocated.
990f4a2713aSLionel Sambuc return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
991f4a2713aSLionel Sambuc }
992f4a2713aSLionel Sambuc
FreeMemAttr(CheckerContext & C,const CallExpr * CE,const OwnershipAttr * Att) const993f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
994f4a2713aSLionel Sambuc const CallExpr *CE,
995f4a2713aSLionel Sambuc const OwnershipAttr *Att) const {
996*0a6a1f1dSLionel Sambuc if (Att->getModule() != II_malloc)
997*0a6a1f1dSLionel Sambuc return nullptr;
998f4a2713aSLionel Sambuc
999f4a2713aSLionel Sambuc ProgramStateRef State = C.getState();
1000f4a2713aSLionel Sambuc bool ReleasedAllocated = false;
1001f4a2713aSLionel Sambuc
1002*0a6a1f1dSLionel Sambuc for (const auto &Arg : Att->args()) {
1003*0a6a1f1dSLionel Sambuc ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1004f4a2713aSLionel Sambuc Att->getOwnKind() == OwnershipAttr::Holds,
1005f4a2713aSLionel Sambuc ReleasedAllocated);
1006f4a2713aSLionel Sambuc if (StateI)
1007f4a2713aSLionel Sambuc State = StateI;
1008f4a2713aSLionel Sambuc }
1009f4a2713aSLionel Sambuc return State;
1010f4a2713aSLionel Sambuc }
1011f4a2713aSLionel Sambuc
FreeMemAux(CheckerContext & C,const CallExpr * CE,ProgramStateRef state,unsigned Num,bool Hold,bool & ReleasedAllocated,bool ReturnsNullOnFailure) const1012f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1013f4a2713aSLionel Sambuc const CallExpr *CE,
1014f4a2713aSLionel Sambuc ProgramStateRef state,
1015f4a2713aSLionel Sambuc unsigned Num,
1016f4a2713aSLionel Sambuc bool Hold,
1017f4a2713aSLionel Sambuc bool &ReleasedAllocated,
1018f4a2713aSLionel Sambuc bool ReturnsNullOnFailure) const {
1019f4a2713aSLionel Sambuc if (CE->getNumArgs() < (Num + 1))
1020*0a6a1f1dSLionel Sambuc return nullptr;
1021f4a2713aSLionel Sambuc
1022f4a2713aSLionel Sambuc return FreeMemAux(C, CE->getArg(Num), CE, state, Hold,
1023f4a2713aSLionel Sambuc ReleasedAllocated, ReturnsNullOnFailure);
1024f4a2713aSLionel Sambuc }
1025f4a2713aSLionel Sambuc
1026f4a2713aSLionel Sambuc /// Checks if the previous call to free on the given symbol failed - if free
1027f4a2713aSLionel Sambuc /// failed, returns true. Also, returns the corresponding return value symbol.
didPreviousFreeFail(ProgramStateRef State,SymbolRef Sym,SymbolRef & RetStatusSymbol)1028f4a2713aSLionel Sambuc static bool didPreviousFreeFail(ProgramStateRef State,
1029f4a2713aSLionel Sambuc SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1030f4a2713aSLionel Sambuc const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1031f4a2713aSLionel Sambuc if (Ret) {
1032f4a2713aSLionel Sambuc assert(*Ret && "We should not store the null return symbol");
1033f4a2713aSLionel Sambuc ConstraintManager &CMgr = State->getConstraintManager();
1034f4a2713aSLionel Sambuc ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1035f4a2713aSLionel Sambuc RetStatusSymbol = *Ret;
1036f4a2713aSLionel Sambuc return FreeFailed.isConstrainedTrue();
1037f4a2713aSLionel Sambuc }
1038f4a2713aSLionel Sambuc return false;
1039f4a2713aSLionel Sambuc }
1040f4a2713aSLionel Sambuc
getAllocationFamily(CheckerContext & C,const Stmt * S) const1041f4a2713aSLionel Sambuc AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1042f4a2713aSLionel Sambuc const Stmt *S) const {
1043f4a2713aSLionel Sambuc if (!S)
1044f4a2713aSLionel Sambuc return AF_None;
1045f4a2713aSLionel Sambuc
1046f4a2713aSLionel Sambuc if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1047f4a2713aSLionel Sambuc const FunctionDecl *FD = C.getCalleeDecl(CE);
1048f4a2713aSLionel Sambuc
1049f4a2713aSLionel Sambuc if (!FD)
1050f4a2713aSLionel Sambuc FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1051f4a2713aSLionel Sambuc
1052f4a2713aSLionel Sambuc ASTContext &Ctx = C.getASTContext();
1053f4a2713aSLionel Sambuc
1054*0a6a1f1dSLionel Sambuc if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1055f4a2713aSLionel Sambuc return AF_Malloc;
1056f4a2713aSLionel Sambuc
1057f4a2713aSLionel Sambuc if (isStandardNewDelete(FD, Ctx)) {
1058f4a2713aSLionel Sambuc OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1059f4a2713aSLionel Sambuc if (Kind == OO_New || Kind == OO_Delete)
1060f4a2713aSLionel Sambuc return AF_CXXNew;
1061f4a2713aSLionel Sambuc else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1062f4a2713aSLionel Sambuc return AF_CXXNewArray;
1063f4a2713aSLionel Sambuc }
1064f4a2713aSLionel Sambuc
1065*0a6a1f1dSLionel Sambuc if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1066*0a6a1f1dSLionel Sambuc return AF_IfNameIndex;
1067*0a6a1f1dSLionel Sambuc
1068f4a2713aSLionel Sambuc return AF_None;
1069f4a2713aSLionel Sambuc }
1070f4a2713aSLionel Sambuc
1071f4a2713aSLionel Sambuc if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1072f4a2713aSLionel Sambuc return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1073f4a2713aSLionel Sambuc
1074f4a2713aSLionel Sambuc if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1075f4a2713aSLionel Sambuc return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1076f4a2713aSLionel Sambuc
1077f4a2713aSLionel Sambuc if (isa<ObjCMessageExpr>(S))
1078f4a2713aSLionel Sambuc return AF_Malloc;
1079f4a2713aSLionel Sambuc
1080f4a2713aSLionel Sambuc return AF_None;
1081f4a2713aSLionel Sambuc }
1082f4a2713aSLionel Sambuc
printAllocDeallocName(raw_ostream & os,CheckerContext & C,const Expr * E) const1083f4a2713aSLionel Sambuc bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1084f4a2713aSLionel Sambuc const Expr *E) const {
1085f4a2713aSLionel Sambuc if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1086f4a2713aSLionel Sambuc // FIXME: This doesn't handle indirect calls.
1087f4a2713aSLionel Sambuc const FunctionDecl *FD = CE->getDirectCallee();
1088f4a2713aSLionel Sambuc if (!FD)
1089f4a2713aSLionel Sambuc return false;
1090f4a2713aSLionel Sambuc
1091f4a2713aSLionel Sambuc os << *FD;
1092f4a2713aSLionel Sambuc if (!FD->isOverloadedOperator())
1093f4a2713aSLionel Sambuc os << "()";
1094f4a2713aSLionel Sambuc return true;
1095f4a2713aSLionel Sambuc }
1096f4a2713aSLionel Sambuc
1097f4a2713aSLionel Sambuc if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1098f4a2713aSLionel Sambuc if (Msg->isInstanceMessage())
1099f4a2713aSLionel Sambuc os << "-";
1100f4a2713aSLionel Sambuc else
1101f4a2713aSLionel Sambuc os << "+";
1102*0a6a1f1dSLionel Sambuc Msg->getSelector().print(os);
1103f4a2713aSLionel Sambuc return true;
1104f4a2713aSLionel Sambuc }
1105f4a2713aSLionel Sambuc
1106f4a2713aSLionel Sambuc if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1107f4a2713aSLionel Sambuc os << "'"
1108f4a2713aSLionel Sambuc << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1109f4a2713aSLionel Sambuc << "'";
1110f4a2713aSLionel Sambuc return true;
1111f4a2713aSLionel Sambuc }
1112f4a2713aSLionel Sambuc
1113f4a2713aSLionel Sambuc if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1114f4a2713aSLionel Sambuc os << "'"
1115f4a2713aSLionel Sambuc << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1116f4a2713aSLionel Sambuc << "'";
1117f4a2713aSLionel Sambuc return true;
1118f4a2713aSLionel Sambuc }
1119f4a2713aSLionel Sambuc
1120f4a2713aSLionel Sambuc return false;
1121f4a2713aSLionel Sambuc }
1122f4a2713aSLionel Sambuc
printExpectedAllocName(raw_ostream & os,CheckerContext & C,const Expr * E) const1123f4a2713aSLionel Sambuc void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1124f4a2713aSLionel Sambuc const Expr *E) const {
1125f4a2713aSLionel Sambuc AllocationFamily Family = getAllocationFamily(C, E);
1126f4a2713aSLionel Sambuc
1127f4a2713aSLionel Sambuc switch(Family) {
1128f4a2713aSLionel Sambuc case AF_Malloc: os << "malloc()"; return;
1129f4a2713aSLionel Sambuc case AF_CXXNew: os << "'new'"; return;
1130f4a2713aSLionel Sambuc case AF_CXXNewArray: os << "'new[]'"; return;
1131*0a6a1f1dSLionel Sambuc case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1132f4a2713aSLionel Sambuc case AF_None: llvm_unreachable("not a deallocation expression");
1133f4a2713aSLionel Sambuc }
1134f4a2713aSLionel Sambuc }
1135f4a2713aSLionel Sambuc
printExpectedDeallocName(raw_ostream & os,AllocationFamily Family) const1136f4a2713aSLionel Sambuc void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1137f4a2713aSLionel Sambuc AllocationFamily Family) const {
1138f4a2713aSLionel Sambuc switch(Family) {
1139f4a2713aSLionel Sambuc case AF_Malloc: os << "free()"; return;
1140f4a2713aSLionel Sambuc case AF_CXXNew: os << "'delete'"; return;
1141f4a2713aSLionel Sambuc case AF_CXXNewArray: os << "'delete[]'"; return;
1142*0a6a1f1dSLionel Sambuc case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1143f4a2713aSLionel Sambuc case AF_None: llvm_unreachable("suspicious AF_None argument");
1144f4a2713aSLionel Sambuc }
1145f4a2713aSLionel Sambuc }
1146f4a2713aSLionel Sambuc
FreeMemAux(CheckerContext & C,const Expr * ArgExpr,const Expr * ParentExpr,ProgramStateRef State,bool Hold,bool & ReleasedAllocated,bool ReturnsNullOnFailure) const1147f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1148f4a2713aSLionel Sambuc const Expr *ArgExpr,
1149f4a2713aSLionel Sambuc const Expr *ParentExpr,
1150f4a2713aSLionel Sambuc ProgramStateRef State,
1151f4a2713aSLionel Sambuc bool Hold,
1152f4a2713aSLionel Sambuc bool &ReleasedAllocated,
1153f4a2713aSLionel Sambuc bool ReturnsNullOnFailure) const {
1154f4a2713aSLionel Sambuc
1155f4a2713aSLionel Sambuc SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1156f4a2713aSLionel Sambuc if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1157*0a6a1f1dSLionel Sambuc return nullptr;
1158f4a2713aSLionel Sambuc DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1159f4a2713aSLionel Sambuc
1160f4a2713aSLionel Sambuc // Check for null dereferences.
1161f4a2713aSLionel Sambuc if (!location.getAs<Loc>())
1162*0a6a1f1dSLionel Sambuc return nullptr;
1163f4a2713aSLionel Sambuc
1164f4a2713aSLionel Sambuc // The explicit NULL case, no operation is performed.
1165f4a2713aSLionel Sambuc ProgramStateRef notNullState, nullState;
1166*0a6a1f1dSLionel Sambuc std::tie(notNullState, nullState) = State->assume(location);
1167f4a2713aSLionel Sambuc if (nullState && !notNullState)
1168*0a6a1f1dSLionel Sambuc return nullptr;
1169f4a2713aSLionel Sambuc
1170f4a2713aSLionel Sambuc // Unknown values could easily be okay
1171f4a2713aSLionel Sambuc // Undefined values are handled elsewhere
1172f4a2713aSLionel Sambuc if (ArgVal.isUnknownOrUndef())
1173*0a6a1f1dSLionel Sambuc return nullptr;
1174f4a2713aSLionel Sambuc
1175f4a2713aSLionel Sambuc const MemRegion *R = ArgVal.getAsRegion();
1176f4a2713aSLionel Sambuc
1177f4a2713aSLionel Sambuc // Nonlocs can't be freed, of course.
1178f4a2713aSLionel Sambuc // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1179f4a2713aSLionel Sambuc if (!R) {
1180f4a2713aSLionel Sambuc ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1181*0a6a1f1dSLionel Sambuc return nullptr;
1182f4a2713aSLionel Sambuc }
1183f4a2713aSLionel Sambuc
1184f4a2713aSLionel Sambuc R = R->StripCasts();
1185f4a2713aSLionel Sambuc
1186f4a2713aSLionel Sambuc // Blocks might show up as heap data, but should not be free()d
1187f4a2713aSLionel Sambuc if (isa<BlockDataRegion>(R)) {
1188f4a2713aSLionel Sambuc ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1189*0a6a1f1dSLionel Sambuc return nullptr;
1190f4a2713aSLionel Sambuc }
1191f4a2713aSLionel Sambuc
1192f4a2713aSLionel Sambuc const MemSpaceRegion *MS = R->getMemorySpace();
1193f4a2713aSLionel Sambuc
1194f4a2713aSLionel Sambuc // Parameters, locals, statics, globals, and memory returned by alloca()
1195f4a2713aSLionel Sambuc // shouldn't be freed.
1196f4a2713aSLionel Sambuc if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1197f4a2713aSLionel Sambuc // FIXME: at the time this code was written, malloc() regions were
1198f4a2713aSLionel Sambuc // represented by conjured symbols, which are all in UnknownSpaceRegion.
1199f4a2713aSLionel Sambuc // This means that there isn't actually anything from HeapSpaceRegion
1200f4a2713aSLionel Sambuc // that should be freed, even though we allow it here.
1201f4a2713aSLionel Sambuc // Of course, free() can work on memory allocated outside the current
1202f4a2713aSLionel Sambuc // function, so UnknownSpaceRegion is always a possibility.
1203f4a2713aSLionel Sambuc // False negatives are better than false positives.
1204f4a2713aSLionel Sambuc
1205f4a2713aSLionel Sambuc ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1206*0a6a1f1dSLionel Sambuc return nullptr;
1207f4a2713aSLionel Sambuc }
1208f4a2713aSLionel Sambuc
1209f4a2713aSLionel Sambuc const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1210f4a2713aSLionel Sambuc // Various cases could lead to non-symbol values here.
1211f4a2713aSLionel Sambuc // For now, ignore them.
1212f4a2713aSLionel Sambuc if (!SrBase)
1213*0a6a1f1dSLionel Sambuc return nullptr;
1214f4a2713aSLionel Sambuc
1215f4a2713aSLionel Sambuc SymbolRef SymBase = SrBase->getSymbol();
1216f4a2713aSLionel Sambuc const RefState *RsBase = State->get<RegionState>(SymBase);
1217*0a6a1f1dSLionel Sambuc SymbolRef PreviousRetStatusSymbol = nullptr;
1218f4a2713aSLionel Sambuc
1219f4a2713aSLionel Sambuc if (RsBase) {
1220f4a2713aSLionel Sambuc
1221f4a2713aSLionel Sambuc // Check for double free first.
1222f4a2713aSLionel Sambuc if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1223f4a2713aSLionel Sambuc !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1224f4a2713aSLionel Sambuc ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1225f4a2713aSLionel Sambuc SymBase, PreviousRetStatusSymbol);
1226*0a6a1f1dSLionel Sambuc return nullptr;
1227f4a2713aSLionel Sambuc
1228f4a2713aSLionel Sambuc // If the pointer is allocated or escaped, but we are now trying to free it,
1229f4a2713aSLionel Sambuc // check that the call to free is proper.
1230f4a2713aSLionel Sambuc } else if (RsBase->isAllocated() || RsBase->isEscaped()) {
1231f4a2713aSLionel Sambuc
1232f4a2713aSLionel Sambuc // Check if an expected deallocation function matches the real one.
1233f4a2713aSLionel Sambuc bool DeallocMatchesAlloc =
1234f4a2713aSLionel Sambuc RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1235f4a2713aSLionel Sambuc if (!DeallocMatchesAlloc) {
1236f4a2713aSLionel Sambuc ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1237f4a2713aSLionel Sambuc ParentExpr, RsBase, SymBase, Hold);
1238*0a6a1f1dSLionel Sambuc return nullptr;
1239f4a2713aSLionel Sambuc }
1240f4a2713aSLionel Sambuc
1241f4a2713aSLionel Sambuc // Check if the memory location being freed is the actual location
1242f4a2713aSLionel Sambuc // allocated, or an offset.
1243f4a2713aSLionel Sambuc RegionOffset Offset = R->getAsOffset();
1244f4a2713aSLionel Sambuc if (Offset.isValid() &&
1245f4a2713aSLionel Sambuc !Offset.hasSymbolicOffset() &&
1246f4a2713aSLionel Sambuc Offset.getOffset() != 0) {
1247f4a2713aSLionel Sambuc const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1248f4a2713aSLionel Sambuc ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1249f4a2713aSLionel Sambuc AllocExpr);
1250*0a6a1f1dSLionel Sambuc return nullptr;
1251f4a2713aSLionel Sambuc }
1252f4a2713aSLionel Sambuc }
1253f4a2713aSLionel Sambuc }
1254f4a2713aSLionel Sambuc
1255*0a6a1f1dSLionel Sambuc ReleasedAllocated = (RsBase != nullptr) && RsBase->isAllocated();
1256f4a2713aSLionel Sambuc
1257f4a2713aSLionel Sambuc // Clean out the info on previous call to free return info.
1258f4a2713aSLionel Sambuc State = State->remove<FreeReturnValue>(SymBase);
1259f4a2713aSLionel Sambuc
1260f4a2713aSLionel Sambuc // Keep track of the return value. If it is NULL, we will know that free
1261f4a2713aSLionel Sambuc // failed.
1262f4a2713aSLionel Sambuc if (ReturnsNullOnFailure) {
1263f4a2713aSLionel Sambuc SVal RetVal = C.getSVal(ParentExpr);
1264f4a2713aSLionel Sambuc SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1265f4a2713aSLionel Sambuc if (RetStatusSymbol) {
1266f4a2713aSLionel Sambuc C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1267f4a2713aSLionel Sambuc State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1268f4a2713aSLionel Sambuc }
1269f4a2713aSLionel Sambuc }
1270f4a2713aSLionel Sambuc
1271f4a2713aSLionel Sambuc AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1272f4a2713aSLionel Sambuc : getAllocationFamily(C, ParentExpr);
1273f4a2713aSLionel Sambuc // Normal free.
1274f4a2713aSLionel Sambuc if (Hold)
1275f4a2713aSLionel Sambuc return State->set<RegionState>(SymBase,
1276f4a2713aSLionel Sambuc RefState::getRelinquished(Family,
1277f4a2713aSLionel Sambuc ParentExpr));
1278f4a2713aSLionel Sambuc
1279f4a2713aSLionel Sambuc return State->set<RegionState>(SymBase,
1280f4a2713aSLionel Sambuc RefState::getReleased(Family, ParentExpr));
1281f4a2713aSLionel Sambuc }
1282f4a2713aSLionel Sambuc
1283*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind>
getCheckIfTracked(AllocationFamily Family) const1284*0a6a1f1dSLionel Sambuc MallocChecker::getCheckIfTracked(AllocationFamily Family) const {
1285f4a2713aSLionel Sambuc switch (Family) {
1286*0a6a1f1dSLionel Sambuc case AF_Malloc:
1287*0a6a1f1dSLionel Sambuc case AF_IfNameIndex: {
1288*0a6a1f1dSLionel Sambuc if (ChecksEnabled[CK_MallocOptimistic]) {
1289*0a6a1f1dSLionel Sambuc return CK_MallocOptimistic;
1290*0a6a1f1dSLionel Sambuc } else if (ChecksEnabled[CK_MallocPessimistic]) {
1291*0a6a1f1dSLionel Sambuc return CK_MallocPessimistic;
1292*0a6a1f1dSLionel Sambuc }
1293*0a6a1f1dSLionel Sambuc return Optional<MallocChecker::CheckKind>();
1294f4a2713aSLionel Sambuc }
1295f4a2713aSLionel Sambuc case AF_CXXNew:
1296f4a2713aSLionel Sambuc case AF_CXXNewArray: {
1297*0a6a1f1dSLionel Sambuc if (ChecksEnabled[CK_NewDeleteChecker]) {
1298*0a6a1f1dSLionel Sambuc return CK_NewDeleteChecker;
1299*0a6a1f1dSLionel Sambuc }
1300*0a6a1f1dSLionel Sambuc return Optional<MallocChecker::CheckKind>();
1301f4a2713aSLionel Sambuc }
1302f4a2713aSLionel Sambuc case AF_None: {
1303f4a2713aSLionel Sambuc llvm_unreachable("no family");
1304f4a2713aSLionel Sambuc }
1305f4a2713aSLionel Sambuc }
1306f4a2713aSLionel Sambuc llvm_unreachable("unhandled family");
1307f4a2713aSLionel Sambuc }
1308f4a2713aSLionel Sambuc
1309*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind>
getCheckIfTracked(CheckerContext & C,const Stmt * AllocDeallocStmt) const1310*0a6a1f1dSLionel Sambuc MallocChecker::getCheckIfTracked(CheckerContext &C,
1311f4a2713aSLionel Sambuc const Stmt *AllocDeallocStmt) const {
1312*0a6a1f1dSLionel Sambuc return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt));
1313f4a2713aSLionel Sambuc }
1314f4a2713aSLionel Sambuc
1315*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind>
getCheckIfTracked(CheckerContext & C,SymbolRef Sym) const1316*0a6a1f1dSLionel Sambuc MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym) const {
1317f4a2713aSLionel Sambuc
1318f4a2713aSLionel Sambuc const RefState *RS = C.getState()->get<RegionState>(Sym);
1319f4a2713aSLionel Sambuc assert(RS);
1320*0a6a1f1dSLionel Sambuc return getCheckIfTracked(RS->getAllocationFamily());
1321f4a2713aSLionel Sambuc }
1322f4a2713aSLionel Sambuc
SummarizeValue(raw_ostream & os,SVal V)1323f4a2713aSLionel Sambuc bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1324f4a2713aSLionel Sambuc if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1325f4a2713aSLionel Sambuc os << "an integer (" << IntVal->getValue() << ")";
1326f4a2713aSLionel Sambuc else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1327f4a2713aSLionel Sambuc os << "a constant address (" << ConstAddr->getValue() << ")";
1328f4a2713aSLionel Sambuc else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1329f4a2713aSLionel Sambuc os << "the address of the label '" << Label->getLabel()->getName() << "'";
1330f4a2713aSLionel Sambuc else
1331f4a2713aSLionel Sambuc return false;
1332f4a2713aSLionel Sambuc
1333f4a2713aSLionel Sambuc return true;
1334f4a2713aSLionel Sambuc }
1335f4a2713aSLionel Sambuc
SummarizeRegion(raw_ostream & os,const MemRegion * MR)1336f4a2713aSLionel Sambuc bool MallocChecker::SummarizeRegion(raw_ostream &os,
1337f4a2713aSLionel Sambuc const MemRegion *MR) {
1338f4a2713aSLionel Sambuc switch (MR->getKind()) {
1339f4a2713aSLionel Sambuc case MemRegion::FunctionTextRegionKind: {
1340f4a2713aSLionel Sambuc const NamedDecl *FD = cast<FunctionTextRegion>(MR)->getDecl();
1341f4a2713aSLionel Sambuc if (FD)
1342f4a2713aSLionel Sambuc os << "the address of the function '" << *FD << '\'';
1343f4a2713aSLionel Sambuc else
1344f4a2713aSLionel Sambuc os << "the address of a function";
1345f4a2713aSLionel Sambuc return true;
1346f4a2713aSLionel Sambuc }
1347f4a2713aSLionel Sambuc case MemRegion::BlockTextRegionKind:
1348f4a2713aSLionel Sambuc os << "block text";
1349f4a2713aSLionel Sambuc return true;
1350f4a2713aSLionel Sambuc case MemRegion::BlockDataRegionKind:
1351f4a2713aSLionel Sambuc // FIXME: where the block came from?
1352f4a2713aSLionel Sambuc os << "a block";
1353f4a2713aSLionel Sambuc return true;
1354f4a2713aSLionel Sambuc default: {
1355f4a2713aSLionel Sambuc const MemSpaceRegion *MS = MR->getMemorySpace();
1356f4a2713aSLionel Sambuc
1357f4a2713aSLionel Sambuc if (isa<StackLocalsSpaceRegion>(MS)) {
1358f4a2713aSLionel Sambuc const VarRegion *VR = dyn_cast<VarRegion>(MR);
1359f4a2713aSLionel Sambuc const VarDecl *VD;
1360f4a2713aSLionel Sambuc if (VR)
1361f4a2713aSLionel Sambuc VD = VR->getDecl();
1362f4a2713aSLionel Sambuc else
1363*0a6a1f1dSLionel Sambuc VD = nullptr;
1364f4a2713aSLionel Sambuc
1365f4a2713aSLionel Sambuc if (VD)
1366f4a2713aSLionel Sambuc os << "the address of the local variable '" << VD->getName() << "'";
1367f4a2713aSLionel Sambuc else
1368f4a2713aSLionel Sambuc os << "the address of a local stack variable";
1369f4a2713aSLionel Sambuc return true;
1370f4a2713aSLionel Sambuc }
1371f4a2713aSLionel Sambuc
1372f4a2713aSLionel Sambuc if (isa<StackArgumentsSpaceRegion>(MS)) {
1373f4a2713aSLionel Sambuc const VarRegion *VR = dyn_cast<VarRegion>(MR);
1374f4a2713aSLionel Sambuc const VarDecl *VD;
1375f4a2713aSLionel Sambuc if (VR)
1376f4a2713aSLionel Sambuc VD = VR->getDecl();
1377f4a2713aSLionel Sambuc else
1378*0a6a1f1dSLionel Sambuc VD = nullptr;
1379f4a2713aSLionel Sambuc
1380f4a2713aSLionel Sambuc if (VD)
1381f4a2713aSLionel Sambuc os << "the address of the parameter '" << VD->getName() << "'";
1382f4a2713aSLionel Sambuc else
1383f4a2713aSLionel Sambuc os << "the address of a parameter";
1384f4a2713aSLionel Sambuc return true;
1385f4a2713aSLionel Sambuc }
1386f4a2713aSLionel Sambuc
1387f4a2713aSLionel Sambuc if (isa<GlobalsSpaceRegion>(MS)) {
1388f4a2713aSLionel Sambuc const VarRegion *VR = dyn_cast<VarRegion>(MR);
1389f4a2713aSLionel Sambuc const VarDecl *VD;
1390f4a2713aSLionel Sambuc if (VR)
1391f4a2713aSLionel Sambuc VD = VR->getDecl();
1392f4a2713aSLionel Sambuc else
1393*0a6a1f1dSLionel Sambuc VD = nullptr;
1394f4a2713aSLionel Sambuc
1395f4a2713aSLionel Sambuc if (VD) {
1396f4a2713aSLionel Sambuc if (VD->isStaticLocal())
1397f4a2713aSLionel Sambuc os << "the address of the static variable '" << VD->getName() << "'";
1398f4a2713aSLionel Sambuc else
1399f4a2713aSLionel Sambuc os << "the address of the global variable '" << VD->getName() << "'";
1400f4a2713aSLionel Sambuc } else
1401f4a2713aSLionel Sambuc os << "the address of a global variable";
1402f4a2713aSLionel Sambuc return true;
1403f4a2713aSLionel Sambuc }
1404f4a2713aSLionel Sambuc
1405f4a2713aSLionel Sambuc return false;
1406f4a2713aSLionel Sambuc }
1407f4a2713aSLionel Sambuc }
1408f4a2713aSLionel Sambuc }
1409f4a2713aSLionel Sambuc
ReportBadFree(CheckerContext & C,SVal ArgVal,SourceRange Range,const Expr * DeallocExpr) const1410f4a2713aSLionel Sambuc void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1411f4a2713aSLionel Sambuc SourceRange Range,
1412f4a2713aSLionel Sambuc const Expr *DeallocExpr) const {
1413f4a2713aSLionel Sambuc
1414*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_MallocOptimistic] &&
1415*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_MallocPessimistic] &&
1416*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_NewDeleteChecker])
1417f4a2713aSLionel Sambuc return;
1418f4a2713aSLionel Sambuc
1419*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind =
1420*0a6a1f1dSLionel Sambuc getCheckIfTracked(C, DeallocExpr);
1421*0a6a1f1dSLionel Sambuc if (!CheckKind.hasValue())
1422f4a2713aSLionel Sambuc return;
1423f4a2713aSLionel Sambuc
1424f4a2713aSLionel Sambuc if (ExplodedNode *N = C.generateSink()) {
1425*0a6a1f1dSLionel Sambuc if (!BT_BadFree[*CheckKind])
1426*0a6a1f1dSLionel Sambuc BT_BadFree[*CheckKind].reset(
1427*0a6a1f1dSLionel Sambuc new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1428f4a2713aSLionel Sambuc
1429f4a2713aSLionel Sambuc SmallString<100> buf;
1430f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
1431f4a2713aSLionel Sambuc
1432f4a2713aSLionel Sambuc const MemRegion *MR = ArgVal.getAsRegion();
1433f4a2713aSLionel Sambuc while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1434f4a2713aSLionel Sambuc MR = ER->getSuperRegion();
1435f4a2713aSLionel Sambuc
1436f4a2713aSLionel Sambuc if (MR && isa<AllocaRegion>(MR))
1437f4a2713aSLionel Sambuc os << "Memory allocated by alloca() should not be deallocated";
1438f4a2713aSLionel Sambuc else {
1439f4a2713aSLionel Sambuc os << "Argument to ";
1440f4a2713aSLionel Sambuc if (!printAllocDeallocName(os, C, DeallocExpr))
1441f4a2713aSLionel Sambuc os << "deallocator";
1442f4a2713aSLionel Sambuc
1443f4a2713aSLionel Sambuc os << " is ";
1444f4a2713aSLionel Sambuc bool Summarized = MR ? SummarizeRegion(os, MR)
1445f4a2713aSLionel Sambuc : SummarizeValue(os, ArgVal);
1446f4a2713aSLionel Sambuc if (Summarized)
1447f4a2713aSLionel Sambuc os << ", which is not memory allocated by ";
1448f4a2713aSLionel Sambuc else
1449f4a2713aSLionel Sambuc os << "not memory allocated by ";
1450f4a2713aSLionel Sambuc
1451f4a2713aSLionel Sambuc printExpectedAllocName(os, C, DeallocExpr);
1452f4a2713aSLionel Sambuc }
1453f4a2713aSLionel Sambuc
1454*0a6a1f1dSLionel Sambuc BugReport *R = new BugReport(*BT_BadFree[*CheckKind], os.str(), N);
1455f4a2713aSLionel Sambuc R->markInteresting(MR);
1456f4a2713aSLionel Sambuc R->addRange(Range);
1457f4a2713aSLionel Sambuc C.emitReport(R);
1458f4a2713aSLionel Sambuc }
1459f4a2713aSLionel Sambuc }
1460f4a2713aSLionel Sambuc
ReportMismatchedDealloc(CheckerContext & C,SourceRange Range,const Expr * DeallocExpr,const RefState * RS,SymbolRef Sym,bool OwnershipTransferred) const1461f4a2713aSLionel Sambuc void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1462f4a2713aSLionel Sambuc SourceRange Range,
1463f4a2713aSLionel Sambuc const Expr *DeallocExpr,
1464f4a2713aSLionel Sambuc const RefState *RS,
1465f4a2713aSLionel Sambuc SymbolRef Sym,
1466f4a2713aSLionel Sambuc bool OwnershipTransferred) const {
1467f4a2713aSLionel Sambuc
1468*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1469f4a2713aSLionel Sambuc return;
1470f4a2713aSLionel Sambuc
1471f4a2713aSLionel Sambuc if (ExplodedNode *N = C.generateSink()) {
1472f4a2713aSLionel Sambuc if (!BT_MismatchedDealloc)
1473*0a6a1f1dSLionel Sambuc BT_MismatchedDealloc.reset(
1474*0a6a1f1dSLionel Sambuc new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1475*0a6a1f1dSLionel Sambuc "Bad deallocator", "Memory Error"));
1476f4a2713aSLionel Sambuc
1477f4a2713aSLionel Sambuc SmallString<100> buf;
1478f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
1479f4a2713aSLionel Sambuc
1480f4a2713aSLionel Sambuc const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1481f4a2713aSLionel Sambuc SmallString<20> AllocBuf;
1482f4a2713aSLionel Sambuc llvm::raw_svector_ostream AllocOs(AllocBuf);
1483f4a2713aSLionel Sambuc SmallString<20> DeallocBuf;
1484f4a2713aSLionel Sambuc llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1485f4a2713aSLionel Sambuc
1486f4a2713aSLionel Sambuc if (OwnershipTransferred) {
1487f4a2713aSLionel Sambuc if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1488f4a2713aSLionel Sambuc os << DeallocOs.str() << " cannot";
1489f4a2713aSLionel Sambuc else
1490f4a2713aSLionel Sambuc os << "Cannot";
1491f4a2713aSLionel Sambuc
1492f4a2713aSLionel Sambuc os << " take ownership of memory";
1493f4a2713aSLionel Sambuc
1494f4a2713aSLionel Sambuc if (printAllocDeallocName(AllocOs, C, AllocExpr))
1495f4a2713aSLionel Sambuc os << " allocated by " << AllocOs.str();
1496f4a2713aSLionel Sambuc } else {
1497f4a2713aSLionel Sambuc os << "Memory";
1498f4a2713aSLionel Sambuc if (printAllocDeallocName(AllocOs, C, AllocExpr))
1499f4a2713aSLionel Sambuc os << " allocated by " << AllocOs.str();
1500f4a2713aSLionel Sambuc
1501f4a2713aSLionel Sambuc os << " should be deallocated by ";
1502f4a2713aSLionel Sambuc printExpectedDeallocName(os, RS->getAllocationFamily());
1503f4a2713aSLionel Sambuc
1504f4a2713aSLionel Sambuc if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1505f4a2713aSLionel Sambuc os << ", not " << DeallocOs.str();
1506f4a2713aSLionel Sambuc }
1507f4a2713aSLionel Sambuc
1508f4a2713aSLionel Sambuc BugReport *R = new BugReport(*BT_MismatchedDealloc, os.str(), N);
1509f4a2713aSLionel Sambuc R->markInteresting(Sym);
1510f4a2713aSLionel Sambuc R->addRange(Range);
1511*0a6a1f1dSLionel Sambuc R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1512f4a2713aSLionel Sambuc C.emitReport(R);
1513f4a2713aSLionel Sambuc }
1514f4a2713aSLionel Sambuc }
1515f4a2713aSLionel Sambuc
ReportOffsetFree(CheckerContext & C,SVal ArgVal,SourceRange Range,const Expr * DeallocExpr,const Expr * AllocExpr) const1516f4a2713aSLionel Sambuc void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1517f4a2713aSLionel Sambuc SourceRange Range, const Expr *DeallocExpr,
1518f4a2713aSLionel Sambuc const Expr *AllocExpr) const {
1519f4a2713aSLionel Sambuc
1520*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_MallocOptimistic] &&
1521*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_MallocPessimistic] &&
1522*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_NewDeleteChecker])
1523f4a2713aSLionel Sambuc return;
1524f4a2713aSLionel Sambuc
1525*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind =
1526*0a6a1f1dSLionel Sambuc getCheckIfTracked(C, AllocExpr);
1527*0a6a1f1dSLionel Sambuc if (!CheckKind.hasValue())
1528f4a2713aSLionel Sambuc return;
1529f4a2713aSLionel Sambuc
1530f4a2713aSLionel Sambuc ExplodedNode *N = C.generateSink();
1531*0a6a1f1dSLionel Sambuc if (!N)
1532f4a2713aSLionel Sambuc return;
1533f4a2713aSLionel Sambuc
1534*0a6a1f1dSLionel Sambuc if (!BT_OffsetFree[*CheckKind])
1535*0a6a1f1dSLionel Sambuc BT_OffsetFree[*CheckKind].reset(
1536*0a6a1f1dSLionel Sambuc new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1537f4a2713aSLionel Sambuc
1538f4a2713aSLionel Sambuc SmallString<100> buf;
1539f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
1540f4a2713aSLionel Sambuc SmallString<20> AllocNameBuf;
1541f4a2713aSLionel Sambuc llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1542f4a2713aSLionel Sambuc
1543f4a2713aSLionel Sambuc const MemRegion *MR = ArgVal.getAsRegion();
1544f4a2713aSLionel Sambuc assert(MR && "Only MemRegion based symbols can have offset free errors");
1545f4a2713aSLionel Sambuc
1546f4a2713aSLionel Sambuc RegionOffset Offset = MR->getAsOffset();
1547f4a2713aSLionel Sambuc assert((Offset.isValid() &&
1548f4a2713aSLionel Sambuc !Offset.hasSymbolicOffset() &&
1549f4a2713aSLionel Sambuc Offset.getOffset() != 0) &&
1550f4a2713aSLionel Sambuc "Only symbols with a valid offset can have offset free errors");
1551f4a2713aSLionel Sambuc
1552f4a2713aSLionel Sambuc int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1553f4a2713aSLionel Sambuc
1554f4a2713aSLionel Sambuc os << "Argument to ";
1555f4a2713aSLionel Sambuc if (!printAllocDeallocName(os, C, DeallocExpr))
1556f4a2713aSLionel Sambuc os << "deallocator";
1557f4a2713aSLionel Sambuc os << " is offset by "
1558f4a2713aSLionel Sambuc << offsetBytes
1559f4a2713aSLionel Sambuc << " "
1560f4a2713aSLionel Sambuc << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1561f4a2713aSLionel Sambuc << " from the start of ";
1562f4a2713aSLionel Sambuc if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1563f4a2713aSLionel Sambuc os << "memory allocated by " << AllocNameOs.str();
1564f4a2713aSLionel Sambuc else
1565f4a2713aSLionel Sambuc os << "allocated memory";
1566f4a2713aSLionel Sambuc
1567*0a6a1f1dSLionel Sambuc BugReport *R = new BugReport(*BT_OffsetFree[*CheckKind], os.str(), N);
1568f4a2713aSLionel Sambuc R->markInteresting(MR->getBaseRegion());
1569f4a2713aSLionel Sambuc R->addRange(Range);
1570f4a2713aSLionel Sambuc C.emitReport(R);
1571f4a2713aSLionel Sambuc }
1572f4a2713aSLionel Sambuc
ReportUseAfterFree(CheckerContext & C,SourceRange Range,SymbolRef Sym) const1573f4a2713aSLionel Sambuc void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1574f4a2713aSLionel Sambuc SymbolRef Sym) const {
1575f4a2713aSLionel Sambuc
1576*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_MallocOptimistic] &&
1577*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_MallocPessimistic] &&
1578*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_NewDeleteChecker])
1579f4a2713aSLionel Sambuc return;
1580f4a2713aSLionel Sambuc
1581*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1582*0a6a1f1dSLionel Sambuc if (!CheckKind.hasValue())
1583f4a2713aSLionel Sambuc return;
1584f4a2713aSLionel Sambuc
1585f4a2713aSLionel Sambuc if (ExplodedNode *N = C.generateSink()) {
1586*0a6a1f1dSLionel Sambuc if (!BT_UseFree[*CheckKind])
1587*0a6a1f1dSLionel Sambuc BT_UseFree[*CheckKind].reset(new BugType(
1588*0a6a1f1dSLionel Sambuc CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1589f4a2713aSLionel Sambuc
1590*0a6a1f1dSLionel Sambuc BugReport *R = new BugReport(*BT_UseFree[*CheckKind],
1591f4a2713aSLionel Sambuc "Use of memory after it is freed", N);
1592f4a2713aSLionel Sambuc
1593f4a2713aSLionel Sambuc R->markInteresting(Sym);
1594f4a2713aSLionel Sambuc R->addRange(Range);
1595*0a6a1f1dSLionel Sambuc R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1596f4a2713aSLionel Sambuc C.emitReport(R);
1597f4a2713aSLionel Sambuc }
1598f4a2713aSLionel Sambuc }
1599f4a2713aSLionel Sambuc
ReportDoubleFree(CheckerContext & C,SourceRange Range,bool Released,SymbolRef Sym,SymbolRef PrevSym) const1600f4a2713aSLionel Sambuc void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1601f4a2713aSLionel Sambuc bool Released, SymbolRef Sym,
1602f4a2713aSLionel Sambuc SymbolRef PrevSym) const {
1603f4a2713aSLionel Sambuc
1604*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_MallocOptimistic] &&
1605*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_MallocPessimistic] &&
1606*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_NewDeleteChecker])
1607f4a2713aSLionel Sambuc return;
1608f4a2713aSLionel Sambuc
1609*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1610*0a6a1f1dSLionel Sambuc if (!CheckKind.hasValue())
1611f4a2713aSLionel Sambuc return;
1612f4a2713aSLionel Sambuc
1613f4a2713aSLionel Sambuc if (ExplodedNode *N = C.generateSink()) {
1614*0a6a1f1dSLionel Sambuc if (!BT_DoubleFree[*CheckKind])
1615*0a6a1f1dSLionel Sambuc BT_DoubleFree[*CheckKind].reset(
1616*0a6a1f1dSLionel Sambuc new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1617f4a2713aSLionel Sambuc
1618*0a6a1f1dSLionel Sambuc BugReport *R =
1619*0a6a1f1dSLionel Sambuc new BugReport(*BT_DoubleFree[*CheckKind],
1620f4a2713aSLionel Sambuc (Released ? "Attempt to free released memory"
1621f4a2713aSLionel Sambuc : "Attempt to free non-owned memory"),
1622f4a2713aSLionel Sambuc N);
1623f4a2713aSLionel Sambuc R->addRange(Range);
1624f4a2713aSLionel Sambuc R->markInteresting(Sym);
1625f4a2713aSLionel Sambuc if (PrevSym)
1626f4a2713aSLionel Sambuc R->markInteresting(PrevSym);
1627*0a6a1f1dSLionel Sambuc R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1628*0a6a1f1dSLionel Sambuc C.emitReport(R);
1629*0a6a1f1dSLionel Sambuc }
1630*0a6a1f1dSLionel Sambuc }
1631*0a6a1f1dSLionel Sambuc
ReportDoubleDelete(CheckerContext & C,SymbolRef Sym) const1632*0a6a1f1dSLionel Sambuc void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1633*0a6a1f1dSLionel Sambuc
1634*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_NewDeleteChecker])
1635*0a6a1f1dSLionel Sambuc return;
1636*0a6a1f1dSLionel Sambuc
1637*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1638*0a6a1f1dSLionel Sambuc if (!CheckKind.hasValue())
1639*0a6a1f1dSLionel Sambuc return;
1640*0a6a1f1dSLionel Sambuc assert(*CheckKind == CK_NewDeleteChecker && "invalid check kind");
1641*0a6a1f1dSLionel Sambuc
1642*0a6a1f1dSLionel Sambuc if (ExplodedNode *N = C.generateSink()) {
1643*0a6a1f1dSLionel Sambuc if (!BT_DoubleDelete)
1644*0a6a1f1dSLionel Sambuc BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1645*0a6a1f1dSLionel Sambuc "Double delete", "Memory Error"));
1646*0a6a1f1dSLionel Sambuc
1647*0a6a1f1dSLionel Sambuc BugReport *R = new BugReport(*BT_DoubleDelete,
1648*0a6a1f1dSLionel Sambuc "Attempt to delete released memory", N);
1649*0a6a1f1dSLionel Sambuc
1650*0a6a1f1dSLionel Sambuc R->markInteresting(Sym);
1651*0a6a1f1dSLionel Sambuc R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1652f4a2713aSLionel Sambuc C.emitReport(R);
1653f4a2713aSLionel Sambuc }
1654f4a2713aSLionel Sambuc }
1655f4a2713aSLionel Sambuc
ReallocMem(CheckerContext & C,const CallExpr * CE,bool FreesOnFail) const1656f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1657f4a2713aSLionel Sambuc const CallExpr *CE,
1658f4a2713aSLionel Sambuc bool FreesOnFail) const {
1659f4a2713aSLionel Sambuc if (CE->getNumArgs() < 2)
1660*0a6a1f1dSLionel Sambuc return nullptr;
1661f4a2713aSLionel Sambuc
1662f4a2713aSLionel Sambuc ProgramStateRef state = C.getState();
1663f4a2713aSLionel Sambuc const Expr *arg0Expr = CE->getArg(0);
1664f4a2713aSLionel Sambuc const LocationContext *LCtx = C.getLocationContext();
1665f4a2713aSLionel Sambuc SVal Arg0Val = state->getSVal(arg0Expr, LCtx);
1666f4a2713aSLionel Sambuc if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
1667*0a6a1f1dSLionel Sambuc return nullptr;
1668f4a2713aSLionel Sambuc DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
1669f4a2713aSLionel Sambuc
1670f4a2713aSLionel Sambuc SValBuilder &svalBuilder = C.getSValBuilder();
1671f4a2713aSLionel Sambuc
1672f4a2713aSLionel Sambuc DefinedOrUnknownSVal PtrEQ =
1673f4a2713aSLionel Sambuc svalBuilder.evalEQ(state, arg0Val, svalBuilder.makeNull());
1674f4a2713aSLionel Sambuc
1675f4a2713aSLionel Sambuc // Get the size argument. If there is no size arg then give up.
1676f4a2713aSLionel Sambuc const Expr *Arg1 = CE->getArg(1);
1677f4a2713aSLionel Sambuc if (!Arg1)
1678*0a6a1f1dSLionel Sambuc return nullptr;
1679f4a2713aSLionel Sambuc
1680f4a2713aSLionel Sambuc // Get the value of the size argument.
1681f4a2713aSLionel Sambuc SVal Arg1ValG = state->getSVal(Arg1, LCtx);
1682f4a2713aSLionel Sambuc if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
1683*0a6a1f1dSLionel Sambuc return nullptr;
1684f4a2713aSLionel Sambuc DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
1685f4a2713aSLionel Sambuc
1686f4a2713aSLionel Sambuc // Compare the size argument to 0.
1687f4a2713aSLionel Sambuc DefinedOrUnknownSVal SizeZero =
1688f4a2713aSLionel Sambuc svalBuilder.evalEQ(state, Arg1Val,
1689f4a2713aSLionel Sambuc svalBuilder.makeIntValWithPtrWidth(0, false));
1690f4a2713aSLionel Sambuc
1691f4a2713aSLionel Sambuc ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1692*0a6a1f1dSLionel Sambuc std::tie(StatePtrIsNull, StatePtrNotNull) = state->assume(PtrEQ);
1693f4a2713aSLionel Sambuc ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1694*0a6a1f1dSLionel Sambuc std::tie(StateSizeIsZero, StateSizeNotZero) = state->assume(SizeZero);
1695f4a2713aSLionel Sambuc // We only assume exceptional states if they are definitely true; if the
1696f4a2713aSLionel Sambuc // state is under-constrained, assume regular realloc behavior.
1697f4a2713aSLionel Sambuc bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1698f4a2713aSLionel Sambuc bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1699f4a2713aSLionel Sambuc
1700f4a2713aSLionel Sambuc // If the ptr is NULL and the size is not 0, the call is equivalent to
1701f4a2713aSLionel Sambuc // malloc(size).
1702f4a2713aSLionel Sambuc if ( PrtIsNull && !SizeIsZero) {
1703f4a2713aSLionel Sambuc ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
1704f4a2713aSLionel Sambuc UndefinedVal(), StatePtrIsNull);
1705f4a2713aSLionel Sambuc return stateMalloc;
1706f4a2713aSLionel Sambuc }
1707f4a2713aSLionel Sambuc
1708f4a2713aSLionel Sambuc if (PrtIsNull && SizeIsZero)
1709*0a6a1f1dSLionel Sambuc return nullptr;
1710f4a2713aSLionel Sambuc
1711f4a2713aSLionel Sambuc // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
1712f4a2713aSLionel Sambuc assert(!PrtIsNull);
1713f4a2713aSLionel Sambuc SymbolRef FromPtr = arg0Val.getAsSymbol();
1714f4a2713aSLionel Sambuc SVal RetVal = state->getSVal(CE, LCtx);
1715f4a2713aSLionel Sambuc SymbolRef ToPtr = RetVal.getAsSymbol();
1716f4a2713aSLionel Sambuc if (!FromPtr || !ToPtr)
1717*0a6a1f1dSLionel Sambuc return nullptr;
1718f4a2713aSLionel Sambuc
1719f4a2713aSLionel Sambuc bool ReleasedAllocated = false;
1720f4a2713aSLionel Sambuc
1721f4a2713aSLionel Sambuc // If the size is 0, free the memory.
1722f4a2713aSLionel Sambuc if (SizeIsZero)
1723f4a2713aSLionel Sambuc if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1724f4a2713aSLionel Sambuc false, ReleasedAllocated)){
1725f4a2713aSLionel Sambuc // The semantics of the return value are:
1726f4a2713aSLionel Sambuc // If size was equal to 0, either NULL or a pointer suitable to be passed
1727f4a2713aSLionel Sambuc // to free() is returned. We just free the input pointer and do not add
1728f4a2713aSLionel Sambuc // any constrains on the output pointer.
1729f4a2713aSLionel Sambuc return stateFree;
1730f4a2713aSLionel Sambuc }
1731f4a2713aSLionel Sambuc
1732f4a2713aSLionel Sambuc // Default behavior.
1733f4a2713aSLionel Sambuc if (ProgramStateRef stateFree =
1734f4a2713aSLionel Sambuc FreeMemAux(C, CE, state, 0, false, ReleasedAllocated)) {
1735f4a2713aSLionel Sambuc
1736f4a2713aSLionel Sambuc ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1737f4a2713aSLionel Sambuc UnknownVal(), stateFree);
1738f4a2713aSLionel Sambuc if (!stateRealloc)
1739*0a6a1f1dSLionel Sambuc return nullptr;
1740f4a2713aSLionel Sambuc
1741f4a2713aSLionel Sambuc ReallocPairKind Kind = RPToBeFreedAfterFailure;
1742f4a2713aSLionel Sambuc if (FreesOnFail)
1743f4a2713aSLionel Sambuc Kind = RPIsFreeOnFailure;
1744f4a2713aSLionel Sambuc else if (!ReleasedAllocated)
1745f4a2713aSLionel Sambuc Kind = RPDoNotTrackAfterFailure;
1746f4a2713aSLionel Sambuc
1747f4a2713aSLionel Sambuc // Record the info about the reallocated symbol so that we could properly
1748f4a2713aSLionel Sambuc // process failed reallocation.
1749f4a2713aSLionel Sambuc stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
1750f4a2713aSLionel Sambuc ReallocPair(FromPtr, Kind));
1751f4a2713aSLionel Sambuc // The reallocated symbol should stay alive for as long as the new symbol.
1752f4a2713aSLionel Sambuc C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
1753f4a2713aSLionel Sambuc return stateRealloc;
1754f4a2713aSLionel Sambuc }
1755*0a6a1f1dSLionel Sambuc return nullptr;
1756f4a2713aSLionel Sambuc }
1757f4a2713aSLionel Sambuc
CallocMem(CheckerContext & C,const CallExpr * CE)1758f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE){
1759f4a2713aSLionel Sambuc if (CE->getNumArgs() < 2)
1760*0a6a1f1dSLionel Sambuc return nullptr;
1761f4a2713aSLionel Sambuc
1762f4a2713aSLionel Sambuc ProgramStateRef state = C.getState();
1763f4a2713aSLionel Sambuc SValBuilder &svalBuilder = C.getSValBuilder();
1764f4a2713aSLionel Sambuc const LocationContext *LCtx = C.getLocationContext();
1765f4a2713aSLionel Sambuc SVal count = state->getSVal(CE->getArg(0), LCtx);
1766f4a2713aSLionel Sambuc SVal elementSize = state->getSVal(CE->getArg(1), LCtx);
1767f4a2713aSLionel Sambuc SVal TotalSize = svalBuilder.evalBinOp(state, BO_Mul, count, elementSize,
1768f4a2713aSLionel Sambuc svalBuilder.getContext().getSizeType());
1769f4a2713aSLionel Sambuc SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1770f4a2713aSLionel Sambuc
1771f4a2713aSLionel Sambuc return MallocMemAux(C, CE, TotalSize, zeroVal, state);
1772f4a2713aSLionel Sambuc }
1773f4a2713aSLionel Sambuc
1774f4a2713aSLionel Sambuc LeakInfo
getAllocationSite(const ExplodedNode * N,SymbolRef Sym,CheckerContext & C) const1775f4a2713aSLionel Sambuc MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
1776f4a2713aSLionel Sambuc CheckerContext &C) const {
1777f4a2713aSLionel Sambuc const LocationContext *LeakContext = N->getLocationContext();
1778f4a2713aSLionel Sambuc // Walk the ExplodedGraph backwards and find the first node that referred to
1779f4a2713aSLionel Sambuc // the tracked symbol.
1780f4a2713aSLionel Sambuc const ExplodedNode *AllocNode = N;
1781*0a6a1f1dSLionel Sambuc const MemRegion *ReferenceRegion = nullptr;
1782f4a2713aSLionel Sambuc
1783f4a2713aSLionel Sambuc while (N) {
1784f4a2713aSLionel Sambuc ProgramStateRef State = N->getState();
1785f4a2713aSLionel Sambuc if (!State->get<RegionState>(Sym))
1786f4a2713aSLionel Sambuc break;
1787f4a2713aSLionel Sambuc
1788f4a2713aSLionel Sambuc // Find the most recent expression bound to the symbol in the current
1789f4a2713aSLionel Sambuc // context.
1790f4a2713aSLionel Sambuc if (!ReferenceRegion) {
1791f4a2713aSLionel Sambuc if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
1792f4a2713aSLionel Sambuc SVal Val = State->getSVal(MR);
1793f4a2713aSLionel Sambuc if (Val.getAsLocSymbol() == Sym) {
1794f4a2713aSLionel Sambuc const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
1795f4a2713aSLionel Sambuc // Do not show local variables belonging to a function other than
1796f4a2713aSLionel Sambuc // where the error is reported.
1797f4a2713aSLionel Sambuc if (!VR ||
1798f4a2713aSLionel Sambuc (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
1799f4a2713aSLionel Sambuc ReferenceRegion = MR;
1800f4a2713aSLionel Sambuc }
1801f4a2713aSLionel Sambuc }
1802f4a2713aSLionel Sambuc }
1803f4a2713aSLionel Sambuc
1804f4a2713aSLionel Sambuc // Allocation node, is the last node in the current context in which the
1805f4a2713aSLionel Sambuc // symbol was tracked.
1806f4a2713aSLionel Sambuc if (N->getLocationContext() == LeakContext)
1807f4a2713aSLionel Sambuc AllocNode = N;
1808*0a6a1f1dSLionel Sambuc N = N->pred_empty() ? nullptr : *(N->pred_begin());
1809f4a2713aSLionel Sambuc }
1810f4a2713aSLionel Sambuc
1811f4a2713aSLionel Sambuc return LeakInfo(AllocNode, ReferenceRegion);
1812f4a2713aSLionel Sambuc }
1813f4a2713aSLionel Sambuc
reportLeak(SymbolRef Sym,ExplodedNode * N,CheckerContext & C) const1814f4a2713aSLionel Sambuc void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
1815f4a2713aSLionel Sambuc CheckerContext &C) const {
1816f4a2713aSLionel Sambuc
1817*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_MallocOptimistic] &&
1818*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_MallocPessimistic] &&
1819*0a6a1f1dSLionel Sambuc !ChecksEnabled[CK_NewDeleteLeaksChecker])
1820f4a2713aSLionel Sambuc return;
1821f4a2713aSLionel Sambuc
1822f4a2713aSLionel Sambuc const RefState *RS = C.getState()->get<RegionState>(Sym);
1823f4a2713aSLionel Sambuc assert(RS && "cannot leak an untracked symbol");
1824f4a2713aSLionel Sambuc AllocationFamily Family = RS->getAllocationFamily();
1825*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
1826*0a6a1f1dSLionel Sambuc if (!CheckKind.hasValue())
1827f4a2713aSLionel Sambuc return;
1828f4a2713aSLionel Sambuc
1829f4a2713aSLionel Sambuc // Special case for new and new[]; these are controlled by a separate checker
1830f4a2713aSLionel Sambuc // flag so that they can be selectively disabled.
1831f4a2713aSLionel Sambuc if (Family == AF_CXXNew || Family == AF_CXXNewArray)
1832*0a6a1f1dSLionel Sambuc if (!ChecksEnabled[CK_NewDeleteLeaksChecker])
1833f4a2713aSLionel Sambuc return;
1834f4a2713aSLionel Sambuc
1835f4a2713aSLionel Sambuc assert(N);
1836*0a6a1f1dSLionel Sambuc if (!BT_Leak[*CheckKind]) {
1837*0a6a1f1dSLionel Sambuc BT_Leak[*CheckKind].reset(
1838*0a6a1f1dSLionel Sambuc new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
1839f4a2713aSLionel Sambuc // Leaks should not be reported if they are post-dominated by a sink:
1840f4a2713aSLionel Sambuc // (1) Sinks are higher importance bugs.
1841f4a2713aSLionel Sambuc // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
1842f4a2713aSLionel Sambuc // with __noreturn functions such as assert() or exit(). We choose not
1843f4a2713aSLionel Sambuc // to report leaks on such paths.
1844*0a6a1f1dSLionel Sambuc BT_Leak[*CheckKind]->setSuppressOnSink(true);
1845f4a2713aSLionel Sambuc }
1846f4a2713aSLionel Sambuc
1847f4a2713aSLionel Sambuc // Most bug reports are cached at the location where they occurred.
1848f4a2713aSLionel Sambuc // With leaks, we want to unique them by the location where they were
1849f4a2713aSLionel Sambuc // allocated, and only report a single path.
1850f4a2713aSLionel Sambuc PathDiagnosticLocation LocUsedForUniqueing;
1851*0a6a1f1dSLionel Sambuc const ExplodedNode *AllocNode = nullptr;
1852*0a6a1f1dSLionel Sambuc const MemRegion *Region = nullptr;
1853*0a6a1f1dSLionel Sambuc std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
1854f4a2713aSLionel Sambuc
1855f4a2713aSLionel Sambuc ProgramPoint P = AllocNode->getLocation();
1856*0a6a1f1dSLionel Sambuc const Stmt *AllocationStmt = nullptr;
1857f4a2713aSLionel Sambuc if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
1858f4a2713aSLionel Sambuc AllocationStmt = Exit->getCalleeContext()->getCallSite();
1859f4a2713aSLionel Sambuc else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
1860f4a2713aSLionel Sambuc AllocationStmt = SP->getStmt();
1861f4a2713aSLionel Sambuc if (AllocationStmt)
1862f4a2713aSLionel Sambuc LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
1863f4a2713aSLionel Sambuc C.getSourceManager(),
1864f4a2713aSLionel Sambuc AllocNode->getLocationContext());
1865f4a2713aSLionel Sambuc
1866f4a2713aSLionel Sambuc SmallString<200> buf;
1867f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
1868f4a2713aSLionel Sambuc if (Region && Region->canPrintPretty()) {
1869f4a2713aSLionel Sambuc os << "Potential leak of memory pointed to by ";
1870f4a2713aSLionel Sambuc Region->printPretty(os);
1871f4a2713aSLionel Sambuc } else {
1872f4a2713aSLionel Sambuc os << "Potential memory leak";
1873f4a2713aSLionel Sambuc }
1874f4a2713aSLionel Sambuc
1875*0a6a1f1dSLionel Sambuc BugReport *R =
1876*0a6a1f1dSLionel Sambuc new BugReport(*BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
1877f4a2713aSLionel Sambuc AllocNode->getLocationContext()->getDecl());
1878f4a2713aSLionel Sambuc R->markInteresting(Sym);
1879*0a6a1f1dSLionel Sambuc R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
1880f4a2713aSLionel Sambuc C.emitReport(R);
1881f4a2713aSLionel Sambuc }
1882f4a2713aSLionel Sambuc
checkDeadSymbols(SymbolReaper & SymReaper,CheckerContext & C) const1883f4a2713aSLionel Sambuc void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
1884f4a2713aSLionel Sambuc CheckerContext &C) const
1885f4a2713aSLionel Sambuc {
1886f4a2713aSLionel Sambuc if (!SymReaper.hasDeadSymbols())
1887f4a2713aSLionel Sambuc return;
1888f4a2713aSLionel Sambuc
1889f4a2713aSLionel Sambuc ProgramStateRef state = C.getState();
1890f4a2713aSLionel Sambuc RegionStateTy RS = state->get<RegionState>();
1891f4a2713aSLionel Sambuc RegionStateTy::Factory &F = state->get_context<RegionState>();
1892f4a2713aSLionel Sambuc
1893f4a2713aSLionel Sambuc SmallVector<SymbolRef, 2> Errors;
1894f4a2713aSLionel Sambuc for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
1895f4a2713aSLionel Sambuc if (SymReaper.isDead(I->first)) {
1896f4a2713aSLionel Sambuc if (I->second.isAllocated())
1897f4a2713aSLionel Sambuc Errors.push_back(I->first);
1898f4a2713aSLionel Sambuc // Remove the dead symbol from the map.
1899f4a2713aSLionel Sambuc RS = F.remove(RS, I->first);
1900f4a2713aSLionel Sambuc
1901f4a2713aSLionel Sambuc }
1902f4a2713aSLionel Sambuc }
1903f4a2713aSLionel Sambuc
1904f4a2713aSLionel Sambuc // Cleanup the Realloc Pairs Map.
1905f4a2713aSLionel Sambuc ReallocPairsTy RP = state->get<ReallocPairs>();
1906f4a2713aSLionel Sambuc for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
1907f4a2713aSLionel Sambuc if (SymReaper.isDead(I->first) ||
1908f4a2713aSLionel Sambuc SymReaper.isDead(I->second.ReallocatedSym)) {
1909f4a2713aSLionel Sambuc state = state->remove<ReallocPairs>(I->first);
1910f4a2713aSLionel Sambuc }
1911f4a2713aSLionel Sambuc }
1912f4a2713aSLionel Sambuc
1913f4a2713aSLionel Sambuc // Cleanup the FreeReturnValue Map.
1914f4a2713aSLionel Sambuc FreeReturnValueTy FR = state->get<FreeReturnValue>();
1915f4a2713aSLionel Sambuc for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
1916f4a2713aSLionel Sambuc if (SymReaper.isDead(I->first) ||
1917f4a2713aSLionel Sambuc SymReaper.isDead(I->second)) {
1918f4a2713aSLionel Sambuc state = state->remove<FreeReturnValue>(I->first);
1919f4a2713aSLionel Sambuc }
1920f4a2713aSLionel Sambuc }
1921f4a2713aSLionel Sambuc
1922f4a2713aSLionel Sambuc // Generate leak node.
1923f4a2713aSLionel Sambuc ExplodedNode *N = C.getPredecessor();
1924f4a2713aSLionel Sambuc if (!Errors.empty()) {
1925*0a6a1f1dSLionel Sambuc static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
1926f4a2713aSLionel Sambuc N = C.addTransition(C.getState(), C.getPredecessor(), &Tag);
1927f4a2713aSLionel Sambuc for (SmallVectorImpl<SymbolRef>::iterator
1928f4a2713aSLionel Sambuc I = Errors.begin(), E = Errors.end(); I != E; ++I) {
1929f4a2713aSLionel Sambuc reportLeak(*I, N, C);
1930f4a2713aSLionel Sambuc }
1931f4a2713aSLionel Sambuc }
1932f4a2713aSLionel Sambuc
1933f4a2713aSLionel Sambuc C.addTransition(state->set<RegionState>(RS), N);
1934f4a2713aSLionel Sambuc }
1935f4a2713aSLionel Sambuc
checkPreCall(const CallEvent & Call,CheckerContext & C) const1936f4a2713aSLionel Sambuc void MallocChecker::checkPreCall(const CallEvent &Call,
1937f4a2713aSLionel Sambuc CheckerContext &C) const {
1938f4a2713aSLionel Sambuc
1939*0a6a1f1dSLionel Sambuc if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
1940*0a6a1f1dSLionel Sambuc SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
1941*0a6a1f1dSLionel Sambuc if (!Sym || checkDoubleDelete(Sym, C))
1942*0a6a1f1dSLionel Sambuc return;
1943*0a6a1f1dSLionel Sambuc }
1944*0a6a1f1dSLionel Sambuc
1945f4a2713aSLionel Sambuc // We will check for double free in the post visit.
1946f4a2713aSLionel Sambuc if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
1947f4a2713aSLionel Sambuc const FunctionDecl *FD = FC->getDecl();
1948f4a2713aSLionel Sambuc if (!FD)
1949f4a2713aSLionel Sambuc return;
1950f4a2713aSLionel Sambuc
1951*0a6a1f1dSLionel Sambuc ASTContext &Ctx = C.getASTContext();
1952*0a6a1f1dSLionel Sambuc if ((ChecksEnabled[CK_MallocOptimistic] ||
1953*0a6a1f1dSLionel Sambuc ChecksEnabled[CK_MallocPessimistic]) &&
1954*0a6a1f1dSLionel Sambuc (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
1955*0a6a1f1dSLionel Sambuc isCMemFunction(FD, Ctx, AF_IfNameIndex,
1956*0a6a1f1dSLionel Sambuc MemoryOperationKind::MOK_Free)))
1957f4a2713aSLionel Sambuc return;
1958f4a2713aSLionel Sambuc
1959*0a6a1f1dSLionel Sambuc if (ChecksEnabled[CK_NewDeleteChecker] &&
1960*0a6a1f1dSLionel Sambuc isStandardNewDelete(FD, Ctx))
1961f4a2713aSLionel Sambuc return;
1962f4a2713aSLionel Sambuc }
1963f4a2713aSLionel Sambuc
1964f4a2713aSLionel Sambuc // Check if the callee of a method is deleted.
1965f4a2713aSLionel Sambuc if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
1966f4a2713aSLionel Sambuc SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
1967f4a2713aSLionel Sambuc if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
1968f4a2713aSLionel Sambuc return;
1969f4a2713aSLionel Sambuc }
1970f4a2713aSLionel Sambuc
1971f4a2713aSLionel Sambuc // Check arguments for being used after free.
1972f4a2713aSLionel Sambuc for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
1973f4a2713aSLionel Sambuc SVal ArgSVal = Call.getArgSVal(I);
1974f4a2713aSLionel Sambuc if (ArgSVal.getAs<Loc>()) {
1975f4a2713aSLionel Sambuc SymbolRef Sym = ArgSVal.getAsSymbol();
1976f4a2713aSLionel Sambuc if (!Sym)
1977f4a2713aSLionel Sambuc continue;
1978f4a2713aSLionel Sambuc if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
1979f4a2713aSLionel Sambuc return;
1980f4a2713aSLionel Sambuc }
1981f4a2713aSLionel Sambuc }
1982f4a2713aSLionel Sambuc }
1983f4a2713aSLionel Sambuc
checkPreStmt(const ReturnStmt * S,CheckerContext & C) const1984f4a2713aSLionel Sambuc void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
1985f4a2713aSLionel Sambuc const Expr *E = S->getRetValue();
1986f4a2713aSLionel Sambuc if (!E)
1987f4a2713aSLionel Sambuc return;
1988f4a2713aSLionel Sambuc
1989f4a2713aSLionel Sambuc // Check if we are returning a symbol.
1990f4a2713aSLionel Sambuc ProgramStateRef State = C.getState();
1991f4a2713aSLionel Sambuc SVal RetVal = State->getSVal(E, C.getLocationContext());
1992f4a2713aSLionel Sambuc SymbolRef Sym = RetVal.getAsSymbol();
1993f4a2713aSLionel Sambuc if (!Sym)
1994f4a2713aSLionel Sambuc // If we are returning a field of the allocated struct or an array element,
1995f4a2713aSLionel Sambuc // the callee could still free the memory.
1996f4a2713aSLionel Sambuc // TODO: This logic should be a part of generic symbol escape callback.
1997f4a2713aSLionel Sambuc if (const MemRegion *MR = RetVal.getAsRegion())
1998f4a2713aSLionel Sambuc if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
1999f4a2713aSLionel Sambuc if (const SymbolicRegion *BMR =
2000f4a2713aSLionel Sambuc dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2001f4a2713aSLionel Sambuc Sym = BMR->getSymbol();
2002f4a2713aSLionel Sambuc
2003f4a2713aSLionel Sambuc // Check if we are returning freed memory.
2004f4a2713aSLionel Sambuc if (Sym)
2005f4a2713aSLionel Sambuc checkUseAfterFree(Sym, C, E);
2006f4a2713aSLionel Sambuc }
2007f4a2713aSLionel Sambuc
2008f4a2713aSLionel Sambuc // TODO: Blocks should be either inlined or should call invalidate regions
2009f4a2713aSLionel Sambuc // upon invocation. After that's in place, special casing here will not be
2010f4a2713aSLionel Sambuc // needed.
checkPostStmt(const BlockExpr * BE,CheckerContext & C) const2011f4a2713aSLionel Sambuc void MallocChecker::checkPostStmt(const BlockExpr *BE,
2012f4a2713aSLionel Sambuc CheckerContext &C) const {
2013f4a2713aSLionel Sambuc
2014f4a2713aSLionel Sambuc // Scan the BlockDecRefExprs for any object the retain count checker
2015f4a2713aSLionel Sambuc // may be tracking.
2016f4a2713aSLionel Sambuc if (!BE->getBlockDecl()->hasCaptures())
2017f4a2713aSLionel Sambuc return;
2018f4a2713aSLionel Sambuc
2019f4a2713aSLionel Sambuc ProgramStateRef state = C.getState();
2020f4a2713aSLionel Sambuc const BlockDataRegion *R =
2021f4a2713aSLionel Sambuc cast<BlockDataRegion>(state->getSVal(BE,
2022f4a2713aSLionel Sambuc C.getLocationContext()).getAsRegion());
2023f4a2713aSLionel Sambuc
2024f4a2713aSLionel Sambuc BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2025f4a2713aSLionel Sambuc E = R->referenced_vars_end();
2026f4a2713aSLionel Sambuc
2027f4a2713aSLionel Sambuc if (I == E)
2028f4a2713aSLionel Sambuc return;
2029f4a2713aSLionel Sambuc
2030f4a2713aSLionel Sambuc SmallVector<const MemRegion*, 10> Regions;
2031f4a2713aSLionel Sambuc const LocationContext *LC = C.getLocationContext();
2032f4a2713aSLionel Sambuc MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2033f4a2713aSLionel Sambuc
2034f4a2713aSLionel Sambuc for ( ; I != E; ++I) {
2035f4a2713aSLionel Sambuc const VarRegion *VR = I.getCapturedRegion();
2036f4a2713aSLionel Sambuc if (VR->getSuperRegion() == R) {
2037f4a2713aSLionel Sambuc VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2038f4a2713aSLionel Sambuc }
2039f4a2713aSLionel Sambuc Regions.push_back(VR);
2040f4a2713aSLionel Sambuc }
2041f4a2713aSLionel Sambuc
2042f4a2713aSLionel Sambuc state =
2043f4a2713aSLionel Sambuc state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2044f4a2713aSLionel Sambuc Regions.data() + Regions.size()).getState();
2045f4a2713aSLionel Sambuc C.addTransition(state);
2046f4a2713aSLionel Sambuc }
2047f4a2713aSLionel Sambuc
isReleased(SymbolRef Sym,CheckerContext & C) const2048f4a2713aSLionel Sambuc bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2049f4a2713aSLionel Sambuc assert(Sym);
2050f4a2713aSLionel Sambuc const RefState *RS = C.getState()->get<RegionState>(Sym);
2051f4a2713aSLionel Sambuc return (RS && RS->isReleased());
2052f4a2713aSLionel Sambuc }
2053f4a2713aSLionel Sambuc
checkUseAfterFree(SymbolRef Sym,CheckerContext & C,const Stmt * S) const2054f4a2713aSLionel Sambuc bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2055f4a2713aSLionel Sambuc const Stmt *S) const {
2056f4a2713aSLionel Sambuc
2057*0a6a1f1dSLionel Sambuc if (isReleased(Sym, C)) {
2058f4a2713aSLionel Sambuc ReportUseAfterFree(C, S->getSourceRange(), Sym);
2059f4a2713aSLionel Sambuc return true;
2060f4a2713aSLionel Sambuc }
2061f4a2713aSLionel Sambuc
2062f4a2713aSLionel Sambuc return false;
2063f4a2713aSLionel Sambuc }
2064f4a2713aSLionel Sambuc
checkDoubleDelete(SymbolRef Sym,CheckerContext & C) const2065*0a6a1f1dSLionel Sambuc bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2066*0a6a1f1dSLionel Sambuc
2067*0a6a1f1dSLionel Sambuc if (isReleased(Sym, C)) {
2068*0a6a1f1dSLionel Sambuc ReportDoubleDelete(C, Sym);
2069*0a6a1f1dSLionel Sambuc return true;
2070*0a6a1f1dSLionel Sambuc }
2071*0a6a1f1dSLionel Sambuc return false;
2072*0a6a1f1dSLionel Sambuc }
2073*0a6a1f1dSLionel Sambuc
2074f4a2713aSLionel Sambuc // Check if the location is a freed symbolic region.
checkLocation(SVal l,bool isLoad,const Stmt * S,CheckerContext & C) const2075f4a2713aSLionel Sambuc void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2076f4a2713aSLionel Sambuc CheckerContext &C) const {
2077f4a2713aSLionel Sambuc SymbolRef Sym = l.getLocSymbolInBase();
2078f4a2713aSLionel Sambuc if (Sym)
2079f4a2713aSLionel Sambuc checkUseAfterFree(Sym, C, S);
2080f4a2713aSLionel Sambuc }
2081f4a2713aSLionel Sambuc
2082f4a2713aSLionel Sambuc // If a symbolic region is assumed to NULL (or another constant), stop tracking
2083f4a2713aSLionel Sambuc // it - assuming that allocation failed on this path.
evalAssume(ProgramStateRef state,SVal Cond,bool Assumption) const2084f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2085f4a2713aSLionel Sambuc SVal Cond,
2086f4a2713aSLionel Sambuc bool Assumption) const {
2087f4a2713aSLionel Sambuc RegionStateTy RS = state->get<RegionState>();
2088f4a2713aSLionel Sambuc for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2089f4a2713aSLionel Sambuc // If the symbol is assumed to be NULL, remove it from consideration.
2090f4a2713aSLionel Sambuc ConstraintManager &CMgr = state->getConstraintManager();
2091f4a2713aSLionel Sambuc ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2092f4a2713aSLionel Sambuc if (AllocFailed.isConstrainedTrue())
2093f4a2713aSLionel Sambuc state = state->remove<RegionState>(I.getKey());
2094f4a2713aSLionel Sambuc }
2095f4a2713aSLionel Sambuc
2096f4a2713aSLionel Sambuc // Realloc returns 0 when reallocation fails, which means that we should
2097f4a2713aSLionel Sambuc // restore the state of the pointer being reallocated.
2098f4a2713aSLionel Sambuc ReallocPairsTy RP = state->get<ReallocPairs>();
2099f4a2713aSLionel Sambuc for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2100f4a2713aSLionel Sambuc // If the symbol is assumed to be NULL, remove it from consideration.
2101f4a2713aSLionel Sambuc ConstraintManager &CMgr = state->getConstraintManager();
2102f4a2713aSLionel Sambuc ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2103f4a2713aSLionel Sambuc if (!AllocFailed.isConstrainedTrue())
2104f4a2713aSLionel Sambuc continue;
2105f4a2713aSLionel Sambuc
2106f4a2713aSLionel Sambuc SymbolRef ReallocSym = I.getData().ReallocatedSym;
2107f4a2713aSLionel Sambuc if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2108f4a2713aSLionel Sambuc if (RS->isReleased()) {
2109f4a2713aSLionel Sambuc if (I.getData().Kind == RPToBeFreedAfterFailure)
2110f4a2713aSLionel Sambuc state = state->set<RegionState>(ReallocSym,
2111f4a2713aSLionel Sambuc RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2112f4a2713aSLionel Sambuc else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2113f4a2713aSLionel Sambuc state = state->remove<RegionState>(ReallocSym);
2114f4a2713aSLionel Sambuc else
2115f4a2713aSLionel Sambuc assert(I.getData().Kind == RPIsFreeOnFailure);
2116f4a2713aSLionel Sambuc }
2117f4a2713aSLionel Sambuc }
2118f4a2713aSLionel Sambuc state = state->remove<ReallocPairs>(I.getKey());
2119f4a2713aSLionel Sambuc }
2120f4a2713aSLionel Sambuc
2121f4a2713aSLionel Sambuc return state;
2122f4a2713aSLionel Sambuc }
2123f4a2713aSLionel Sambuc
mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent * Call,ProgramStateRef State,SymbolRef & EscapingSymbol) const2124f4a2713aSLionel Sambuc bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2125f4a2713aSLionel Sambuc const CallEvent *Call,
2126f4a2713aSLionel Sambuc ProgramStateRef State,
2127f4a2713aSLionel Sambuc SymbolRef &EscapingSymbol) const {
2128f4a2713aSLionel Sambuc assert(Call);
2129*0a6a1f1dSLionel Sambuc EscapingSymbol = nullptr;
2130f4a2713aSLionel Sambuc
2131*0a6a1f1dSLionel Sambuc // For now, assume that any C++ or block call can free memory.
2132f4a2713aSLionel Sambuc // TODO: If we want to be more optimistic here, we'll need to make sure that
2133f4a2713aSLionel Sambuc // regions escape to C++ containers. They seem to do that even now, but for
2134f4a2713aSLionel Sambuc // mysterious reasons.
2135*0a6a1f1dSLionel Sambuc if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2136f4a2713aSLionel Sambuc return true;
2137f4a2713aSLionel Sambuc
2138f4a2713aSLionel Sambuc // Check Objective-C messages by selector name.
2139f4a2713aSLionel Sambuc if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2140f4a2713aSLionel Sambuc // If it's not a framework call, or if it takes a callback, assume it
2141f4a2713aSLionel Sambuc // can free memory.
2142f4a2713aSLionel Sambuc if (!Call->isInSystemHeader() || Call->hasNonZeroCallbackArg())
2143f4a2713aSLionel Sambuc return true;
2144f4a2713aSLionel Sambuc
2145f4a2713aSLionel Sambuc // If it's a method we know about, handle it explicitly post-call.
2146f4a2713aSLionel Sambuc // This should happen before the "freeWhenDone" check below.
2147f4a2713aSLionel Sambuc if (isKnownDeallocObjCMethodName(*Msg))
2148f4a2713aSLionel Sambuc return false;
2149f4a2713aSLionel Sambuc
2150f4a2713aSLionel Sambuc // If there's a "freeWhenDone" parameter, but the method isn't one we know
2151f4a2713aSLionel Sambuc // about, we can't be sure that the object will use free() to deallocate the
2152f4a2713aSLionel Sambuc // memory, so we can't model it explicitly. The best we can do is use it to
2153f4a2713aSLionel Sambuc // decide whether the pointer escapes.
2154f4a2713aSLionel Sambuc if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2155f4a2713aSLionel Sambuc return *FreeWhenDone;
2156f4a2713aSLionel Sambuc
2157f4a2713aSLionel Sambuc // If the first selector piece ends with "NoCopy", and there is no
2158f4a2713aSLionel Sambuc // "freeWhenDone" parameter set to zero, we know ownership is being
2159f4a2713aSLionel Sambuc // transferred. Again, though, we can't be sure that the object will use
2160f4a2713aSLionel Sambuc // free() to deallocate the memory, so we can't model it explicitly.
2161f4a2713aSLionel Sambuc StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2162f4a2713aSLionel Sambuc if (FirstSlot.endswith("NoCopy"))
2163f4a2713aSLionel Sambuc return true;
2164f4a2713aSLionel Sambuc
2165f4a2713aSLionel Sambuc // If the first selector starts with addPointer, insertPointer,
2166f4a2713aSLionel Sambuc // or replacePointer, assume we are dealing with NSPointerArray or similar.
2167f4a2713aSLionel Sambuc // This is similar to C++ containers (vector); we still might want to check
2168f4a2713aSLionel Sambuc // that the pointers get freed by following the container itself.
2169f4a2713aSLionel Sambuc if (FirstSlot.startswith("addPointer") ||
2170f4a2713aSLionel Sambuc FirstSlot.startswith("insertPointer") ||
2171*0a6a1f1dSLionel Sambuc FirstSlot.startswith("replacePointer") ||
2172*0a6a1f1dSLionel Sambuc FirstSlot.equals("valueWithPointer")) {
2173f4a2713aSLionel Sambuc return true;
2174f4a2713aSLionel Sambuc }
2175f4a2713aSLionel Sambuc
2176f4a2713aSLionel Sambuc // We should escape receiver on call to 'init'. This is especially relevant
2177f4a2713aSLionel Sambuc // to the receiver, as the corresponding symbol is usually not referenced
2178f4a2713aSLionel Sambuc // after the call.
2179f4a2713aSLionel Sambuc if (Msg->getMethodFamily() == OMF_init) {
2180f4a2713aSLionel Sambuc EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2181f4a2713aSLionel Sambuc return true;
2182f4a2713aSLionel Sambuc }
2183f4a2713aSLionel Sambuc
2184f4a2713aSLionel Sambuc // Otherwise, assume that the method does not free memory.
2185f4a2713aSLionel Sambuc // Most framework methods do not free memory.
2186f4a2713aSLionel Sambuc return false;
2187f4a2713aSLionel Sambuc }
2188f4a2713aSLionel Sambuc
2189f4a2713aSLionel Sambuc // At this point the only thing left to handle is straight function calls.
2190*0a6a1f1dSLionel Sambuc const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2191f4a2713aSLionel Sambuc if (!FD)
2192f4a2713aSLionel Sambuc return true;
2193f4a2713aSLionel Sambuc
2194f4a2713aSLionel Sambuc ASTContext &ASTC = State->getStateManager().getContext();
2195f4a2713aSLionel Sambuc
2196f4a2713aSLionel Sambuc // If it's one of the allocation functions we can reason about, we model
2197f4a2713aSLionel Sambuc // its behavior explicitly.
2198f4a2713aSLionel Sambuc if (isMemFunction(FD, ASTC))
2199f4a2713aSLionel Sambuc return false;
2200f4a2713aSLionel Sambuc
2201f4a2713aSLionel Sambuc // If it's not a system call, assume it frees memory.
2202f4a2713aSLionel Sambuc if (!Call->isInSystemHeader())
2203f4a2713aSLionel Sambuc return true;
2204f4a2713aSLionel Sambuc
2205f4a2713aSLionel Sambuc // White list the system functions whose arguments escape.
2206f4a2713aSLionel Sambuc const IdentifierInfo *II = FD->getIdentifier();
2207f4a2713aSLionel Sambuc if (!II)
2208f4a2713aSLionel Sambuc return true;
2209f4a2713aSLionel Sambuc StringRef FName = II->getName();
2210f4a2713aSLionel Sambuc
2211f4a2713aSLionel Sambuc // White list the 'XXXNoCopy' CoreFoundation functions.
2212f4a2713aSLionel Sambuc // We specifically check these before
2213f4a2713aSLionel Sambuc if (FName.endswith("NoCopy")) {
2214f4a2713aSLionel Sambuc // Look for the deallocator argument. We know that the memory ownership
2215f4a2713aSLionel Sambuc // is not transferred only if the deallocator argument is
2216f4a2713aSLionel Sambuc // 'kCFAllocatorNull'.
2217f4a2713aSLionel Sambuc for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2218f4a2713aSLionel Sambuc const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2219f4a2713aSLionel Sambuc if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2220f4a2713aSLionel Sambuc StringRef DeallocatorName = DE->getFoundDecl()->getName();
2221f4a2713aSLionel Sambuc if (DeallocatorName == "kCFAllocatorNull")
2222f4a2713aSLionel Sambuc return false;
2223f4a2713aSLionel Sambuc }
2224f4a2713aSLionel Sambuc }
2225f4a2713aSLionel Sambuc return true;
2226f4a2713aSLionel Sambuc }
2227f4a2713aSLionel Sambuc
2228f4a2713aSLionel Sambuc // Associating streams with malloced buffers. The pointer can escape if
2229f4a2713aSLionel Sambuc // 'closefn' is specified (and if that function does free memory),
2230f4a2713aSLionel Sambuc // but it will not if closefn is not specified.
2231f4a2713aSLionel Sambuc // Currently, we do not inspect the 'closefn' function (PR12101).
2232f4a2713aSLionel Sambuc if (FName == "funopen")
2233f4a2713aSLionel Sambuc if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2234f4a2713aSLionel Sambuc return false;
2235f4a2713aSLionel Sambuc
2236f4a2713aSLionel Sambuc // Do not warn on pointers passed to 'setbuf' when used with std streams,
2237f4a2713aSLionel Sambuc // these leaks might be intentional when setting the buffer for stdio.
2238f4a2713aSLionel Sambuc // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2239f4a2713aSLionel Sambuc if (FName == "setbuf" || FName =="setbuffer" ||
2240f4a2713aSLionel Sambuc FName == "setlinebuf" || FName == "setvbuf") {
2241f4a2713aSLionel Sambuc if (Call->getNumArgs() >= 1) {
2242f4a2713aSLionel Sambuc const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2243f4a2713aSLionel Sambuc if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2244f4a2713aSLionel Sambuc if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2245f4a2713aSLionel Sambuc if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2246f4a2713aSLionel Sambuc return true;
2247f4a2713aSLionel Sambuc }
2248f4a2713aSLionel Sambuc }
2249f4a2713aSLionel Sambuc
2250f4a2713aSLionel Sambuc // A bunch of other functions which either take ownership of a pointer or
2251f4a2713aSLionel Sambuc // wrap the result up in a struct or object, meaning it can be freed later.
2252f4a2713aSLionel Sambuc // (See RetainCountChecker.) Not all the parameters here are invalidated,
2253f4a2713aSLionel Sambuc // but the Malloc checker cannot differentiate between them. The right way
2254f4a2713aSLionel Sambuc // of doing this would be to implement a pointer escapes callback.
2255f4a2713aSLionel Sambuc if (FName == "CGBitmapContextCreate" ||
2256f4a2713aSLionel Sambuc FName == "CGBitmapContextCreateWithData" ||
2257f4a2713aSLionel Sambuc FName == "CVPixelBufferCreateWithBytes" ||
2258f4a2713aSLionel Sambuc FName == "CVPixelBufferCreateWithPlanarBytes" ||
2259f4a2713aSLionel Sambuc FName == "OSAtomicEnqueue") {
2260f4a2713aSLionel Sambuc return true;
2261f4a2713aSLionel Sambuc }
2262f4a2713aSLionel Sambuc
2263f4a2713aSLionel Sambuc // Handle cases where we know a buffer's /address/ can escape.
2264f4a2713aSLionel Sambuc // Note that the above checks handle some special cases where we know that
2265f4a2713aSLionel Sambuc // even though the address escapes, it's still our responsibility to free the
2266f4a2713aSLionel Sambuc // buffer.
2267f4a2713aSLionel Sambuc if (Call->argumentsMayEscape())
2268f4a2713aSLionel Sambuc return true;
2269f4a2713aSLionel Sambuc
2270f4a2713aSLionel Sambuc // Otherwise, assume that the function does not free memory.
2271f4a2713aSLionel Sambuc // Most system calls do not free the memory.
2272f4a2713aSLionel Sambuc return false;
2273f4a2713aSLionel Sambuc }
2274f4a2713aSLionel Sambuc
retTrue(const RefState * RS)2275f4a2713aSLionel Sambuc static bool retTrue(const RefState *RS) {
2276f4a2713aSLionel Sambuc return true;
2277f4a2713aSLionel Sambuc }
2278f4a2713aSLionel Sambuc
checkIfNewOrNewArrayFamily(const RefState * RS)2279f4a2713aSLionel Sambuc static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2280f4a2713aSLionel Sambuc return (RS->getAllocationFamily() == AF_CXXNewArray ||
2281f4a2713aSLionel Sambuc RS->getAllocationFamily() == AF_CXXNew);
2282f4a2713aSLionel Sambuc }
2283f4a2713aSLionel Sambuc
checkPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const2284f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2285f4a2713aSLionel Sambuc const InvalidatedSymbols &Escaped,
2286f4a2713aSLionel Sambuc const CallEvent *Call,
2287f4a2713aSLionel Sambuc PointerEscapeKind Kind) const {
2288f4a2713aSLionel Sambuc return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2289f4a2713aSLionel Sambuc }
2290f4a2713aSLionel Sambuc
checkConstPointerEscape(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind) const2291f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2292f4a2713aSLionel Sambuc const InvalidatedSymbols &Escaped,
2293f4a2713aSLionel Sambuc const CallEvent *Call,
2294f4a2713aSLionel Sambuc PointerEscapeKind Kind) const {
2295f4a2713aSLionel Sambuc return checkPointerEscapeAux(State, Escaped, Call, Kind,
2296f4a2713aSLionel Sambuc &checkIfNewOrNewArrayFamily);
2297f4a2713aSLionel Sambuc }
2298f4a2713aSLionel Sambuc
checkPointerEscapeAux(ProgramStateRef State,const InvalidatedSymbols & Escaped,const CallEvent * Call,PointerEscapeKind Kind,bool (* CheckRefState)(const RefState *)) const2299f4a2713aSLionel Sambuc ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2300f4a2713aSLionel Sambuc const InvalidatedSymbols &Escaped,
2301f4a2713aSLionel Sambuc const CallEvent *Call,
2302f4a2713aSLionel Sambuc PointerEscapeKind Kind,
2303f4a2713aSLionel Sambuc bool(*CheckRefState)(const RefState*)) const {
2304f4a2713aSLionel Sambuc // If we know that the call does not free memory, or we want to process the
2305f4a2713aSLionel Sambuc // call later, keep tracking the top level arguments.
2306*0a6a1f1dSLionel Sambuc SymbolRef EscapingSymbol = nullptr;
2307f4a2713aSLionel Sambuc if (Kind == PSK_DirectEscapeOnCall &&
2308f4a2713aSLionel Sambuc !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2309f4a2713aSLionel Sambuc EscapingSymbol) &&
2310f4a2713aSLionel Sambuc !EscapingSymbol) {
2311f4a2713aSLionel Sambuc return State;
2312f4a2713aSLionel Sambuc }
2313f4a2713aSLionel Sambuc
2314f4a2713aSLionel Sambuc for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2315f4a2713aSLionel Sambuc E = Escaped.end();
2316f4a2713aSLionel Sambuc I != E; ++I) {
2317f4a2713aSLionel Sambuc SymbolRef sym = *I;
2318f4a2713aSLionel Sambuc
2319f4a2713aSLionel Sambuc if (EscapingSymbol && EscapingSymbol != sym)
2320f4a2713aSLionel Sambuc continue;
2321f4a2713aSLionel Sambuc
2322f4a2713aSLionel Sambuc if (const RefState *RS = State->get<RegionState>(sym)) {
2323f4a2713aSLionel Sambuc if (RS->isAllocated() && CheckRefState(RS)) {
2324f4a2713aSLionel Sambuc State = State->remove<RegionState>(sym);
2325f4a2713aSLionel Sambuc State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2326f4a2713aSLionel Sambuc }
2327f4a2713aSLionel Sambuc }
2328f4a2713aSLionel Sambuc }
2329f4a2713aSLionel Sambuc return State;
2330f4a2713aSLionel Sambuc }
2331f4a2713aSLionel Sambuc
findFailedReallocSymbol(ProgramStateRef currState,ProgramStateRef prevState)2332f4a2713aSLionel Sambuc static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2333f4a2713aSLionel Sambuc ProgramStateRef prevState) {
2334f4a2713aSLionel Sambuc ReallocPairsTy currMap = currState->get<ReallocPairs>();
2335f4a2713aSLionel Sambuc ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2336f4a2713aSLionel Sambuc
2337f4a2713aSLionel Sambuc for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2338f4a2713aSLionel Sambuc I != E; ++I) {
2339f4a2713aSLionel Sambuc SymbolRef sym = I.getKey();
2340f4a2713aSLionel Sambuc if (!currMap.lookup(sym))
2341f4a2713aSLionel Sambuc return sym;
2342f4a2713aSLionel Sambuc }
2343f4a2713aSLionel Sambuc
2344*0a6a1f1dSLionel Sambuc return nullptr;
2345f4a2713aSLionel Sambuc }
2346f4a2713aSLionel Sambuc
2347f4a2713aSLionel Sambuc PathDiagnosticPiece *
VisitNode(const ExplodedNode * N,const ExplodedNode * PrevN,BugReporterContext & BRC,BugReport & BR)2348f4a2713aSLionel Sambuc MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2349f4a2713aSLionel Sambuc const ExplodedNode *PrevN,
2350f4a2713aSLionel Sambuc BugReporterContext &BRC,
2351f4a2713aSLionel Sambuc BugReport &BR) {
2352f4a2713aSLionel Sambuc ProgramStateRef state = N->getState();
2353f4a2713aSLionel Sambuc ProgramStateRef statePrev = PrevN->getState();
2354f4a2713aSLionel Sambuc
2355f4a2713aSLionel Sambuc const RefState *RS = state->get<RegionState>(Sym);
2356f4a2713aSLionel Sambuc const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2357f4a2713aSLionel Sambuc if (!RS)
2358*0a6a1f1dSLionel Sambuc return nullptr;
2359f4a2713aSLionel Sambuc
2360*0a6a1f1dSLionel Sambuc const Stmt *S = nullptr;
2361*0a6a1f1dSLionel Sambuc const char *Msg = nullptr;
2362*0a6a1f1dSLionel Sambuc StackHintGeneratorForSymbol *StackHint = nullptr;
2363f4a2713aSLionel Sambuc
2364f4a2713aSLionel Sambuc // Retrieve the associated statement.
2365f4a2713aSLionel Sambuc ProgramPoint ProgLoc = N->getLocation();
2366f4a2713aSLionel Sambuc if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
2367f4a2713aSLionel Sambuc S = SP->getStmt();
2368f4a2713aSLionel Sambuc } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
2369f4a2713aSLionel Sambuc S = Exit->getCalleeContext()->getCallSite();
2370f4a2713aSLionel Sambuc } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
2371f4a2713aSLionel Sambuc // If an assumption was made on a branch, it should be caught
2372f4a2713aSLionel Sambuc // here by looking at the state transition.
2373f4a2713aSLionel Sambuc S = Edge->getSrc()->getTerminator();
2374f4a2713aSLionel Sambuc }
2375f4a2713aSLionel Sambuc
2376f4a2713aSLionel Sambuc if (!S)
2377*0a6a1f1dSLionel Sambuc return nullptr;
2378f4a2713aSLionel Sambuc
2379f4a2713aSLionel Sambuc // FIXME: We will eventually need to handle non-statement-based events
2380f4a2713aSLionel Sambuc // (__attribute__((cleanup))).
2381f4a2713aSLionel Sambuc
2382f4a2713aSLionel Sambuc // Find out if this is an interesting point and what is the kind.
2383f4a2713aSLionel Sambuc if (Mode == Normal) {
2384f4a2713aSLionel Sambuc if (isAllocated(RS, RSPrev, S)) {
2385f4a2713aSLionel Sambuc Msg = "Memory is allocated";
2386f4a2713aSLionel Sambuc StackHint = new StackHintGeneratorForSymbol(Sym,
2387f4a2713aSLionel Sambuc "Returned allocated memory");
2388f4a2713aSLionel Sambuc } else if (isReleased(RS, RSPrev, S)) {
2389f4a2713aSLionel Sambuc Msg = "Memory is released";
2390f4a2713aSLionel Sambuc StackHint = new StackHintGeneratorForSymbol(Sym,
2391f4a2713aSLionel Sambuc "Returning; memory was released");
2392f4a2713aSLionel Sambuc } else if (isRelinquished(RS, RSPrev, S)) {
2393*0a6a1f1dSLionel Sambuc Msg = "Memory ownership is transferred";
2394f4a2713aSLionel Sambuc StackHint = new StackHintGeneratorForSymbol(Sym, "");
2395f4a2713aSLionel Sambuc } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2396f4a2713aSLionel Sambuc Mode = ReallocationFailed;
2397f4a2713aSLionel Sambuc Msg = "Reallocation failed";
2398f4a2713aSLionel Sambuc StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2399f4a2713aSLionel Sambuc "Reallocation failed");
2400f4a2713aSLionel Sambuc
2401f4a2713aSLionel Sambuc if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2402f4a2713aSLionel Sambuc // Is it possible to fail two reallocs WITHOUT testing in between?
2403f4a2713aSLionel Sambuc assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2404f4a2713aSLionel Sambuc "We only support one failed realloc at a time.");
2405f4a2713aSLionel Sambuc BR.markInteresting(sym);
2406f4a2713aSLionel Sambuc FailedReallocSymbol = sym;
2407f4a2713aSLionel Sambuc }
2408f4a2713aSLionel Sambuc }
2409f4a2713aSLionel Sambuc
2410f4a2713aSLionel Sambuc // We are in a special mode if a reallocation failed later in the path.
2411f4a2713aSLionel Sambuc } else if (Mode == ReallocationFailed) {
2412f4a2713aSLionel Sambuc assert(FailedReallocSymbol && "No symbol to look for.");
2413f4a2713aSLionel Sambuc
2414f4a2713aSLionel Sambuc // Is this is the first appearance of the reallocated symbol?
2415f4a2713aSLionel Sambuc if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2416f4a2713aSLionel Sambuc // We're at the reallocation point.
2417f4a2713aSLionel Sambuc Msg = "Attempt to reallocate memory";
2418f4a2713aSLionel Sambuc StackHint = new StackHintGeneratorForSymbol(Sym,
2419f4a2713aSLionel Sambuc "Returned reallocated memory");
2420*0a6a1f1dSLionel Sambuc FailedReallocSymbol = nullptr;
2421f4a2713aSLionel Sambuc Mode = Normal;
2422f4a2713aSLionel Sambuc }
2423f4a2713aSLionel Sambuc }
2424f4a2713aSLionel Sambuc
2425f4a2713aSLionel Sambuc if (!Msg)
2426*0a6a1f1dSLionel Sambuc return nullptr;
2427f4a2713aSLionel Sambuc assert(StackHint);
2428f4a2713aSLionel Sambuc
2429f4a2713aSLionel Sambuc // Generate the extra diagnostic.
2430f4a2713aSLionel Sambuc PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2431f4a2713aSLionel Sambuc N->getLocationContext());
2432f4a2713aSLionel Sambuc return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
2433f4a2713aSLionel Sambuc }
2434f4a2713aSLionel Sambuc
printState(raw_ostream & Out,ProgramStateRef State,const char * NL,const char * Sep) const2435f4a2713aSLionel Sambuc void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2436f4a2713aSLionel Sambuc const char *NL, const char *Sep) const {
2437f4a2713aSLionel Sambuc
2438f4a2713aSLionel Sambuc RegionStateTy RS = State->get<RegionState>();
2439f4a2713aSLionel Sambuc
2440f4a2713aSLionel Sambuc if (!RS.isEmpty()) {
2441f4a2713aSLionel Sambuc Out << Sep << "MallocChecker :" << NL;
2442f4a2713aSLionel Sambuc for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2443*0a6a1f1dSLionel Sambuc const RefState *RefS = State->get<RegionState>(I.getKey());
2444*0a6a1f1dSLionel Sambuc AllocationFamily Family = RefS->getAllocationFamily();
2445*0a6a1f1dSLionel Sambuc Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2446*0a6a1f1dSLionel Sambuc
2447f4a2713aSLionel Sambuc I.getKey()->dumpToStream(Out);
2448f4a2713aSLionel Sambuc Out << " : ";
2449f4a2713aSLionel Sambuc I.getData().dump(Out);
2450*0a6a1f1dSLionel Sambuc if (CheckKind.hasValue())
2451*0a6a1f1dSLionel Sambuc Out << " (" << CheckNames[*CheckKind].getName() << ")";
2452f4a2713aSLionel Sambuc Out << NL;
2453f4a2713aSLionel Sambuc }
2454f4a2713aSLionel Sambuc }
2455f4a2713aSLionel Sambuc }
2456f4a2713aSLionel Sambuc
registerNewDeleteLeaksChecker(CheckerManager & mgr)2457f4a2713aSLionel Sambuc void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2458f4a2713aSLionel Sambuc registerCStringCheckerBasic(mgr);
2459*0a6a1f1dSLionel Sambuc MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2460*0a6a1f1dSLionel Sambuc checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2461*0a6a1f1dSLionel Sambuc checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2462*0a6a1f1dSLionel Sambuc mgr.getCurrentCheckName();
2463f4a2713aSLionel Sambuc // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2464f4a2713aSLionel Sambuc // checker.
2465*0a6a1f1dSLionel Sambuc if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2466*0a6a1f1dSLionel Sambuc checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2467f4a2713aSLionel Sambuc }
2468f4a2713aSLionel Sambuc
2469f4a2713aSLionel Sambuc #define REGISTER_CHECKER(name) \
2470f4a2713aSLionel Sambuc void ento::register##name(CheckerManager &mgr) { \
2471f4a2713aSLionel Sambuc registerCStringCheckerBasic(mgr); \
2472*0a6a1f1dSLionel Sambuc MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2473*0a6a1f1dSLionel Sambuc checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2474*0a6a1f1dSLionel Sambuc checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2475f4a2713aSLionel Sambuc }
2476f4a2713aSLionel Sambuc
2477f4a2713aSLionel Sambuc REGISTER_CHECKER(MallocPessimistic)
2478f4a2713aSLionel Sambuc REGISTER_CHECKER(MallocOptimistic)
2479f4a2713aSLionel Sambuc REGISTER_CHECKER(NewDeleteChecker)
2480f4a2713aSLionel Sambuc REGISTER_CHECKER(MismatchedDeallocatorChecker)
2481