1 //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines malloc/free checker, which checks for potential memory
11 // leaks, double free, and use-after-free problems.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "InterCheckerAPI.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
29 #include "llvm/ADT/ImmutableMap.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
35 using namespace clang;
40 // Used to check correspondence between allocators and deallocators.
41 enum AllocationFamily {
51 enum Kind { // Reference to allocated memory.
53 // Reference to zero-allocated memory.
55 // Reference to released/freed memory.
57 // The responsibility for freeing resources has transferred from
58 // this reference. A relinquished symbol should not be freed.
60 // We are no longer guaranteed to have observed all manipulations
61 // of this pointer/memory. For example, it could have been
62 // passed as a parameter to an opaque function.
67 unsigned K : 3; // Kind enum, but stored as a bitfield.
68 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
71 RefState(Kind k, const Stmt *s, unsigned family)
72 : S(s), K(k), Family(family) {
73 assert(family != AF_None);
76 bool isAllocated() const { return K == Allocated; }
77 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
78 bool isReleased() const { return K == Released; }
79 bool isRelinquished() const { return K == Relinquished; }
80 bool isEscaped() const { return K == Escaped; }
81 AllocationFamily getAllocationFamily() const {
82 return (AllocationFamily)Family;
84 const Stmt *getStmt() const { return S; }
86 bool operator==(const RefState &X) const {
87 return K == X.K && S == X.S && Family == X.Family;
90 static RefState getAllocated(unsigned family, const Stmt *s) {
91 return RefState(Allocated, s, family);
93 static RefState getAllocatedOfSizeZero(const RefState *RS) {
94 return RefState(AllocatedOfSizeZero, RS->getStmt(),
95 RS->getAllocationFamily());
97 static RefState getReleased(unsigned family, const Stmt *s) {
98 return RefState(Released, s, family);
100 static RefState getRelinquished(unsigned family, const Stmt *s) {
101 return RefState(Relinquished, s, family);
103 static RefState getEscaped(const RefState *RS) {
104 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
107 void Profile(llvm::FoldingSetNodeID &ID) const {
110 ID.AddInteger(Family);
113 void dump(raw_ostream &OS) const {
114 switch (static_cast<Kind>(K)) {
115 #define CASE(ID) case ID: OS << #ID; break;
117 CASE(AllocatedOfSizeZero)
124 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
127 enum ReallocPairKind {
128 RPToBeFreedAfterFailure,
129 // The symbol has been freed when reallocation failed.
131 // The symbol does not need to be freed after reallocation fails.
132 RPDoNotTrackAfterFailure
135 /// \class ReallocPair
136 /// \brief Stores information about the symbol being reallocated by a call to
137 /// 'realloc' to allow modeling failed reallocation later in the path.
139 // \brief The symbol which realloc reallocated.
140 SymbolRef ReallocatedSym;
141 ReallocPairKind Kind;
143 ReallocPair(SymbolRef S, ReallocPairKind K) :
144 ReallocatedSym(S), Kind(K) {}
145 void Profile(llvm::FoldingSetNodeID &ID) const {
147 ID.AddPointer(ReallocatedSym);
149 bool operator==(const ReallocPair &X) const {
150 return ReallocatedSym == X.ReallocatedSym &&
155 typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
157 class MallocChecker : public Checker<check::DeadSymbols,
158 check::PointerEscape,
159 check::ConstPointerEscape,
160 check::PreStmt<ReturnStmt>,
162 check::PostStmt<CallExpr>,
163 check::PostStmt<CXXNewExpr>,
164 check::PreStmt<CXXDeleteExpr>,
165 check::PostStmt<BlockExpr>,
166 check::PostObjCMessage,
172 : II_alloca(nullptr), II_malloc(nullptr), II_free(nullptr),
173 II_realloc(nullptr), II_calloc(nullptr), II_valloc(nullptr),
174 II_reallocf(nullptr), II_strndup(nullptr), II_strdup(nullptr),
175 II_kmalloc(nullptr), II_if_nameindex(nullptr),
176 II_if_freenameindex(nullptr) {}
178 /// In pessimistic mode, the checker assumes that it does not know which
179 /// functions might free the memory.
183 CK_NewDeleteLeaksChecker,
184 CK_MismatchedDeallocatorChecker,
188 enum class MemoryOperationKind {
194 DefaultBool IsOptimistic;
196 DefaultBool ChecksEnabled[CK_NumCheckKinds];
197 CheckName CheckNames[CK_NumCheckKinds];
199 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
200 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
201 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
202 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
203 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
204 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
205 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
206 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
207 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
208 bool Assumption) const;
209 void checkLocation(SVal l, bool isLoad, const Stmt *S,
210 CheckerContext &C) const;
212 ProgramStateRef checkPointerEscape(ProgramStateRef State,
213 const InvalidatedSymbols &Escaped,
214 const CallEvent *Call,
215 PointerEscapeKind Kind) const;
216 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
217 const InvalidatedSymbols &Escaped,
218 const CallEvent *Call,
219 PointerEscapeKind Kind) const;
221 void printState(raw_ostream &Out, ProgramStateRef State,
222 const char *NL, const char *Sep) const override;
225 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
226 mutable std::unique_ptr<BugType> BT_DoubleDelete;
227 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
228 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
229 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
230 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
231 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
232 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
233 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
234 mutable IdentifierInfo *II_alloca, *II_malloc, *II_free, *II_realloc,
235 *II_calloc, *II_valloc, *II_reallocf, *II_strndup,
236 *II_strdup, *II_kmalloc, *II_if_nameindex,
237 *II_if_freenameindex;
238 mutable Optional<uint64_t> KernelZeroFlagVal;
240 void initIdentifierInfo(ASTContext &C) const;
242 /// \brief Determine family of a deallocation expression.
243 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
245 /// \brief Print names of allocators and deallocators.
247 /// \returns true on success.
248 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
249 const Expr *E) const;
251 /// \brief Print expected name of an allocator based on the deallocator's
252 /// family derived from the DeallocExpr.
253 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
254 const Expr *DeallocExpr) const;
255 /// \brief Print expected name of a deallocator based on the allocator's
257 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
260 /// Check if this is one of the functions which can allocate/reallocate memory
261 /// pointed to by one of its arguments.
262 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
263 bool isCMemFunction(const FunctionDecl *FD,
265 AllocationFamily Family,
266 MemoryOperationKind MemKind) const;
267 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
270 /// \brief Perform a zero-allocation check.
271 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
272 const unsigned AllocationSizeArg,
273 ProgramStateRef State) const;
275 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
277 const OwnershipAttr* Att,
278 ProgramStateRef State) const;
279 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
280 const Expr *SizeEx, SVal Init,
281 ProgramStateRef State,
282 AllocationFamily Family = AF_Malloc);
283 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
284 SVal SizeEx, SVal Init,
285 ProgramStateRef State,
286 AllocationFamily Family = AF_Malloc);
288 // Check if this malloc() for special flags. At present that means M_ZERO or
289 // __GFP_ZERO (in which case, treat it like calloc).
290 llvm::Optional<ProgramStateRef>
291 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
292 const ProgramStateRef &State) const;
294 /// Update the RefState to reflect the new memory allocation.
295 static ProgramStateRef
296 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
297 AllocationFamily Family = AF_Malloc);
299 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
300 const OwnershipAttr* Att,
301 ProgramStateRef State) const;
302 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
303 ProgramStateRef state, unsigned Num,
305 bool &ReleasedAllocated,
306 bool ReturnsNullOnFailure = false) const;
307 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
308 const Expr *ParentExpr,
309 ProgramStateRef State,
311 bool &ReleasedAllocated,
312 bool ReturnsNullOnFailure = false) const;
314 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
315 bool FreesMemOnFailure,
316 ProgramStateRef State) const;
317 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
318 ProgramStateRef State);
320 ///\brief Check if the memory associated with this symbol was released.
321 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
323 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
325 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
326 const Stmt *S) const;
328 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
330 /// Check if the function is known free memory, or if it is
331 /// "interesting" and should be modeled explicitly.
333 /// \param [out] EscapingSymbol A function might not free memory in general,
334 /// but could be known to free a particular symbol. In this case, false is
335 /// returned and the single escaping symbol is returned through the out
338 /// We assume that pointers do not escape through calls to system functions
339 /// not handled by this checker.
340 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
341 ProgramStateRef State,
342 SymbolRef &EscapingSymbol) const;
344 // Implementation of the checkPointerEscape callabcks.
345 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
346 const InvalidatedSymbols &Escaped,
347 const CallEvent *Call,
348 PointerEscapeKind Kind,
349 bool(*CheckRefState)(const RefState*)) const;
352 /// Tells if a given family/call/symbol is tracked by the current checker.
353 /// Sets CheckKind to the kind of the checker responsible for this
354 /// family/call/symbol.
355 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
356 bool IsALeakCheck = false) const;
357 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
358 const Stmt *AllocDeallocStmt,
359 bool IsALeakCheck = false) const;
360 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
361 bool IsALeakCheck = false) const;
363 static bool SummarizeValue(raw_ostream &os, SVal V);
364 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
365 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
366 const Expr *DeallocExpr) const;
367 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
368 SourceRange Range) const;
369 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
370 const Expr *DeallocExpr, const RefState *RS,
371 SymbolRef Sym, bool OwnershipTransferred) const;
372 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
373 const Expr *DeallocExpr,
374 const Expr *AllocExpr = nullptr) const;
375 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
376 SymbolRef Sym) const;
377 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
378 SymbolRef Sym, SymbolRef PrevSym) const;
380 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
382 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
383 SymbolRef Sym) const;
385 /// Find the location of the allocation for Sym on the path leading to the
387 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
388 CheckerContext &C) const;
390 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
392 /// The bug visitor which allows us to print extra diagnostics along the
393 /// BugReport path. For example, showing the allocation site of the leaked
395 class MallocBugVisitor final
396 : public BugReporterVisitorImpl<MallocBugVisitor> {
398 enum NotificationMode {
403 // The allocated region symbol tracked by the main analysis.
406 // The mode we are in, i.e. what kind of diagnostics will be emitted.
407 NotificationMode Mode;
409 // A symbol from when the primary region should have been reallocated.
410 SymbolRef FailedReallocSymbol;
415 MallocBugVisitor(SymbolRef S, bool isLeak = false)
416 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
418 void Profile(llvm::FoldingSetNodeID &ID) const override {
424 inline bool isAllocated(const RefState *S, const RefState *SPrev,
426 // Did not track -> allocated. Other state (released) -> allocated.
427 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
428 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
429 (!SPrev || !(SPrev->isAllocated() ||
430 SPrev->isAllocatedOfSizeZero())));
433 inline bool isReleased(const RefState *S, const RefState *SPrev,
435 // Did not track -> released. Other state (allocated) -> released.
436 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
437 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
440 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
442 // Did not track -> relinquished. Other state (allocated) -> relinquished.
443 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
444 isa<ObjCPropertyRefExpr>(Stmt)) &&
445 (S && S->isRelinquished()) &&
446 (!SPrev || !SPrev->isRelinquished()));
449 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
451 // If the expression is not a call, and the state change is
452 // released -> allocated, it must be the realloc return value
453 // check. If we have to handle more cases here, it might be cleaner just
454 // to track this extra bit in the state itself.
455 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
456 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
457 (SPrev && !(SPrev->isAllocated() ||
458 SPrev->isAllocatedOfSizeZero())));
461 PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
462 const ExplodedNode *PrevN,
463 BugReporterContext &BRC,
464 BugReport &BR) override;
466 std::unique_ptr<PathDiagnosticPiece>
467 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
468 BugReport &BR) override {
472 PathDiagnosticLocation L =
473 PathDiagnosticLocation::createEndOfPath(EndPathNode,
474 BRC.getSourceManager());
475 // Do not add the statement itself as a range in case of leak.
476 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
481 class StackHintGeneratorForReallocationFailed
482 : public StackHintGeneratorForSymbol {
484 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
485 : StackHintGeneratorForSymbol(S, M) {}
487 std::string getMessageForArg(const Expr *ArgE,
488 unsigned ArgIndex) override {
489 // Printed parameters start at 1, not 0.
492 SmallString<200> buf;
493 llvm::raw_svector_ostream os(buf);
495 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
496 << " parameter failed";
501 std::string getMessageForReturn(const CallExpr *CallExpr) override {
502 return "Reallocation of returned value failed";
507 } // end anonymous namespace
509 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
510 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
511 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
513 // A map from the freed symbol to the symbol representing the return value of
514 // the free function.
515 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
518 class StopTrackingCallback final : public SymbolVisitor {
519 ProgramStateRef state;
521 StopTrackingCallback(ProgramStateRef st) : state(st) {}
522 ProgramStateRef getState() const { return state; }
524 bool VisitSymbol(SymbolRef sym) override {
525 state = state->remove<RegionState>(sym);
529 } // end anonymous namespace
531 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
534 II_alloca = &Ctx.Idents.get("alloca");
535 II_malloc = &Ctx.Idents.get("malloc");
536 II_free = &Ctx.Idents.get("free");
537 II_realloc = &Ctx.Idents.get("realloc");
538 II_reallocf = &Ctx.Idents.get("reallocf");
539 II_calloc = &Ctx.Idents.get("calloc");
540 II_valloc = &Ctx.Idents.get("valloc");
541 II_strdup = &Ctx.Idents.get("strdup");
542 II_strndup = &Ctx.Idents.get("strndup");
543 II_kmalloc = &Ctx.Idents.get("kmalloc");
544 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
545 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
548 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
549 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
552 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
555 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
558 if (isStandardNewDelete(FD, C))
564 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
566 AllocationFamily Family,
567 MemoryOperationKind MemKind) const {
571 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
572 MemKind == MemoryOperationKind::MOK_Free);
573 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
574 MemKind == MemoryOperationKind::MOK_Allocate);
576 if (FD->getKind() == Decl::Function) {
577 const IdentifierInfo *FunI = FD->getIdentifier();
578 initIdentifierInfo(C);
580 if (Family == AF_Malloc && CheckFree) {
581 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf)
585 if (Family == AF_Malloc && CheckAlloc) {
586 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
587 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
588 FunI == II_strndup || FunI == II_kmalloc)
592 if (Family == AF_IfNameIndex && CheckFree) {
593 if (FunI == II_if_freenameindex)
597 if (Family == AF_IfNameIndex && CheckAlloc) {
598 if (FunI == II_if_nameindex)
602 if (Family == AF_Alloca && CheckAlloc) {
603 if (FunI == II_alloca)
608 if (Family != AF_Malloc)
611 if (IsOptimistic && FD->hasAttrs()) {
612 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
613 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
614 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
617 } else if (OwnKind == OwnershipAttr::Returns) {
627 // Tells if the callee is one of the following:
628 // 1) A global non-placement new/delete operator function.
629 // 2) A global placement operator function with the single placement argument
630 // of type std::nothrow_t.
631 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
632 ASTContext &C) const {
636 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
637 if (Kind != OO_New && Kind != OO_Array_New &&
638 Kind != OO_Delete && Kind != OO_Array_Delete)
641 // Skip all operator new/delete methods.
642 if (isa<CXXMethodDecl>(FD))
645 // Return true if tested operator is a standard placement nothrow operator.
646 if (FD->getNumParams() == 2) {
647 QualType T = FD->getParamDecl(1)->getType();
648 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
649 return II->getName().equals("nothrow_t");
652 // Skip placement operators.
653 if (FD->getNumParams() != 1 || FD->isVariadic())
656 // One of the standard new/new[]/delete/delete[] non-placement operators.
660 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
661 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
662 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
664 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
666 // One of the possible flags is M_ZERO, which means 'give me back an
667 // allocation which is already zeroed', like calloc.
669 // 2-argument kmalloc(), as used in the Linux kernel:
671 // void *kmalloc(size_t size, gfp_t flags);
673 // Has the similar flag value __GFP_ZERO.
675 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
676 // code could be shared.
678 ASTContext &Ctx = C.getASTContext();
679 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
681 if (!KernelZeroFlagVal.hasValue()) {
682 if (OS == llvm::Triple::FreeBSD)
683 KernelZeroFlagVal = 0x0100;
684 else if (OS == llvm::Triple::NetBSD)
685 KernelZeroFlagVal = 0x0002;
686 else if (OS == llvm::Triple::OpenBSD)
687 KernelZeroFlagVal = 0x0008;
688 else if (OS == llvm::Triple::Linux)
690 KernelZeroFlagVal = 0x8000;
692 // FIXME: We need a more general way of getting the M_ZERO value.
693 // See also: O_CREAT in UnixAPIChecker.cpp.
695 // Fall back to normal malloc behavior on platforms where we don't
700 // We treat the last argument as the flags argument, and callers fall-back to
701 // normal malloc on a None return. This works for the FreeBSD kernel malloc
702 // as well as Linux kmalloc.
703 if (CE->getNumArgs() < 2)
706 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
707 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
708 if (!V.getAs<NonLoc>()) {
709 // The case where 'V' can be a location can only be due to a bad header,
710 // so in this case bail out.
714 NonLoc Flags = V.castAs<NonLoc>();
715 NonLoc ZeroFlag = C.getSValBuilder()
716 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
718 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
721 if (MaskedFlagsUC.isUnknownOrUndef())
723 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
725 // Check if maskedFlags is non-zero.
726 ProgramStateRef TrueState, FalseState;
727 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
729 // If M_ZERO is set, treat this like calloc (initialized).
730 if (TrueState && !FalseState) {
731 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
732 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
738 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
742 const FunctionDecl *FD = C.getCalleeDecl(CE);
746 ProgramStateRef State = C.getState();
747 bool ReleasedAllocatedMemory = false;
749 if (FD->getKind() == Decl::Function) {
750 initIdentifierInfo(C.getASTContext());
751 IdentifierInfo *FunI = FD->getIdentifier();
753 if (FunI == II_malloc) {
754 if (CE->getNumArgs() < 1)
756 if (CE->getNumArgs() < 3) {
757 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
758 if (CE->getNumArgs() == 1)
759 State = ProcessZeroAllocation(C, CE, 0, State);
760 } else if (CE->getNumArgs() == 3) {
761 llvm::Optional<ProgramStateRef> MaybeState =
762 performKernelMalloc(CE, C, State);
763 if (MaybeState.hasValue())
764 State = MaybeState.getValue();
766 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
768 } else if (FunI == II_kmalloc) {
769 llvm::Optional<ProgramStateRef> MaybeState =
770 performKernelMalloc(CE, C, State);
771 if (MaybeState.hasValue())
772 State = MaybeState.getValue();
774 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
775 } else if (FunI == II_valloc) {
776 if (CE->getNumArgs() < 1)
778 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
779 State = ProcessZeroAllocation(C, CE, 0, State);
780 } else if (FunI == II_realloc) {
781 State = ReallocMem(C, CE, false, State);
782 State = ProcessZeroAllocation(C, CE, 1, State);
783 } else if (FunI == II_reallocf) {
784 State = ReallocMem(C, CE, true, State);
785 State = ProcessZeroAllocation(C, CE, 1, State);
786 } else if (FunI == II_calloc) {
787 State = CallocMem(C, CE, State);
788 State = ProcessZeroAllocation(C, CE, 0, State);
789 State = ProcessZeroAllocation(C, CE, 1, State);
790 } else if (FunI == II_free) {
791 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
792 } else if (FunI == II_strdup) {
793 State = MallocUpdateRefState(C, CE, State);
794 } else if (FunI == II_strndup) {
795 State = MallocUpdateRefState(C, CE, State);
796 } else if (FunI == II_alloca) {
797 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
799 State = ProcessZeroAllocation(C, CE, 0, State);
800 } else if (isStandardNewDelete(FD, C.getASTContext())) {
801 // Process direct calls to operator new/new[]/delete/delete[] functions
802 // as distinct from new/new[]/delete/delete[] expressions that are
803 // processed by the checkPostStmt callbacks for CXXNewExpr and
805 OverloadedOperatorKind K = FD->getOverloadedOperator();
807 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
809 State = ProcessZeroAllocation(C, CE, 0, State);
811 else if (K == OO_Array_New) {
812 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
814 State = ProcessZeroAllocation(C, CE, 0, State);
816 else if (K == OO_Delete || K == OO_Array_Delete)
817 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
819 llvm_unreachable("not a new/delete operator");
820 } else if (FunI == II_if_nameindex) {
821 // Should we model this differently? We can allocate a fixed number of
822 // elements with zeros in the last one.
823 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
825 } else if (FunI == II_if_freenameindex) {
826 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
830 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
831 // Check all the attributes, if there are any.
832 // There can be multiple of these attributes.
834 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
835 switch (I->getOwnKind()) {
836 case OwnershipAttr::Returns:
837 State = MallocMemReturnsAttr(C, CE, I, State);
839 case OwnershipAttr::Takes:
840 case OwnershipAttr::Holds:
841 State = FreeMemAttr(C, CE, I, State);
846 C.addTransition(State);
849 // Performs a 0-sized allocations check.
850 ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
852 const unsigned AllocationSizeArg,
853 ProgramStateRef State) const {
857 const Expr *Arg = nullptr;
859 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
860 Arg = CE->getArg(AllocationSizeArg);
862 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
864 Arg = NE->getArraySize();
869 llvm_unreachable("not a CallExpr or CXXNewExpr");
873 Optional<DefinedSVal> DefArgVal =
874 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
879 // Check if the allocation size is 0.
880 ProgramStateRef TrueState, FalseState;
881 SValBuilder &SvalBuilder = C.getSValBuilder();
883 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
885 std::tie(TrueState, FalseState) =
886 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
888 if (TrueState && !FalseState) {
889 SVal retVal = State->getSVal(E, C.getLocationContext());
890 SymbolRef Sym = retVal.getAsLocSymbol();
894 const RefState *RS = State->get<RegionState>(Sym);
896 if (RS->isAllocated())
897 return TrueState->set<RegionState>(Sym,
898 RefState::getAllocatedOfSizeZero(RS));
902 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
903 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
904 // tracked. Add zero-reallocated Sym to the state to catch references
905 // to zero-allocated memory.
906 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
910 // Assume the value is non-zero going forward.
915 static QualType getDeepPointeeType(QualType T) {
916 QualType Result = T, PointeeType = T->getPointeeType();
917 while (!PointeeType.isNull()) {
918 Result = PointeeType;
919 PointeeType = PointeeType->getPointeeType();
924 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
926 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
930 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
933 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
935 // Iterate over the constructor parameters.
936 for (const auto *CtorParam : CtorD->params()) {
938 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
939 if (CtorParamPointeeT.isNull())
942 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
944 if (CtorParamPointeeT->getAsCXXRecordDecl())
951 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
952 CheckerContext &C) const {
954 if (NE->getNumPlacementArgs())
955 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
956 E = NE->placement_arg_end(); I != E; ++I)
957 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
958 checkUseAfterFree(Sym, C, *I);
960 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
963 ParentMap &PM = C.getLocationContext()->getParentMap();
964 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
967 ProgramStateRef State = C.getState();
968 // The return value from operator new is bound to a specified initialization
969 // value (if any) and we don't want to loose this value. So we call
970 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
972 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
974 State = ProcessZeroAllocation(C, NE, 0, State);
975 C.addTransition(State);
978 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
979 CheckerContext &C) const {
981 if (!ChecksEnabled[CK_NewDeleteChecker])
982 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
983 checkUseAfterFree(Sym, C, DE->getArgument());
985 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
988 ProgramStateRef State = C.getState();
989 bool ReleasedAllocated;
990 State = FreeMemAux(C, DE->getArgument(), DE, State,
991 /*Hold*/false, ReleasedAllocated);
993 C.addTransition(State);
996 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
997 // If the first selector piece is one of the names below, assume that the
998 // object takes ownership of the memory, promising to eventually deallocate it
1000 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1001 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1002 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1003 return FirstSlot == "dataWithBytesNoCopy" ||
1004 FirstSlot == "initWithBytesNoCopy" ||
1005 FirstSlot == "initWithCharactersNoCopy";
1008 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1009 Selector S = Call.getSelector();
1011 // FIXME: We should not rely on fully-constrained symbols being folded.
1012 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1013 if (S.getNameForSlot(i).equals("freeWhenDone"))
1014 return !Call.getArgSVal(i).isZeroConstant();
1019 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1020 CheckerContext &C) const {
1024 if (!isKnownDeallocObjCMethodName(Call))
1027 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1031 bool ReleasedAllocatedMemory;
1032 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1033 Call.getOriginExpr(), C.getState(),
1034 /*Hold=*/true, ReleasedAllocatedMemory,
1035 /*RetNullOnFailure=*/true);
1037 C.addTransition(State);
1041 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1042 const OwnershipAttr *Att,
1043 ProgramStateRef State) const {
1047 if (Att->getModule() != II_malloc)
1050 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1052 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
1054 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1057 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1059 const Expr *SizeEx, SVal Init,
1060 ProgramStateRef State,
1061 AllocationFamily Family) {
1065 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1066 Init, State, Family);
1069 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1071 SVal Size, SVal Init,
1072 ProgramStateRef State,
1073 AllocationFamily Family) {
1077 // We expect the malloc functions to return a pointer.
1078 if (!Loc::isLocType(CE->getType()))
1081 // Bind the return value to the symbolic value from the heap region.
1082 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1083 // side effects other than what we model here.
1084 unsigned Count = C.blockCount();
1085 SValBuilder &svalBuilder = C.getSValBuilder();
1086 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1087 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1088 .castAs<DefinedSVal>();
1089 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1091 // Fill the region with the initialization value.
1092 State = State->bindDefault(RetVal, Init);
1094 // Set the region's extent equal to the Size parameter.
1095 const SymbolicRegion *R =
1096 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1099 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1100 Size.getAs<DefinedOrUnknownSVal>()) {
1101 SValBuilder &svalBuilder = C.getSValBuilder();
1102 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1103 DefinedOrUnknownSVal extentMatchesSize =
1104 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1106 State = State->assume(extentMatchesSize, true);
1110 return MallocUpdateRefState(C, CE, State, Family);
1113 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1115 ProgramStateRef State,
1116 AllocationFamily Family) {
1120 // Get the return value.
1121 SVal retVal = State->getSVal(E, C.getLocationContext());
1123 // We expect the malloc functions to return a pointer.
1124 if (!retVal.getAs<Loc>())
1127 SymbolRef Sym = retVal.getAsLocSymbol();
1130 // Set the symbol's state to Allocated.
1131 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1134 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1136 const OwnershipAttr *Att,
1137 ProgramStateRef State) const {
1141 if (Att->getModule() != II_malloc)
1144 bool ReleasedAllocated = false;
1146 for (const auto &Arg : Att->args()) {
1147 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1148 Att->getOwnKind() == OwnershipAttr::Holds,
1156 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1158 ProgramStateRef State,
1161 bool &ReleasedAllocated,
1162 bool ReturnsNullOnFailure) const {
1166 if (CE->getNumArgs() < (Num + 1))
1169 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1170 ReleasedAllocated, ReturnsNullOnFailure);
1173 /// Checks if the previous call to free on the given symbol failed - if free
1174 /// failed, returns true. Also, returns the corresponding return value symbol.
1175 static bool didPreviousFreeFail(ProgramStateRef State,
1176 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1177 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1179 assert(*Ret && "We should not store the null return symbol");
1180 ConstraintManager &CMgr = State->getConstraintManager();
1181 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1182 RetStatusSymbol = *Ret;
1183 return FreeFailed.isConstrainedTrue();
1188 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1189 const Stmt *S) const {
1193 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1194 const FunctionDecl *FD = C.getCalleeDecl(CE);
1197 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1199 ASTContext &Ctx = C.getASTContext();
1201 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1204 if (isStandardNewDelete(FD, Ctx)) {
1205 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1206 if (Kind == OO_New || Kind == OO_Delete)
1208 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1209 return AF_CXXNewArray;
1212 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1213 return AF_IfNameIndex;
1215 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1221 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1222 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1224 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1225 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1227 if (isa<ObjCMessageExpr>(S))
1233 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1234 const Expr *E) const {
1235 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1236 // FIXME: This doesn't handle indirect calls.
1237 const FunctionDecl *FD = CE->getDirectCallee();
1242 if (!FD->isOverloadedOperator())
1247 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1248 if (Msg->isInstanceMessage())
1252 Msg->getSelector().print(os);
1256 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1258 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1263 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1265 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1273 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1274 const Expr *E) const {
1275 AllocationFamily Family = getAllocationFamily(C, E);
1278 case AF_Malloc: os << "malloc()"; return;
1279 case AF_CXXNew: os << "'new'"; return;
1280 case AF_CXXNewArray: os << "'new[]'"; return;
1281 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1283 case AF_None: llvm_unreachable("not a deallocation expression");
1287 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1288 AllocationFamily Family) const {
1290 case AF_Malloc: os << "free()"; return;
1291 case AF_CXXNew: os << "'delete'"; return;
1292 case AF_CXXNewArray: os << "'delete[]'"; return;
1293 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1295 case AF_None: llvm_unreachable("suspicious argument");
1299 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1300 const Expr *ArgExpr,
1301 const Expr *ParentExpr,
1302 ProgramStateRef State,
1304 bool &ReleasedAllocated,
1305 bool ReturnsNullOnFailure) const {
1310 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1311 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1313 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1315 // Check for null dereferences.
1316 if (!location.getAs<Loc>())
1319 // The explicit NULL case, no operation is performed.
1320 ProgramStateRef notNullState, nullState;
1321 std::tie(notNullState, nullState) = State->assume(location);
1322 if (nullState && !notNullState)
1325 // Unknown values could easily be okay
1326 // Undefined values are handled elsewhere
1327 if (ArgVal.isUnknownOrUndef())
1330 const MemRegion *R = ArgVal.getAsRegion();
1332 // Nonlocs can't be freed, of course.
1333 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1335 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1339 R = R->StripCasts();
1341 // Blocks might show up as heap data, but should not be free()d
1342 if (isa<BlockDataRegion>(R)) {
1343 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1347 const MemSpaceRegion *MS = R->getMemorySpace();
1349 // Parameters, locals, statics, globals, and memory returned by
1350 // __builtin_alloca() shouldn't be freed.
1351 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1352 // FIXME: at the time this code was written, malloc() regions were
1353 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1354 // This means that there isn't actually anything from HeapSpaceRegion
1355 // that should be freed, even though we allow it here.
1356 // Of course, free() can work on memory allocated outside the current
1357 // function, so UnknownSpaceRegion is always a possibility.
1358 // False negatives are better than false positives.
1360 if (isa<AllocaRegion>(R))
1361 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1363 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1368 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1369 // Various cases could lead to non-symbol values here.
1370 // For now, ignore them.
1374 SymbolRef SymBase = SrBase->getSymbol();
1375 const RefState *RsBase = State->get<RegionState>(SymBase);
1376 SymbolRef PreviousRetStatusSymbol = nullptr;
1380 // Memory returned by alloca() shouldn't be freed.
1381 if (RsBase->getAllocationFamily() == AF_Alloca) {
1382 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1386 // Check for double free first.
1387 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1388 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1389 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1390 SymBase, PreviousRetStatusSymbol);
1393 // If the pointer is allocated or escaped, but we are now trying to free it,
1394 // check that the call to free is proper.
1395 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1396 RsBase->isEscaped()) {
1398 // Check if an expected deallocation function matches the real one.
1399 bool DeallocMatchesAlloc =
1400 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1401 if (!DeallocMatchesAlloc) {
1402 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1403 ParentExpr, RsBase, SymBase, Hold);
1407 // Check if the memory location being freed is the actual location
1408 // allocated, or an offset.
1409 RegionOffset Offset = R->getAsOffset();
1410 if (Offset.isValid() &&
1411 !Offset.hasSymbolicOffset() &&
1412 Offset.getOffset() != 0) {
1413 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1414 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1421 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1422 RsBase->isAllocatedOfSizeZero());
1424 // Clean out the info on previous call to free return info.
1425 State = State->remove<FreeReturnValue>(SymBase);
1427 // Keep track of the return value. If it is NULL, we will know that free
1429 if (ReturnsNullOnFailure) {
1430 SVal RetVal = C.getSVal(ParentExpr);
1431 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1432 if (RetStatusSymbol) {
1433 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1434 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1438 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1439 : getAllocationFamily(C, ParentExpr);
1442 return State->set<RegionState>(SymBase,
1443 RefState::getRelinquished(Family,
1446 return State->set<RegionState>(SymBase,
1447 RefState::getReleased(Family, ParentExpr));
1450 Optional<MallocChecker::CheckKind>
1451 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1452 bool IsALeakCheck) const {
1456 case AF_IfNameIndex: {
1457 if (ChecksEnabled[CK_MallocChecker])
1458 return CK_MallocChecker;
1460 return Optional<MallocChecker::CheckKind>();
1463 case AF_CXXNewArray: {
1465 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1466 return CK_NewDeleteLeaksChecker;
1469 if (ChecksEnabled[CK_NewDeleteChecker])
1470 return CK_NewDeleteChecker;
1472 return Optional<MallocChecker::CheckKind>();
1475 llvm_unreachable("no family");
1478 llvm_unreachable("unhandled family");
1481 Optional<MallocChecker::CheckKind>
1482 MallocChecker::getCheckIfTracked(CheckerContext &C,
1483 const Stmt *AllocDeallocStmt,
1484 bool IsALeakCheck) const {
1485 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1489 Optional<MallocChecker::CheckKind>
1490 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1491 bool IsALeakCheck) const {
1492 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1493 return CK_MallocChecker;
1495 const RefState *RS = C.getState()->get<RegionState>(Sym);
1497 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1500 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1501 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1502 os << "an integer (" << IntVal->getValue() << ")";
1503 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1504 os << "a constant address (" << ConstAddr->getValue() << ")";
1505 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1506 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1513 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1514 const MemRegion *MR) {
1515 switch (MR->getKind()) {
1516 case MemRegion::FunctionCodeRegionKind: {
1517 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1519 os << "the address of the function '" << *FD << '\'';
1521 os << "the address of a function";
1524 case MemRegion::BlockCodeRegionKind:
1527 case MemRegion::BlockDataRegionKind:
1528 // FIXME: where the block came from?
1532 const MemSpaceRegion *MS = MR->getMemorySpace();
1534 if (isa<StackLocalsSpaceRegion>(MS)) {
1535 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1543 os << "the address of the local variable '" << VD->getName() << "'";
1545 os << "the address of a local stack variable";
1549 if (isa<StackArgumentsSpaceRegion>(MS)) {
1550 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1558 os << "the address of the parameter '" << VD->getName() << "'";
1560 os << "the address of a parameter";
1564 if (isa<GlobalsSpaceRegion>(MS)) {
1565 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1573 if (VD->isStaticLocal())
1574 os << "the address of the static variable '" << VD->getName() << "'";
1576 os << "the address of the global variable '" << VD->getName() << "'";
1578 os << "the address of a global variable";
1587 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1589 const Expr *DeallocExpr) const {
1591 if (!ChecksEnabled[CK_MallocChecker] &&
1592 !ChecksEnabled[CK_NewDeleteChecker])
1595 Optional<MallocChecker::CheckKind> CheckKind =
1596 getCheckIfTracked(C, DeallocExpr);
1597 if (!CheckKind.hasValue())
1600 if (ExplodedNode *N = C.generateErrorNode()) {
1601 if (!BT_BadFree[*CheckKind])
1602 BT_BadFree[*CheckKind].reset(
1603 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1605 SmallString<100> buf;
1606 llvm::raw_svector_ostream os(buf);
1608 const MemRegion *MR = ArgVal.getAsRegion();
1609 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1610 MR = ER->getSuperRegion();
1612 os << "Argument to ";
1613 if (!printAllocDeallocName(os, C, DeallocExpr))
1614 os << "deallocator";
1617 bool Summarized = MR ? SummarizeRegion(os, MR)
1618 : SummarizeValue(os, ArgVal);
1620 os << ", which is not memory allocated by ";
1622 os << "not memory allocated by ";
1624 printExpectedAllocName(os, C, DeallocExpr);
1626 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1627 R->markInteresting(MR);
1629 C.emitReport(std::move(R));
1633 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1634 SourceRange Range) const {
1636 Optional<MallocChecker::CheckKind> CheckKind;
1638 if (ChecksEnabled[CK_MallocChecker])
1639 CheckKind = CK_MallocChecker;
1640 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1641 CheckKind = CK_MismatchedDeallocatorChecker;
1645 if (ExplodedNode *N = C.generateErrorNode()) {
1646 if (!BT_FreeAlloca[*CheckKind])
1647 BT_FreeAlloca[*CheckKind].reset(
1648 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1650 auto R = llvm::make_unique<BugReport>(
1651 *BT_FreeAlloca[*CheckKind],
1652 "Memory allocated by alloca() should not be deallocated", N);
1653 R->markInteresting(ArgVal.getAsRegion());
1655 C.emitReport(std::move(R));
1659 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1661 const Expr *DeallocExpr,
1664 bool OwnershipTransferred) const {
1666 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1669 if (ExplodedNode *N = C.generateErrorNode()) {
1670 if (!BT_MismatchedDealloc)
1671 BT_MismatchedDealloc.reset(
1672 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1673 "Bad deallocator", "Memory Error"));
1675 SmallString<100> buf;
1676 llvm::raw_svector_ostream os(buf);
1678 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1679 SmallString<20> AllocBuf;
1680 llvm::raw_svector_ostream AllocOs(AllocBuf);
1681 SmallString<20> DeallocBuf;
1682 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1684 if (OwnershipTransferred) {
1685 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1686 os << DeallocOs.str() << " cannot";
1690 os << " take ownership of memory";
1692 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1693 os << " allocated by " << AllocOs.str();
1696 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1697 os << " allocated by " << AllocOs.str();
1699 os << " should be deallocated by ";
1700 printExpectedDeallocName(os, RS->getAllocationFamily());
1702 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1703 os << ", not " << DeallocOs.str();
1706 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1707 R->markInteresting(Sym);
1709 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1710 C.emitReport(std::move(R));
1714 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1715 SourceRange Range, const Expr *DeallocExpr,
1716 const Expr *AllocExpr) const {
1719 if (!ChecksEnabled[CK_MallocChecker] &&
1720 !ChecksEnabled[CK_NewDeleteChecker])
1723 Optional<MallocChecker::CheckKind> CheckKind =
1724 getCheckIfTracked(C, AllocExpr);
1725 if (!CheckKind.hasValue())
1728 ExplodedNode *N = C.generateErrorNode();
1732 if (!BT_OffsetFree[*CheckKind])
1733 BT_OffsetFree[*CheckKind].reset(
1734 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1736 SmallString<100> buf;
1737 llvm::raw_svector_ostream os(buf);
1738 SmallString<20> AllocNameBuf;
1739 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1741 const MemRegion *MR = ArgVal.getAsRegion();
1742 assert(MR && "Only MemRegion based symbols can have offset free errors");
1744 RegionOffset Offset = MR->getAsOffset();
1745 assert((Offset.isValid() &&
1746 !Offset.hasSymbolicOffset() &&
1747 Offset.getOffset() != 0) &&
1748 "Only symbols with a valid offset can have offset free errors");
1750 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1752 os << "Argument to ";
1753 if (!printAllocDeallocName(os, C, DeallocExpr))
1754 os << "deallocator";
1755 os << " is offset by "
1758 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1759 << " from the start of ";
1760 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1761 os << "memory allocated by " << AllocNameOs.str();
1763 os << "allocated memory";
1765 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1766 R->markInteresting(MR->getBaseRegion());
1768 C.emitReport(std::move(R));
1771 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1772 SymbolRef Sym) const {
1774 if (!ChecksEnabled[CK_MallocChecker] &&
1775 !ChecksEnabled[CK_NewDeleteChecker])
1778 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1779 if (!CheckKind.hasValue())
1782 if (ExplodedNode *N = C.generateErrorNode()) {
1783 if (!BT_UseFree[*CheckKind])
1784 BT_UseFree[*CheckKind].reset(new BugType(
1785 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1787 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1788 "Use of memory after it is freed", N);
1790 R->markInteresting(Sym);
1792 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1793 C.emitReport(std::move(R));
1797 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1798 bool Released, SymbolRef Sym,
1799 SymbolRef PrevSym) const {
1801 if (!ChecksEnabled[CK_MallocChecker] &&
1802 !ChecksEnabled[CK_NewDeleteChecker])
1805 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1806 if (!CheckKind.hasValue())
1809 if (ExplodedNode *N = C.generateErrorNode()) {
1810 if (!BT_DoubleFree[*CheckKind])
1811 BT_DoubleFree[*CheckKind].reset(
1812 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1814 auto R = llvm::make_unique<BugReport>(
1815 *BT_DoubleFree[*CheckKind],
1816 (Released ? "Attempt to free released memory"
1817 : "Attempt to free non-owned memory"),
1820 R->markInteresting(Sym);
1822 R->markInteresting(PrevSym);
1823 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1824 C.emitReport(std::move(R));
1828 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1830 if (!ChecksEnabled[CK_NewDeleteChecker])
1833 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1834 if (!CheckKind.hasValue())
1837 if (ExplodedNode *N = C.generateErrorNode()) {
1838 if (!BT_DoubleDelete)
1839 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1840 "Double delete", "Memory Error"));
1842 auto R = llvm::make_unique<BugReport>(
1843 *BT_DoubleDelete, "Attempt to delete released memory", N);
1845 R->markInteresting(Sym);
1846 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1847 C.emitReport(std::move(R));
1851 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1853 SymbolRef Sym) const {
1855 if (!ChecksEnabled[CK_MallocChecker] &&
1856 !ChecksEnabled[CK_NewDeleteChecker])
1859 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1861 if (!CheckKind.hasValue())
1864 if (ExplodedNode *N = C.generateErrorNode()) {
1865 if (!BT_UseZerroAllocated[*CheckKind])
1866 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1867 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1869 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1870 "Use of zero-allocated memory", N);
1874 R->markInteresting(Sym);
1875 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1877 C.emitReport(std::move(R));
1881 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1884 ProgramStateRef State) const {
1888 if (CE->getNumArgs() < 2)
1891 const Expr *arg0Expr = CE->getArg(0);
1892 const LocationContext *LCtx = C.getLocationContext();
1893 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
1894 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
1896 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
1898 SValBuilder &svalBuilder = C.getSValBuilder();
1900 DefinedOrUnknownSVal PtrEQ =
1901 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
1903 // Get the size argument. If there is no size arg then give up.
1904 const Expr *Arg1 = CE->getArg(1);
1908 // Get the value of the size argument.
1909 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
1910 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
1912 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
1914 // Compare the size argument to 0.
1915 DefinedOrUnknownSVal SizeZero =
1916 svalBuilder.evalEQ(State, Arg1Val,
1917 svalBuilder.makeIntValWithPtrWidth(0, false));
1919 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
1920 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
1921 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
1922 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
1923 // We only assume exceptional states if they are definitely true; if the
1924 // state is under-constrained, assume regular realloc behavior.
1925 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
1926 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
1928 // If the ptr is NULL and the size is not 0, the call is equivalent to
1930 if ( PrtIsNull && !SizeIsZero) {
1931 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
1932 UndefinedVal(), StatePtrIsNull);
1936 if (PrtIsNull && SizeIsZero)
1939 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
1941 SymbolRef FromPtr = arg0Val.getAsSymbol();
1942 SVal RetVal = State->getSVal(CE, LCtx);
1943 SymbolRef ToPtr = RetVal.getAsSymbol();
1944 if (!FromPtr || !ToPtr)
1947 bool ReleasedAllocated = false;
1949 // If the size is 0, free the memory.
1951 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
1952 false, ReleasedAllocated)){
1953 // The semantics of the return value are:
1954 // If size was equal to 0, either NULL or a pointer suitable to be passed
1955 // to free() is returned. We just free the input pointer and do not add
1956 // any constrains on the output pointer.
1960 // Default behavior.
1961 if (ProgramStateRef stateFree =
1962 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
1964 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
1965 UnknownVal(), stateFree);
1969 ReallocPairKind Kind = RPToBeFreedAfterFailure;
1971 Kind = RPIsFreeOnFailure;
1972 else if (!ReleasedAllocated)
1973 Kind = RPDoNotTrackAfterFailure;
1975 // Record the info about the reallocated symbol so that we could properly
1976 // process failed reallocation.
1977 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
1978 ReallocPair(FromPtr, Kind));
1979 // The reallocated symbol should stay alive for as long as the new symbol.
1980 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
1981 return stateRealloc;
1986 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
1987 ProgramStateRef State) {
1991 if (CE->getNumArgs() < 2)
1994 SValBuilder &svalBuilder = C.getSValBuilder();
1995 const LocationContext *LCtx = C.getLocationContext();
1996 SVal count = State->getSVal(CE->getArg(0), LCtx);
1997 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
1998 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
1999 svalBuilder.getContext().getSizeType());
2000 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2002 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2006 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2007 CheckerContext &C) const {
2008 const LocationContext *LeakContext = N->getLocationContext();
2009 // Walk the ExplodedGraph backwards and find the first node that referred to
2010 // the tracked symbol.
2011 const ExplodedNode *AllocNode = N;
2012 const MemRegion *ReferenceRegion = nullptr;
2015 ProgramStateRef State = N->getState();
2016 if (!State->get<RegionState>(Sym))
2019 // Find the most recent expression bound to the symbol in the current
2021 if (!ReferenceRegion) {
2022 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2023 SVal Val = State->getSVal(MR);
2024 if (Val.getAsLocSymbol() == Sym) {
2025 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2026 // Do not show local variables belonging to a function other than
2027 // where the error is reported.
2029 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2030 ReferenceRegion = MR;
2035 // Allocation node, is the last node in the current or parent context in
2036 // which the symbol was tracked.
2037 const LocationContext *NContext = N->getLocationContext();
2038 if (NContext == LeakContext ||
2039 NContext->isParentOf(LeakContext))
2041 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2044 return LeakInfo(AllocNode, ReferenceRegion);
2047 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2048 CheckerContext &C) const {
2050 if (!ChecksEnabled[CK_MallocChecker] &&
2051 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2054 const RefState *RS = C.getState()->get<RegionState>(Sym);
2055 assert(RS && "cannot leak an untracked symbol");
2056 AllocationFamily Family = RS->getAllocationFamily();
2058 if (Family == AF_Alloca)
2061 Optional<MallocChecker::CheckKind>
2062 CheckKind = getCheckIfTracked(Family, true);
2064 if (!CheckKind.hasValue())
2068 if (!BT_Leak[*CheckKind]) {
2069 BT_Leak[*CheckKind].reset(
2070 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
2071 // Leaks should not be reported if they are post-dominated by a sink:
2072 // (1) Sinks are higher importance bugs.
2073 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2074 // with __noreturn functions such as assert() or exit(). We choose not
2075 // to report leaks on such paths.
2076 BT_Leak[*CheckKind]->setSuppressOnSink(true);
2079 // Most bug reports are cached at the location where they occurred.
2080 // With leaks, we want to unique them by the location where they were
2081 // allocated, and only report a single path.
2082 PathDiagnosticLocation LocUsedForUniqueing;
2083 const ExplodedNode *AllocNode = nullptr;
2084 const MemRegion *Region = nullptr;
2085 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2087 ProgramPoint P = AllocNode->getLocation();
2088 const Stmt *AllocationStmt = nullptr;
2089 if (Optional<CallExitEnd> Exit = P.getAs<CallExitEnd>())
2090 AllocationStmt = Exit->getCalleeContext()->getCallSite();
2091 else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>())
2092 AllocationStmt = SP->getStmt();
2094 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2095 C.getSourceManager(),
2096 AllocNode->getLocationContext());
2098 SmallString<200> buf;
2099 llvm::raw_svector_ostream os(buf);
2100 if (Region && Region->canPrintPretty()) {
2101 os << "Potential leak of memory pointed to by ";
2102 Region->printPretty(os);
2104 os << "Potential memory leak";
2107 auto R = llvm::make_unique<BugReport>(
2108 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2109 AllocNode->getLocationContext()->getDecl());
2110 R->markInteresting(Sym);
2111 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2112 C.emitReport(std::move(R));
2115 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2116 CheckerContext &C) const
2118 if (!SymReaper.hasDeadSymbols())
2121 ProgramStateRef state = C.getState();
2122 RegionStateTy RS = state->get<RegionState>();
2123 RegionStateTy::Factory &F = state->get_context<RegionState>();
2125 SmallVector<SymbolRef, 2> Errors;
2126 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2127 if (SymReaper.isDead(I->first)) {
2128 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2129 Errors.push_back(I->first);
2130 // Remove the dead symbol from the map.
2131 RS = F.remove(RS, I->first);
2136 // Cleanup the Realloc Pairs Map.
2137 ReallocPairsTy RP = state->get<ReallocPairs>();
2138 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2139 if (SymReaper.isDead(I->first) ||
2140 SymReaper.isDead(I->second.ReallocatedSym)) {
2141 state = state->remove<ReallocPairs>(I->first);
2145 // Cleanup the FreeReturnValue Map.
2146 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2147 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2148 if (SymReaper.isDead(I->first) ||
2149 SymReaper.isDead(I->second)) {
2150 state = state->remove<FreeReturnValue>(I->first);
2154 // Generate leak node.
2155 ExplodedNode *N = C.getPredecessor();
2156 if (!Errors.empty()) {
2157 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2158 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2160 for (SmallVectorImpl<SymbolRef>::iterator
2161 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2162 reportLeak(*I, N, C);
2167 C.addTransition(state->set<RegionState>(RS), N);
2170 void MallocChecker::checkPreCall(const CallEvent &Call,
2171 CheckerContext &C) const {
2173 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2174 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2175 if (!Sym || checkDoubleDelete(Sym, C))
2179 // We will check for double free in the post visit.
2180 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2181 const FunctionDecl *FD = FC->getDecl();
2185 ASTContext &Ctx = C.getASTContext();
2186 if (ChecksEnabled[CK_MallocChecker] &&
2187 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2188 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2189 MemoryOperationKind::MOK_Free)))
2192 if (ChecksEnabled[CK_NewDeleteChecker] &&
2193 isStandardNewDelete(FD, Ctx))
2197 // Check if the callee of a method is deleted.
2198 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2199 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2200 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2204 // Check arguments for being used after free.
2205 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2206 SVal ArgSVal = Call.getArgSVal(I);
2207 if (ArgSVal.getAs<Loc>()) {
2208 SymbolRef Sym = ArgSVal.getAsSymbol();
2211 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2217 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2218 const Expr *E = S->getRetValue();
2222 // Check if we are returning a symbol.
2223 ProgramStateRef State = C.getState();
2224 SVal RetVal = State->getSVal(E, C.getLocationContext());
2225 SymbolRef Sym = RetVal.getAsSymbol();
2227 // If we are returning a field of the allocated struct or an array element,
2228 // the callee could still free the memory.
2229 // TODO: This logic should be a part of generic symbol escape callback.
2230 if (const MemRegion *MR = RetVal.getAsRegion())
2231 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2232 if (const SymbolicRegion *BMR =
2233 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2234 Sym = BMR->getSymbol();
2236 // Check if we are returning freed memory.
2238 checkUseAfterFree(Sym, C, E);
2241 // TODO: Blocks should be either inlined or should call invalidate regions
2242 // upon invocation. After that's in place, special casing here will not be
2244 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2245 CheckerContext &C) const {
2247 // Scan the BlockDecRefExprs for any object the retain count checker
2249 if (!BE->getBlockDecl()->hasCaptures())
2252 ProgramStateRef state = C.getState();
2253 const BlockDataRegion *R =
2254 cast<BlockDataRegion>(state->getSVal(BE,
2255 C.getLocationContext()).getAsRegion());
2257 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2258 E = R->referenced_vars_end();
2263 SmallVector<const MemRegion*, 10> Regions;
2264 const LocationContext *LC = C.getLocationContext();
2265 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2267 for ( ; I != E; ++I) {
2268 const VarRegion *VR = I.getCapturedRegion();
2269 if (VR->getSuperRegion() == R) {
2270 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2272 Regions.push_back(VR);
2276 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2277 Regions.data() + Regions.size()).getState();
2278 C.addTransition(state);
2281 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2283 const RefState *RS = C.getState()->get<RegionState>(Sym);
2284 return (RS && RS->isReleased());
2287 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2288 const Stmt *S) const {
2290 if (isReleased(Sym, C)) {
2291 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2298 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2299 const Stmt *S) const {
2302 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2303 if (RS->isAllocatedOfSizeZero())
2304 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2306 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2307 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2311 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2313 if (isReleased(Sym, C)) {
2314 ReportDoubleDelete(C, Sym);
2320 // Check if the location is a freed symbolic region.
2321 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2322 CheckerContext &C) const {
2323 SymbolRef Sym = l.getLocSymbolInBase();
2325 checkUseAfterFree(Sym, C, S);
2326 checkUseZeroAllocated(Sym, C, S);
2330 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2331 // it - assuming that allocation failed on this path.
2332 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2334 bool Assumption) const {
2335 RegionStateTy RS = state->get<RegionState>();
2336 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2337 // If the symbol is assumed to be NULL, remove it from consideration.
2338 ConstraintManager &CMgr = state->getConstraintManager();
2339 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2340 if (AllocFailed.isConstrainedTrue())
2341 state = state->remove<RegionState>(I.getKey());
2344 // Realloc returns 0 when reallocation fails, which means that we should
2345 // restore the state of the pointer being reallocated.
2346 ReallocPairsTy RP = state->get<ReallocPairs>();
2347 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2348 // If the symbol is assumed to be NULL, remove it from consideration.
2349 ConstraintManager &CMgr = state->getConstraintManager();
2350 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2351 if (!AllocFailed.isConstrainedTrue())
2354 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2355 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2356 if (RS->isReleased()) {
2357 if (I.getData().Kind == RPToBeFreedAfterFailure)
2358 state = state->set<RegionState>(ReallocSym,
2359 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2360 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2361 state = state->remove<RegionState>(ReallocSym);
2363 assert(I.getData().Kind == RPIsFreeOnFailure);
2366 state = state->remove<ReallocPairs>(I.getKey());
2372 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2373 const CallEvent *Call,
2374 ProgramStateRef State,
2375 SymbolRef &EscapingSymbol) const {
2377 EscapingSymbol = nullptr;
2379 // For now, assume that any C++ or block call can free memory.
2380 // TODO: If we want to be more optimistic here, we'll need to make sure that
2381 // regions escape to C++ containers. They seem to do that even now, but for
2382 // mysterious reasons.
2383 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2386 // Check Objective-C messages by selector name.
2387 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2388 // If it's not a framework call, or if it takes a callback, assume it
2390 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2393 // If it's a method we know about, handle it explicitly post-call.
2394 // This should happen before the "freeWhenDone" check below.
2395 if (isKnownDeallocObjCMethodName(*Msg))
2398 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2399 // about, we can't be sure that the object will use free() to deallocate the
2400 // memory, so we can't model it explicitly. The best we can do is use it to
2401 // decide whether the pointer escapes.
2402 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2403 return *FreeWhenDone;
2405 // If the first selector piece ends with "NoCopy", and there is no
2406 // "freeWhenDone" parameter set to zero, we know ownership is being
2407 // transferred. Again, though, we can't be sure that the object will use
2408 // free() to deallocate the memory, so we can't model it explicitly.
2409 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2410 if (FirstSlot.endswith("NoCopy"))
2413 // If the first selector starts with addPointer, insertPointer,
2414 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2415 // This is similar to C++ containers (vector); we still might want to check
2416 // that the pointers get freed by following the container itself.
2417 if (FirstSlot.startswith("addPointer") ||
2418 FirstSlot.startswith("insertPointer") ||
2419 FirstSlot.startswith("replacePointer") ||
2420 FirstSlot.equals("valueWithPointer")) {
2424 // We should escape receiver on call to 'init'. This is especially relevant
2425 // to the receiver, as the corresponding symbol is usually not referenced
2427 if (Msg->getMethodFamily() == OMF_init) {
2428 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2432 // Otherwise, assume that the method does not free memory.
2433 // Most framework methods do not free memory.
2437 // At this point the only thing left to handle is straight function calls.
2438 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2442 ASTContext &ASTC = State->getStateManager().getContext();
2444 // If it's one of the allocation functions we can reason about, we model
2445 // its behavior explicitly.
2446 if (isMemFunction(FD, ASTC))
2449 // If it's not a system call, assume it frees memory.
2450 if (!Call->isInSystemHeader())
2453 // White list the system functions whose arguments escape.
2454 const IdentifierInfo *II = FD->getIdentifier();
2457 StringRef FName = II->getName();
2459 // White list the 'XXXNoCopy' CoreFoundation functions.
2460 // We specifically check these before
2461 if (FName.endswith("NoCopy")) {
2462 // Look for the deallocator argument. We know that the memory ownership
2463 // is not transferred only if the deallocator argument is
2464 // 'kCFAllocatorNull'.
2465 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2466 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2467 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2468 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2469 if (DeallocatorName == "kCFAllocatorNull")
2476 // Associating streams with malloced buffers. The pointer can escape if
2477 // 'closefn' is specified (and if that function does free memory),
2478 // but it will not if closefn is not specified.
2479 // Currently, we do not inspect the 'closefn' function (PR12101).
2480 if (FName == "funopen")
2481 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2484 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2485 // these leaks might be intentional when setting the buffer for stdio.
2486 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2487 if (FName == "setbuf" || FName =="setbuffer" ||
2488 FName == "setlinebuf" || FName == "setvbuf") {
2489 if (Call->getNumArgs() >= 1) {
2490 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2491 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2492 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2493 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2498 // A bunch of other functions which either take ownership of a pointer or
2499 // wrap the result up in a struct or object, meaning it can be freed later.
2500 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2501 // but the Malloc checker cannot differentiate between them. The right way
2502 // of doing this would be to implement a pointer escapes callback.
2503 if (FName == "CGBitmapContextCreate" ||
2504 FName == "CGBitmapContextCreateWithData" ||
2505 FName == "CVPixelBufferCreateWithBytes" ||
2506 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2507 FName == "OSAtomicEnqueue") {
2511 if (FName == "postEvent" &&
2512 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2516 if (FName == "postEvent" &&
2517 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2521 // Handle cases where we know a buffer's /address/ can escape.
2522 // Note that the above checks handle some special cases where we know that
2523 // even though the address escapes, it's still our responsibility to free the
2525 if (Call->argumentsMayEscape())
2528 // Otherwise, assume that the function does not free memory.
2529 // Most system calls do not free the memory.
2533 static bool retTrue(const RefState *RS) {
2537 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2538 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2539 RS->getAllocationFamily() == AF_CXXNew);
2542 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2543 const InvalidatedSymbols &Escaped,
2544 const CallEvent *Call,
2545 PointerEscapeKind Kind) const {
2546 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2549 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2550 const InvalidatedSymbols &Escaped,
2551 const CallEvent *Call,
2552 PointerEscapeKind Kind) const {
2553 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2554 &checkIfNewOrNewArrayFamily);
2557 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2558 const InvalidatedSymbols &Escaped,
2559 const CallEvent *Call,
2560 PointerEscapeKind Kind,
2561 bool(*CheckRefState)(const RefState*)) const {
2562 // If we know that the call does not free memory, or we want to process the
2563 // call later, keep tracking the top level arguments.
2564 SymbolRef EscapingSymbol = nullptr;
2565 if (Kind == PSK_DirectEscapeOnCall &&
2566 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2572 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2577 if (EscapingSymbol && EscapingSymbol != sym)
2580 if (const RefState *RS = State->get<RegionState>(sym)) {
2581 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2582 CheckRefState(RS)) {
2583 State = State->remove<RegionState>(sym);
2584 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2591 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2592 ProgramStateRef prevState) {
2593 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2594 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2596 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2598 SymbolRef sym = I.getKey();
2599 if (!currMap.lookup(sym))
2606 PathDiagnosticPiece *
2607 MallocChecker::MallocBugVisitor::VisitNode(const ExplodedNode *N,
2608 const ExplodedNode *PrevN,
2609 BugReporterContext &BRC,
2611 ProgramStateRef state = N->getState();
2612 ProgramStateRef statePrev = PrevN->getState();
2614 const RefState *RS = state->get<RegionState>(Sym);
2615 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2619 const Stmt *S = nullptr;
2620 const char *Msg = nullptr;
2621 StackHintGeneratorForSymbol *StackHint = nullptr;
2623 // Retrieve the associated statement.
2624 ProgramPoint ProgLoc = N->getLocation();
2625 if (Optional<StmtPoint> SP = ProgLoc.getAs<StmtPoint>()) {
2627 } else if (Optional<CallExitEnd> Exit = ProgLoc.getAs<CallExitEnd>()) {
2628 S = Exit->getCalleeContext()->getCallSite();
2629 } else if (Optional<BlockEdge> Edge = ProgLoc.getAs<BlockEdge>()) {
2630 // If an assumption was made on a branch, it should be caught
2631 // here by looking at the state transition.
2632 S = Edge->getSrc()->getTerminator();
2638 // FIXME: We will eventually need to handle non-statement-based events
2639 // (__attribute__((cleanup))).
2641 // Find out if this is an interesting point and what is the kind.
2642 if (Mode == Normal) {
2643 if (isAllocated(RS, RSPrev, S)) {
2644 Msg = "Memory is allocated";
2645 StackHint = new StackHintGeneratorForSymbol(Sym,
2646 "Returned allocated memory");
2647 } else if (isReleased(RS, RSPrev, S)) {
2648 Msg = "Memory is released";
2649 StackHint = new StackHintGeneratorForSymbol(Sym,
2650 "Returning; memory was released");
2651 } else if (isRelinquished(RS, RSPrev, S)) {
2652 Msg = "Memory ownership is transferred";
2653 StackHint = new StackHintGeneratorForSymbol(Sym, "");
2654 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2655 Mode = ReallocationFailed;
2656 Msg = "Reallocation failed";
2657 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2658 "Reallocation failed");
2660 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2661 // Is it possible to fail two reallocs WITHOUT testing in between?
2662 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2663 "We only support one failed realloc at a time.");
2664 BR.markInteresting(sym);
2665 FailedReallocSymbol = sym;
2669 // We are in a special mode if a reallocation failed later in the path.
2670 } else if (Mode == ReallocationFailed) {
2671 assert(FailedReallocSymbol && "No symbol to look for.");
2673 // Is this is the first appearance of the reallocated symbol?
2674 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2675 // We're at the reallocation point.
2676 Msg = "Attempt to reallocate memory";
2677 StackHint = new StackHintGeneratorForSymbol(Sym,
2678 "Returned reallocated memory");
2679 FailedReallocSymbol = nullptr;
2688 // Generate the extra diagnostic.
2689 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2690 N->getLocationContext());
2691 return new PathDiagnosticEventPiece(Pos, Msg, true, StackHint);
2694 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2695 const char *NL, const char *Sep) const {
2697 RegionStateTy RS = State->get<RegionState>();
2699 if (!RS.isEmpty()) {
2700 Out << Sep << "MallocChecker :" << NL;
2701 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2702 const RefState *RefS = State->get<RegionState>(I.getKey());
2703 AllocationFamily Family = RefS->getAllocationFamily();
2704 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2705 if (!CheckKind.hasValue())
2706 CheckKind = getCheckIfTracked(Family, true);
2708 I.getKey()->dumpToStream(Out);
2710 I.getData().dump(Out);
2711 if (CheckKind.hasValue())
2712 Out << " (" << CheckNames[*CheckKind].getName() << ")";
2718 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2719 registerCStringCheckerBasic(mgr);
2720 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2721 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2722 "Optimistic", false, checker);
2723 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2724 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2725 mgr.getCurrentCheckName();
2726 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2728 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2729 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2732 #define REGISTER_CHECKER(name) \
2733 void ento::register##name(CheckerManager &mgr) { \
2734 registerCStringCheckerBasic(mgr); \
2735 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2736 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2737 "Optimistic", false, checker); \
2738 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2739 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2742 REGISTER_CHECKER(MallocChecker)
2743 REGISTER_CHECKER(NewDeleteChecker)
2744 REGISTER_CHECKER(MismatchedDeallocatorChecker)