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/STLExtras.h"
30 #include "llvm/ADT/SmallString.h"
31 #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_win_alloca(nullptr), II_malloc(nullptr),
173 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
174 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
175 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
176 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
177 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
178 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
179 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
180 II_g_free(nullptr), II_g_memdup(nullptr) {}
182 /// In pessimistic mode, the checker assumes that it does not know which
183 /// functions might free the memory.
187 CK_NewDeleteLeaksChecker,
188 CK_MismatchedDeallocatorChecker,
192 enum class MemoryOperationKind {
198 DefaultBool IsOptimistic;
200 DefaultBool ChecksEnabled[CK_NumCheckKinds];
201 CheckName CheckNames[CK_NumCheckKinds];
203 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
204 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
205 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
206 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
207 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
208 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
209 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
210 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
211 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
212 bool Assumption) const;
213 void checkLocation(SVal l, bool isLoad, const Stmt *S,
214 CheckerContext &C) const;
216 ProgramStateRef checkPointerEscape(ProgramStateRef State,
217 const InvalidatedSymbols &Escaped,
218 const CallEvent *Call,
219 PointerEscapeKind Kind) const;
220 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
221 const InvalidatedSymbols &Escaped,
222 const CallEvent *Call,
223 PointerEscapeKind Kind) const;
225 void printState(raw_ostream &Out, ProgramStateRef State,
226 const char *NL, const char *Sep) const override;
229 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
230 mutable std::unique_ptr<BugType> BT_DoubleDelete;
231 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
232 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
233 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
234 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
235 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
236 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
237 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
238 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
239 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
240 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
241 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
242 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
243 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
244 *II_g_try_realloc, *II_g_free, *II_g_memdup;
245 mutable Optional<uint64_t> KernelZeroFlagVal;
247 void initIdentifierInfo(ASTContext &C) const;
249 /// \brief Determine family of a deallocation expression.
250 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
252 /// \brief Print names of allocators and deallocators.
254 /// \returns true on success.
255 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
256 const Expr *E) const;
258 /// \brief Print expected name of an allocator based on the deallocator's
259 /// family derived from the DeallocExpr.
260 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
261 const Expr *DeallocExpr) const;
262 /// \brief Print expected name of a deallocator based on the allocator's
264 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
267 /// Check if this is one of the functions which can allocate/reallocate memory
268 /// pointed to by one of its arguments.
269 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
270 bool isCMemFunction(const FunctionDecl *FD,
272 AllocationFamily Family,
273 MemoryOperationKind MemKind) const;
274 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
277 /// \brief Perform a zero-allocation check.
278 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
279 const unsigned AllocationSizeArg,
280 ProgramStateRef State) const;
282 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
284 const OwnershipAttr* Att,
285 ProgramStateRef State) const;
286 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
287 const Expr *SizeEx, SVal Init,
288 ProgramStateRef State,
289 AllocationFamily Family = AF_Malloc);
290 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
291 SVal SizeEx, SVal Init,
292 ProgramStateRef State,
293 AllocationFamily Family = AF_Malloc);
295 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
296 ProgramStateRef State);
298 // Check if this malloc() for special flags. At present that means M_ZERO or
299 // __GFP_ZERO (in which case, treat it like calloc).
300 llvm::Optional<ProgramStateRef>
301 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
302 const ProgramStateRef &State) const;
304 /// Update the RefState to reflect the new memory allocation.
305 static ProgramStateRef
306 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
307 AllocationFamily Family = AF_Malloc);
309 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
310 const OwnershipAttr* Att,
311 ProgramStateRef State) const;
312 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
313 ProgramStateRef state, unsigned Num,
315 bool &ReleasedAllocated,
316 bool ReturnsNullOnFailure = false) const;
317 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
318 const Expr *ParentExpr,
319 ProgramStateRef State,
321 bool &ReleasedAllocated,
322 bool ReturnsNullOnFailure = false) const;
324 ProgramStateRef ReallocMem(CheckerContext &C, const CallExpr *CE,
325 bool FreesMemOnFailure,
326 ProgramStateRef State) const;
327 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
328 ProgramStateRef State);
330 ///\brief Check if the memory associated with this symbol was released.
331 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
333 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
335 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
336 const Stmt *S) const;
338 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
340 /// Check if the function is known free memory, or if it is
341 /// "interesting" and should be modeled explicitly.
343 /// \param [out] EscapingSymbol A function might not free memory in general,
344 /// but could be known to free a particular symbol. In this case, false is
345 /// returned and the single escaping symbol is returned through the out
348 /// We assume that pointers do not escape through calls to system functions
349 /// not handled by this checker.
350 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
351 ProgramStateRef State,
352 SymbolRef &EscapingSymbol) const;
354 // Implementation of the checkPointerEscape callabcks.
355 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
356 const InvalidatedSymbols &Escaped,
357 const CallEvent *Call,
358 PointerEscapeKind Kind,
359 bool(*CheckRefState)(const RefState*)) const;
362 /// Tells if a given family/call/symbol is tracked by the current checker.
363 /// Sets CheckKind to the kind of the checker responsible for this
364 /// family/call/symbol.
365 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
366 bool IsALeakCheck = false) const;
367 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
368 const Stmt *AllocDeallocStmt,
369 bool IsALeakCheck = false) const;
370 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
371 bool IsALeakCheck = false) const;
373 static bool SummarizeValue(raw_ostream &os, SVal V);
374 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
375 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
376 const Expr *DeallocExpr) const;
377 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
378 SourceRange Range) const;
379 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
380 const Expr *DeallocExpr, const RefState *RS,
381 SymbolRef Sym, bool OwnershipTransferred) const;
382 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
383 const Expr *DeallocExpr,
384 const Expr *AllocExpr = nullptr) const;
385 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
386 SymbolRef Sym) const;
387 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
388 SymbolRef Sym, SymbolRef PrevSym) const;
390 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
392 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
393 SymbolRef Sym) const;
395 /// Find the location of the allocation for Sym on the path leading to the
397 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
398 CheckerContext &C) const;
400 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
402 /// The bug visitor which allows us to print extra diagnostics along the
403 /// BugReport path. For example, showing the allocation site of the leaked
405 class MallocBugVisitor final
406 : public BugReporterVisitorImpl<MallocBugVisitor> {
408 enum NotificationMode {
413 // The allocated region symbol tracked by the main analysis.
416 // The mode we are in, i.e. what kind of diagnostics will be emitted.
417 NotificationMode Mode;
419 // A symbol from when the primary region should have been reallocated.
420 SymbolRef FailedReallocSymbol;
425 MallocBugVisitor(SymbolRef S, bool isLeak = false)
426 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
428 void Profile(llvm::FoldingSetNodeID &ID) const override {
434 inline bool isAllocated(const RefState *S, const RefState *SPrev,
436 // Did not track -> allocated. Other state (released) -> allocated.
437 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
438 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
439 (!SPrev || !(SPrev->isAllocated() ||
440 SPrev->isAllocatedOfSizeZero())));
443 inline bool isReleased(const RefState *S, const RefState *SPrev,
445 // Did not track -> released. Other state (allocated) -> released.
446 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
447 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
450 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
452 // Did not track -> relinquished. Other state (allocated) -> relinquished.
453 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
454 isa<ObjCPropertyRefExpr>(Stmt)) &&
455 (S && S->isRelinquished()) &&
456 (!SPrev || !SPrev->isRelinquished()));
459 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
461 // If the expression is not a call, and the state change is
462 // released -> allocated, it must be the realloc return value
463 // check. If we have to handle more cases here, it might be cleaner just
464 // to track this extra bit in the state itself.
465 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
466 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
467 (SPrev && !(SPrev->isAllocated() ||
468 SPrev->isAllocatedOfSizeZero())));
471 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
472 const ExplodedNode *PrevN,
473 BugReporterContext &BRC,
474 BugReport &BR) override;
476 std::unique_ptr<PathDiagnosticPiece>
477 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
478 BugReport &BR) override {
482 PathDiagnosticLocation L =
483 PathDiagnosticLocation::createEndOfPath(EndPathNode,
484 BRC.getSourceManager());
485 // Do not add the statement itself as a range in case of leak.
486 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
491 class StackHintGeneratorForReallocationFailed
492 : public StackHintGeneratorForSymbol {
494 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
495 : StackHintGeneratorForSymbol(S, M) {}
497 std::string getMessageForArg(const Expr *ArgE,
498 unsigned ArgIndex) override {
499 // Printed parameters start at 1, not 0.
502 SmallString<200> buf;
503 llvm::raw_svector_ostream os(buf);
505 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
506 << " parameter failed";
511 std::string getMessageForReturn(const CallExpr *CallExpr) override {
512 return "Reallocation of returned value failed";
517 } // end anonymous namespace
519 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
520 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
521 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
523 // A map from the freed symbol to the symbol representing the return value of
524 // the free function.
525 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
528 class StopTrackingCallback final : public SymbolVisitor {
529 ProgramStateRef state;
531 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
532 ProgramStateRef getState() const { return state; }
534 bool VisitSymbol(SymbolRef sym) override {
535 state = state->remove<RegionState>(sym);
539 } // end anonymous namespace
541 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
544 II_alloca = &Ctx.Idents.get("alloca");
545 II_malloc = &Ctx.Idents.get("malloc");
546 II_free = &Ctx.Idents.get("free");
547 II_realloc = &Ctx.Idents.get("realloc");
548 II_reallocf = &Ctx.Idents.get("reallocf");
549 II_calloc = &Ctx.Idents.get("calloc");
550 II_valloc = &Ctx.Idents.get("valloc");
551 II_strdup = &Ctx.Idents.get("strdup");
552 II_strndup = &Ctx.Idents.get("strndup");
553 II_wcsdup = &Ctx.Idents.get("wcsdup");
554 II_kmalloc = &Ctx.Idents.get("kmalloc");
555 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
556 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
558 //MSVC uses `_`-prefixed instead, so we check for them too.
559 II_win_strdup = &Ctx.Idents.get("_strdup");
560 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
561 II_win_alloca = &Ctx.Idents.get("_alloca");
564 II_g_malloc = &Ctx.Idents.get("g_malloc");
565 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
566 II_g_realloc = &Ctx.Idents.get("g_realloc");
567 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
568 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
569 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
570 II_g_free = &Ctx.Idents.get("g_free");
571 II_g_memdup = &Ctx.Idents.get("g_memdup");
574 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
575 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
578 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
581 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
584 if (isStandardNewDelete(FD, C))
590 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
592 AllocationFamily Family,
593 MemoryOperationKind MemKind) const {
597 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
598 MemKind == MemoryOperationKind::MOK_Free);
599 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
600 MemKind == MemoryOperationKind::MOK_Allocate);
602 if (FD->getKind() == Decl::Function) {
603 const IdentifierInfo *FunI = FD->getIdentifier();
604 initIdentifierInfo(C);
606 if (Family == AF_Malloc && CheckFree) {
607 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
612 if (Family == AF_Malloc && CheckAlloc) {
613 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
614 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
615 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
616 FunI == II_win_wcsdup || FunI == II_kmalloc ||
617 FunI == II_g_malloc || FunI == II_g_malloc0 ||
618 FunI == II_g_realloc || FunI == II_g_try_malloc ||
619 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
624 if (Family == AF_IfNameIndex && CheckFree) {
625 if (FunI == II_if_freenameindex)
629 if (Family == AF_IfNameIndex && CheckAlloc) {
630 if (FunI == II_if_nameindex)
634 if (Family == AF_Alloca && CheckAlloc) {
635 if (FunI == II_alloca || FunI == II_win_alloca)
640 if (Family != AF_Malloc)
643 if (IsOptimistic && FD->hasAttrs()) {
644 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
645 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
646 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
649 } else if (OwnKind == OwnershipAttr::Returns) {
659 // Tells if the callee is one of the following:
660 // 1) A global non-placement new/delete operator function.
661 // 2) A global placement operator function with the single placement argument
662 // of type std::nothrow_t.
663 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
664 ASTContext &C) const {
668 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
669 if (Kind != OO_New && Kind != OO_Array_New &&
670 Kind != OO_Delete && Kind != OO_Array_Delete)
673 // Skip all operator new/delete methods.
674 if (isa<CXXMethodDecl>(FD))
677 // Return true if tested operator is a standard placement nothrow operator.
678 if (FD->getNumParams() == 2) {
679 QualType T = FD->getParamDecl(1)->getType();
680 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
681 return II->getName().equals("nothrow_t");
684 // Skip placement operators.
685 if (FD->getNumParams() != 1 || FD->isVariadic())
688 // One of the standard new/new[]/delete/delete[] non-placement operators.
692 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
693 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
694 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
696 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
698 // One of the possible flags is M_ZERO, which means 'give me back an
699 // allocation which is already zeroed', like calloc.
701 // 2-argument kmalloc(), as used in the Linux kernel:
703 // void *kmalloc(size_t size, gfp_t flags);
705 // Has the similar flag value __GFP_ZERO.
707 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
708 // code could be shared.
710 ASTContext &Ctx = C.getASTContext();
711 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
713 if (!KernelZeroFlagVal.hasValue()) {
714 if (OS == llvm::Triple::FreeBSD)
715 KernelZeroFlagVal = 0x0100;
716 else if (OS == llvm::Triple::NetBSD)
717 KernelZeroFlagVal = 0x0002;
718 else if (OS == llvm::Triple::OpenBSD)
719 KernelZeroFlagVal = 0x0008;
720 else if (OS == llvm::Triple::Linux)
722 KernelZeroFlagVal = 0x8000;
724 // FIXME: We need a more general way of getting the M_ZERO value.
725 // See also: O_CREAT in UnixAPIChecker.cpp.
727 // Fall back to normal malloc behavior on platforms where we don't
732 // We treat the last argument as the flags argument, and callers fall-back to
733 // normal malloc on a None return. This works for the FreeBSD kernel malloc
734 // as well as Linux kmalloc.
735 if (CE->getNumArgs() < 2)
738 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
739 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
740 if (!V.getAs<NonLoc>()) {
741 // The case where 'V' can be a location can only be due to a bad header,
742 // so in this case bail out.
746 NonLoc Flags = V.castAs<NonLoc>();
747 NonLoc ZeroFlag = C.getSValBuilder()
748 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
750 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
753 if (MaskedFlagsUC.isUnknownOrUndef())
755 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
757 // Check if maskedFlags is non-zero.
758 ProgramStateRef TrueState, FalseState;
759 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
761 // If M_ZERO is set, treat this like calloc (initialized).
762 if (TrueState && !FalseState) {
763 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
764 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
770 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
774 const FunctionDecl *FD = C.getCalleeDecl(CE);
778 ProgramStateRef State = C.getState();
779 bool ReleasedAllocatedMemory = false;
781 if (FD->getKind() == Decl::Function) {
782 initIdentifierInfo(C.getASTContext());
783 IdentifierInfo *FunI = FD->getIdentifier();
785 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
786 if (CE->getNumArgs() < 1)
788 if (CE->getNumArgs() < 3) {
789 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
790 if (CE->getNumArgs() == 1)
791 State = ProcessZeroAllocation(C, CE, 0, State);
792 } else if (CE->getNumArgs() == 3) {
793 llvm::Optional<ProgramStateRef> MaybeState =
794 performKernelMalloc(CE, C, State);
795 if (MaybeState.hasValue())
796 State = MaybeState.getValue();
798 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
800 } else if (FunI == II_kmalloc) {
801 if (CE->getNumArgs() < 1)
803 llvm::Optional<ProgramStateRef> MaybeState =
804 performKernelMalloc(CE, C, State);
805 if (MaybeState.hasValue())
806 State = MaybeState.getValue();
808 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
809 } else if (FunI == II_valloc) {
810 if (CE->getNumArgs() < 1)
812 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
813 State = ProcessZeroAllocation(C, CE, 0, State);
814 } else if (FunI == II_realloc || FunI == II_g_realloc ||
815 FunI == II_g_try_realloc) {
816 State = ReallocMem(C, CE, false, State);
817 State = ProcessZeroAllocation(C, CE, 1, State);
818 } else if (FunI == II_reallocf) {
819 State = ReallocMem(C, CE, true, State);
820 State = ProcessZeroAllocation(C, CE, 1, State);
821 } else if (FunI == II_calloc) {
822 State = CallocMem(C, CE, State);
823 State = ProcessZeroAllocation(C, CE, 0, State);
824 State = ProcessZeroAllocation(C, CE, 1, State);
825 } else if (FunI == II_free || FunI == II_g_free) {
826 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
827 } else if (FunI == II_strdup || FunI == II_win_strdup ||
828 FunI == II_wcsdup || FunI == II_win_wcsdup) {
829 State = MallocUpdateRefState(C, CE, State);
830 } else if (FunI == II_strndup) {
831 State = MallocUpdateRefState(C, CE, State);
832 } else if (FunI == II_alloca || FunI == II_win_alloca) {
833 if (CE->getNumArgs() < 1)
835 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
837 State = ProcessZeroAllocation(C, CE, 0, State);
838 } else if (isStandardNewDelete(FD, C.getASTContext())) {
839 // Process direct calls to operator new/new[]/delete/delete[] functions
840 // as distinct from new/new[]/delete/delete[] expressions that are
841 // processed by the checkPostStmt callbacks for CXXNewExpr and
843 OverloadedOperatorKind K = FD->getOverloadedOperator();
845 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
847 State = ProcessZeroAllocation(C, CE, 0, State);
849 else if (K == OO_Array_New) {
850 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
852 State = ProcessZeroAllocation(C, CE, 0, State);
854 else if (K == OO_Delete || K == OO_Array_Delete)
855 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
857 llvm_unreachable("not a new/delete operator");
858 } else if (FunI == II_if_nameindex) {
859 // Should we model this differently? We can allocate a fixed number of
860 // elements with zeros in the last one.
861 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
863 } else if (FunI == II_if_freenameindex) {
864 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
865 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
866 if (CE->getNumArgs() < 1)
868 SValBuilder &svalBuilder = C.getSValBuilder();
869 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
870 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
871 State = ProcessZeroAllocation(C, CE, 0, State);
872 } else if (FunI == II_g_memdup) {
873 if (CE->getNumArgs() < 2)
875 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
876 State = ProcessZeroAllocation(C, CE, 1, State);
880 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
881 // Check all the attributes, if there are any.
882 // There can be multiple of these attributes.
884 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
885 switch (I->getOwnKind()) {
886 case OwnershipAttr::Returns:
887 State = MallocMemReturnsAttr(C, CE, I, State);
889 case OwnershipAttr::Takes:
890 case OwnershipAttr::Holds:
891 State = FreeMemAttr(C, CE, I, State);
896 C.addTransition(State);
899 // Performs a 0-sized allocations check.
900 ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
902 const unsigned AllocationSizeArg,
903 ProgramStateRef State) const {
907 const Expr *Arg = nullptr;
909 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
910 Arg = CE->getArg(AllocationSizeArg);
912 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
914 Arg = NE->getArraySize();
919 llvm_unreachable("not a CallExpr or CXXNewExpr");
923 Optional<DefinedSVal> DefArgVal =
924 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
929 // Check if the allocation size is 0.
930 ProgramStateRef TrueState, FalseState;
931 SValBuilder &SvalBuilder = C.getSValBuilder();
933 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
935 std::tie(TrueState, FalseState) =
936 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
938 if (TrueState && !FalseState) {
939 SVal retVal = State->getSVal(E, C.getLocationContext());
940 SymbolRef Sym = retVal.getAsLocSymbol();
944 const RefState *RS = State->get<RegionState>(Sym);
946 if (RS->isAllocated())
947 return TrueState->set<RegionState>(Sym,
948 RefState::getAllocatedOfSizeZero(RS));
952 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
953 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
954 // tracked. Add zero-reallocated Sym to the state to catch references
955 // to zero-allocated memory.
956 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
960 // Assume the value is non-zero going forward.
965 static QualType getDeepPointeeType(QualType T) {
966 QualType Result = T, PointeeType = T->getPointeeType();
967 while (!PointeeType.isNull()) {
968 Result = PointeeType;
969 PointeeType = PointeeType->getPointeeType();
974 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
976 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
980 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
983 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
985 // Iterate over the constructor parameters.
986 for (const auto *CtorParam : CtorD->parameters()) {
988 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
989 if (CtorParamPointeeT.isNull())
992 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
994 if (CtorParamPointeeT->getAsCXXRecordDecl())
1001 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1002 CheckerContext &C) const {
1004 if (NE->getNumPlacementArgs())
1005 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1006 E = NE->placement_arg_end(); I != E; ++I)
1007 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1008 checkUseAfterFree(Sym, C, *I);
1010 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1013 ParentMap &PM = C.getLocationContext()->getParentMap();
1014 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1017 ProgramStateRef State = C.getState();
1018 // The return value from operator new is bound to a specified initialization
1019 // value (if any) and we don't want to loose this value. So we call
1020 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
1021 // existing binding.
1022 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
1024 State = addExtentSize(C, NE, State);
1025 State = ProcessZeroAllocation(C, NE, 0, State);
1026 C.addTransition(State);
1029 // Sets the extent value of the MemRegion allocated by
1030 // new expression NE to its size in Bytes.
1032 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1033 const CXXNewExpr *NE,
1034 ProgramStateRef State) {
1037 SValBuilder &svalBuilder = C.getSValBuilder();
1039 const LocationContext *LCtx = C.getLocationContext();
1040 const SubRegion *Region;
1041 if (NE->isArray()) {
1042 const Expr *SizeExpr = NE->getArraySize();
1043 ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1044 // Store the extent size for the (symbolic)region
1045 // containing the elements.
1046 Region = (State->getSVal(NE, LCtx))
1048 ->getAs<SubRegion>()
1050 ->getAs<SubRegion>();
1052 ElementCount = svalBuilder.makeIntVal(1, true);
1053 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1057 // Set the region's extent equal to the Size in Bytes.
1058 QualType ElementType = NE->getAllocatedType();
1059 ASTContext &AstContext = C.getASTContext();
1060 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1062 if (ElementCount.getAs<NonLoc>()) {
1063 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1064 // size in Bytes = ElementCount*TypeSize
1065 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1066 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1067 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1068 svalBuilder.getArrayIndexType());
1069 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1070 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1071 State = State->assume(extentMatchesSize, true);
1076 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1077 CheckerContext &C) const {
1079 if (!ChecksEnabled[CK_NewDeleteChecker])
1080 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1081 checkUseAfterFree(Sym, C, DE->getArgument());
1083 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1086 ProgramStateRef State = C.getState();
1087 bool ReleasedAllocated;
1088 State = FreeMemAux(C, DE->getArgument(), DE, State,
1089 /*Hold*/false, ReleasedAllocated);
1091 C.addTransition(State);
1094 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1095 // If the first selector piece is one of the names below, assume that the
1096 // object takes ownership of the memory, promising to eventually deallocate it
1098 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1099 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1100 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1101 return FirstSlot == "dataWithBytesNoCopy" ||
1102 FirstSlot == "initWithBytesNoCopy" ||
1103 FirstSlot == "initWithCharactersNoCopy";
1106 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1107 Selector S = Call.getSelector();
1109 // FIXME: We should not rely on fully-constrained symbols being folded.
1110 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1111 if (S.getNameForSlot(i).equals("freeWhenDone"))
1112 return !Call.getArgSVal(i).isZeroConstant();
1117 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1118 CheckerContext &C) const {
1122 if (!isKnownDeallocObjCMethodName(Call))
1125 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1129 bool ReleasedAllocatedMemory;
1130 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1131 Call.getOriginExpr(), C.getState(),
1132 /*Hold=*/true, ReleasedAllocatedMemory,
1133 /*RetNullOnFailure=*/true);
1135 C.addTransition(State);
1139 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1140 const OwnershipAttr *Att,
1141 ProgramStateRef State) const {
1145 if (Att->getModule() != II_malloc)
1148 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1150 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
1152 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1155 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1157 const Expr *SizeEx, SVal Init,
1158 ProgramStateRef State,
1159 AllocationFamily Family) {
1163 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1164 Init, State, Family);
1167 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1169 SVal Size, SVal Init,
1170 ProgramStateRef State,
1171 AllocationFamily Family) {
1175 // We expect the malloc functions to return a pointer.
1176 if (!Loc::isLocType(CE->getType()))
1179 // Bind the return value to the symbolic value from the heap region.
1180 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1181 // side effects other than what we model here.
1182 unsigned Count = C.blockCount();
1183 SValBuilder &svalBuilder = C.getSValBuilder();
1184 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1185 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1186 .castAs<DefinedSVal>();
1187 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1189 // Fill the region with the initialization value.
1190 State = State->bindDefault(RetVal, Init, LCtx);
1192 // Set the region's extent equal to the Size parameter.
1193 const SymbolicRegion *R =
1194 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1197 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1198 Size.getAs<DefinedOrUnknownSVal>()) {
1199 SValBuilder &svalBuilder = C.getSValBuilder();
1200 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1201 DefinedOrUnknownSVal extentMatchesSize =
1202 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1204 State = State->assume(extentMatchesSize, true);
1208 return MallocUpdateRefState(C, CE, State, Family);
1211 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1213 ProgramStateRef State,
1214 AllocationFamily Family) {
1218 // Get the return value.
1219 SVal retVal = State->getSVal(E, C.getLocationContext());
1221 // We expect the malloc functions to return a pointer.
1222 if (!retVal.getAs<Loc>())
1225 SymbolRef Sym = retVal.getAsLocSymbol();
1228 // Set the symbol's state to Allocated.
1229 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1232 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1234 const OwnershipAttr *Att,
1235 ProgramStateRef State) const {
1239 if (Att->getModule() != II_malloc)
1242 bool ReleasedAllocated = false;
1244 for (const auto &Arg : Att->args()) {
1245 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1246 Att->getOwnKind() == OwnershipAttr::Holds,
1254 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1256 ProgramStateRef State,
1259 bool &ReleasedAllocated,
1260 bool ReturnsNullOnFailure) const {
1264 if (CE->getNumArgs() < (Num + 1))
1267 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1268 ReleasedAllocated, ReturnsNullOnFailure);
1271 /// Checks if the previous call to free on the given symbol failed - if free
1272 /// failed, returns true. Also, returns the corresponding return value symbol.
1273 static bool didPreviousFreeFail(ProgramStateRef State,
1274 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1275 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1277 assert(*Ret && "We should not store the null return symbol");
1278 ConstraintManager &CMgr = State->getConstraintManager();
1279 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1280 RetStatusSymbol = *Ret;
1281 return FreeFailed.isConstrainedTrue();
1286 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1287 const Stmt *S) const {
1291 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1292 const FunctionDecl *FD = C.getCalleeDecl(CE);
1295 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1297 ASTContext &Ctx = C.getASTContext();
1299 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1302 if (isStandardNewDelete(FD, Ctx)) {
1303 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1304 if (Kind == OO_New || Kind == OO_Delete)
1306 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1307 return AF_CXXNewArray;
1310 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1311 return AF_IfNameIndex;
1313 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1319 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1320 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1322 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1323 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1325 if (isa<ObjCMessageExpr>(S))
1331 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1332 const Expr *E) const {
1333 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1334 // FIXME: This doesn't handle indirect calls.
1335 const FunctionDecl *FD = CE->getDirectCallee();
1340 if (!FD->isOverloadedOperator())
1345 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1346 if (Msg->isInstanceMessage())
1350 Msg->getSelector().print(os);
1354 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1356 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1361 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1363 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1371 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1372 const Expr *E) const {
1373 AllocationFamily Family = getAllocationFamily(C, E);
1376 case AF_Malloc: os << "malloc()"; return;
1377 case AF_CXXNew: os << "'new'"; return;
1378 case AF_CXXNewArray: os << "'new[]'"; return;
1379 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1381 case AF_None: llvm_unreachable("not a deallocation expression");
1385 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1386 AllocationFamily Family) const {
1388 case AF_Malloc: os << "free()"; return;
1389 case AF_CXXNew: os << "'delete'"; return;
1390 case AF_CXXNewArray: os << "'delete[]'"; return;
1391 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1393 case AF_None: llvm_unreachable("suspicious argument");
1397 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1398 const Expr *ArgExpr,
1399 const Expr *ParentExpr,
1400 ProgramStateRef State,
1402 bool &ReleasedAllocated,
1403 bool ReturnsNullOnFailure) const {
1408 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1409 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1411 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1413 // Check for null dereferences.
1414 if (!location.getAs<Loc>())
1417 // The explicit NULL case, no operation is performed.
1418 ProgramStateRef notNullState, nullState;
1419 std::tie(notNullState, nullState) = State->assume(location);
1420 if (nullState && !notNullState)
1423 // Unknown values could easily be okay
1424 // Undefined values are handled elsewhere
1425 if (ArgVal.isUnknownOrUndef())
1428 const MemRegion *R = ArgVal.getAsRegion();
1430 // Nonlocs can't be freed, of course.
1431 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1433 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1437 R = R->StripCasts();
1439 // Blocks might show up as heap data, but should not be free()d
1440 if (isa<BlockDataRegion>(R)) {
1441 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1445 const MemSpaceRegion *MS = R->getMemorySpace();
1447 // Parameters, locals, statics, globals, and memory returned by
1448 // __builtin_alloca() shouldn't be freed.
1449 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1450 // FIXME: at the time this code was written, malloc() regions were
1451 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1452 // This means that there isn't actually anything from HeapSpaceRegion
1453 // that should be freed, even though we allow it here.
1454 // Of course, free() can work on memory allocated outside the current
1455 // function, so UnknownSpaceRegion is always a possibility.
1456 // False negatives are better than false positives.
1458 if (isa<AllocaRegion>(R))
1459 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1461 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1466 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1467 // Various cases could lead to non-symbol values here.
1468 // For now, ignore them.
1472 SymbolRef SymBase = SrBase->getSymbol();
1473 const RefState *RsBase = State->get<RegionState>(SymBase);
1474 SymbolRef PreviousRetStatusSymbol = nullptr;
1478 // Memory returned by alloca() shouldn't be freed.
1479 if (RsBase->getAllocationFamily() == AF_Alloca) {
1480 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1484 // Check for double free first.
1485 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1486 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1487 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1488 SymBase, PreviousRetStatusSymbol);
1491 // If the pointer is allocated or escaped, but we are now trying to free it,
1492 // check that the call to free is proper.
1493 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1494 RsBase->isEscaped()) {
1496 // Check if an expected deallocation function matches the real one.
1497 bool DeallocMatchesAlloc =
1498 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1499 if (!DeallocMatchesAlloc) {
1500 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1501 ParentExpr, RsBase, SymBase, Hold);
1505 // Check if the memory location being freed is the actual location
1506 // allocated, or an offset.
1507 RegionOffset Offset = R->getAsOffset();
1508 if (Offset.isValid() &&
1509 !Offset.hasSymbolicOffset() &&
1510 Offset.getOffset() != 0) {
1511 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1512 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1519 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1520 RsBase->isAllocatedOfSizeZero());
1522 // Clean out the info on previous call to free return info.
1523 State = State->remove<FreeReturnValue>(SymBase);
1525 // Keep track of the return value. If it is NULL, we will know that free
1527 if (ReturnsNullOnFailure) {
1528 SVal RetVal = C.getSVal(ParentExpr);
1529 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1530 if (RetStatusSymbol) {
1531 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1532 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1536 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1537 : getAllocationFamily(C, ParentExpr);
1540 return State->set<RegionState>(SymBase,
1541 RefState::getRelinquished(Family,
1544 return State->set<RegionState>(SymBase,
1545 RefState::getReleased(Family, ParentExpr));
1548 Optional<MallocChecker::CheckKind>
1549 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1550 bool IsALeakCheck) const {
1554 case AF_IfNameIndex: {
1555 if (ChecksEnabled[CK_MallocChecker])
1556 return CK_MallocChecker;
1558 return Optional<MallocChecker::CheckKind>();
1561 case AF_CXXNewArray: {
1563 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1564 return CK_NewDeleteLeaksChecker;
1567 if (ChecksEnabled[CK_NewDeleteChecker])
1568 return CK_NewDeleteChecker;
1570 return Optional<MallocChecker::CheckKind>();
1573 llvm_unreachable("no family");
1576 llvm_unreachable("unhandled family");
1579 Optional<MallocChecker::CheckKind>
1580 MallocChecker::getCheckIfTracked(CheckerContext &C,
1581 const Stmt *AllocDeallocStmt,
1582 bool IsALeakCheck) const {
1583 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1587 Optional<MallocChecker::CheckKind>
1588 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1589 bool IsALeakCheck) const {
1590 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1591 return CK_MallocChecker;
1593 const RefState *RS = C.getState()->get<RegionState>(Sym);
1595 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1598 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1599 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1600 os << "an integer (" << IntVal->getValue() << ")";
1601 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1602 os << "a constant address (" << ConstAddr->getValue() << ")";
1603 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1604 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1611 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1612 const MemRegion *MR) {
1613 switch (MR->getKind()) {
1614 case MemRegion::FunctionCodeRegionKind: {
1615 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1617 os << "the address of the function '" << *FD << '\'';
1619 os << "the address of a function";
1622 case MemRegion::BlockCodeRegionKind:
1625 case MemRegion::BlockDataRegionKind:
1626 // FIXME: where the block came from?
1630 const MemSpaceRegion *MS = MR->getMemorySpace();
1632 if (isa<StackLocalsSpaceRegion>(MS)) {
1633 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1641 os << "the address of the local variable '" << VD->getName() << "'";
1643 os << "the address of a local stack variable";
1647 if (isa<StackArgumentsSpaceRegion>(MS)) {
1648 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1656 os << "the address of the parameter '" << VD->getName() << "'";
1658 os << "the address of a parameter";
1662 if (isa<GlobalsSpaceRegion>(MS)) {
1663 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1671 if (VD->isStaticLocal())
1672 os << "the address of the static variable '" << VD->getName() << "'";
1674 os << "the address of the global variable '" << VD->getName() << "'";
1676 os << "the address of a global variable";
1685 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1687 const Expr *DeallocExpr) const {
1689 if (!ChecksEnabled[CK_MallocChecker] &&
1690 !ChecksEnabled[CK_NewDeleteChecker])
1693 Optional<MallocChecker::CheckKind> CheckKind =
1694 getCheckIfTracked(C, DeallocExpr);
1695 if (!CheckKind.hasValue())
1698 if (ExplodedNode *N = C.generateErrorNode()) {
1699 if (!BT_BadFree[*CheckKind])
1700 BT_BadFree[*CheckKind].reset(
1701 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1703 SmallString<100> buf;
1704 llvm::raw_svector_ostream os(buf);
1706 const MemRegion *MR = ArgVal.getAsRegion();
1707 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1708 MR = ER->getSuperRegion();
1710 os << "Argument to ";
1711 if (!printAllocDeallocName(os, C, DeallocExpr))
1712 os << "deallocator";
1715 bool Summarized = MR ? SummarizeRegion(os, MR)
1716 : SummarizeValue(os, ArgVal);
1718 os << ", which is not memory allocated by ";
1720 os << "not memory allocated by ";
1722 printExpectedAllocName(os, C, DeallocExpr);
1724 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1725 R->markInteresting(MR);
1727 C.emitReport(std::move(R));
1731 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1732 SourceRange Range) const {
1734 Optional<MallocChecker::CheckKind> CheckKind;
1736 if (ChecksEnabled[CK_MallocChecker])
1737 CheckKind = CK_MallocChecker;
1738 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1739 CheckKind = CK_MismatchedDeallocatorChecker;
1743 if (ExplodedNode *N = C.generateErrorNode()) {
1744 if (!BT_FreeAlloca[*CheckKind])
1745 BT_FreeAlloca[*CheckKind].reset(
1746 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1748 auto R = llvm::make_unique<BugReport>(
1749 *BT_FreeAlloca[*CheckKind],
1750 "Memory allocated by alloca() should not be deallocated", N);
1751 R->markInteresting(ArgVal.getAsRegion());
1753 C.emitReport(std::move(R));
1757 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1759 const Expr *DeallocExpr,
1762 bool OwnershipTransferred) const {
1764 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1767 if (ExplodedNode *N = C.generateErrorNode()) {
1768 if (!BT_MismatchedDealloc)
1769 BT_MismatchedDealloc.reset(
1770 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1771 "Bad deallocator", "Memory Error"));
1773 SmallString<100> buf;
1774 llvm::raw_svector_ostream os(buf);
1776 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1777 SmallString<20> AllocBuf;
1778 llvm::raw_svector_ostream AllocOs(AllocBuf);
1779 SmallString<20> DeallocBuf;
1780 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1782 if (OwnershipTransferred) {
1783 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1784 os << DeallocOs.str() << " cannot";
1788 os << " take ownership of memory";
1790 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1791 os << " allocated by " << AllocOs.str();
1794 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1795 os << " allocated by " << AllocOs.str();
1797 os << " should be deallocated by ";
1798 printExpectedDeallocName(os, RS->getAllocationFamily());
1800 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1801 os << ", not " << DeallocOs.str();
1804 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1805 R->markInteresting(Sym);
1807 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1808 C.emitReport(std::move(R));
1812 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1813 SourceRange Range, const Expr *DeallocExpr,
1814 const Expr *AllocExpr) const {
1817 if (!ChecksEnabled[CK_MallocChecker] &&
1818 !ChecksEnabled[CK_NewDeleteChecker])
1821 Optional<MallocChecker::CheckKind> CheckKind =
1822 getCheckIfTracked(C, AllocExpr);
1823 if (!CheckKind.hasValue())
1826 ExplodedNode *N = C.generateErrorNode();
1830 if (!BT_OffsetFree[*CheckKind])
1831 BT_OffsetFree[*CheckKind].reset(
1832 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1834 SmallString<100> buf;
1835 llvm::raw_svector_ostream os(buf);
1836 SmallString<20> AllocNameBuf;
1837 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1839 const MemRegion *MR = ArgVal.getAsRegion();
1840 assert(MR && "Only MemRegion based symbols can have offset free errors");
1842 RegionOffset Offset = MR->getAsOffset();
1843 assert((Offset.isValid() &&
1844 !Offset.hasSymbolicOffset() &&
1845 Offset.getOffset() != 0) &&
1846 "Only symbols with a valid offset can have offset free errors");
1848 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1850 os << "Argument to ";
1851 if (!printAllocDeallocName(os, C, DeallocExpr))
1852 os << "deallocator";
1853 os << " is offset by "
1856 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1857 << " from the start of ";
1858 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1859 os << "memory allocated by " << AllocNameOs.str();
1861 os << "allocated memory";
1863 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1864 R->markInteresting(MR->getBaseRegion());
1866 C.emitReport(std::move(R));
1869 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1870 SymbolRef Sym) const {
1872 if (!ChecksEnabled[CK_MallocChecker] &&
1873 !ChecksEnabled[CK_NewDeleteChecker])
1876 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1877 if (!CheckKind.hasValue())
1880 if (ExplodedNode *N = C.generateErrorNode()) {
1881 if (!BT_UseFree[*CheckKind])
1882 BT_UseFree[*CheckKind].reset(new BugType(
1883 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1885 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1886 "Use of memory after it is freed", N);
1888 R->markInteresting(Sym);
1890 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1891 C.emitReport(std::move(R));
1895 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1896 bool Released, SymbolRef Sym,
1897 SymbolRef PrevSym) const {
1899 if (!ChecksEnabled[CK_MallocChecker] &&
1900 !ChecksEnabled[CK_NewDeleteChecker])
1903 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1904 if (!CheckKind.hasValue())
1907 if (ExplodedNode *N = C.generateErrorNode()) {
1908 if (!BT_DoubleFree[*CheckKind])
1909 BT_DoubleFree[*CheckKind].reset(
1910 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1912 auto R = llvm::make_unique<BugReport>(
1913 *BT_DoubleFree[*CheckKind],
1914 (Released ? "Attempt to free released memory"
1915 : "Attempt to free non-owned memory"),
1918 R->markInteresting(Sym);
1920 R->markInteresting(PrevSym);
1921 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1922 C.emitReport(std::move(R));
1926 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1928 if (!ChecksEnabled[CK_NewDeleteChecker])
1931 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1932 if (!CheckKind.hasValue())
1935 if (ExplodedNode *N = C.generateErrorNode()) {
1936 if (!BT_DoubleDelete)
1937 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1938 "Double delete", "Memory Error"));
1940 auto R = llvm::make_unique<BugReport>(
1941 *BT_DoubleDelete, "Attempt to delete released memory", N);
1943 R->markInteresting(Sym);
1944 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1945 C.emitReport(std::move(R));
1949 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1951 SymbolRef Sym) const {
1953 if (!ChecksEnabled[CK_MallocChecker] &&
1954 !ChecksEnabled[CK_NewDeleteChecker])
1957 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1959 if (!CheckKind.hasValue())
1962 if (ExplodedNode *N = C.generateErrorNode()) {
1963 if (!BT_UseZerroAllocated[*CheckKind])
1964 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
1965 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
1967 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
1968 "Use of zero-allocated memory", N);
1972 R->markInteresting(Sym);
1973 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1975 C.emitReport(std::move(R));
1979 ProgramStateRef MallocChecker::ReallocMem(CheckerContext &C,
1982 ProgramStateRef State) const {
1986 if (CE->getNumArgs() < 2)
1989 const Expr *arg0Expr = CE->getArg(0);
1990 const LocationContext *LCtx = C.getLocationContext();
1991 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
1992 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
1994 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
1996 SValBuilder &svalBuilder = C.getSValBuilder();
1998 DefinedOrUnknownSVal PtrEQ =
1999 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2001 // Get the size argument. If there is no size arg then give up.
2002 const Expr *Arg1 = CE->getArg(1);
2006 // Get the value of the size argument.
2007 SVal Arg1ValG = State->getSVal(Arg1, LCtx);
2008 if (!Arg1ValG.getAs<DefinedOrUnknownSVal>())
2010 DefinedOrUnknownSVal Arg1Val = Arg1ValG.castAs<DefinedOrUnknownSVal>();
2012 // Compare the size argument to 0.
2013 DefinedOrUnknownSVal SizeZero =
2014 svalBuilder.evalEQ(State, Arg1Val,
2015 svalBuilder.makeIntValWithPtrWidth(0, false));
2017 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2018 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2019 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2020 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2021 // We only assume exceptional states if they are definitely true; if the
2022 // state is under-constrained, assume regular realloc behavior.
2023 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2024 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2026 // If the ptr is NULL and the size is not 0, the call is equivalent to
2028 if ( PrtIsNull && !SizeIsZero) {
2029 ProgramStateRef stateMalloc = MallocMemAux(C, CE, CE->getArg(1),
2030 UndefinedVal(), StatePtrIsNull);
2034 if (PrtIsNull && SizeIsZero)
2037 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2039 SymbolRef FromPtr = arg0Val.getAsSymbol();
2040 SVal RetVal = State->getSVal(CE, LCtx);
2041 SymbolRef ToPtr = RetVal.getAsSymbol();
2042 if (!FromPtr || !ToPtr)
2045 bool ReleasedAllocated = false;
2047 // If the size is 0, free the memory.
2049 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2050 false, ReleasedAllocated)){
2051 // The semantics of the return value are:
2052 // If size was equal to 0, either NULL or a pointer suitable to be passed
2053 // to free() is returned. We just free the input pointer and do not add
2054 // any constrains on the output pointer.
2058 // Default behavior.
2059 if (ProgramStateRef stateFree =
2060 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
2062 ProgramStateRef stateRealloc = MallocMemAux(C, CE, CE->getArg(1),
2063 UnknownVal(), stateFree);
2067 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2069 Kind = RPIsFreeOnFailure;
2070 else if (!ReleasedAllocated)
2071 Kind = RPDoNotTrackAfterFailure;
2073 // Record the info about the reallocated symbol so that we could properly
2074 // process failed reallocation.
2075 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2076 ReallocPair(FromPtr, Kind));
2077 // The reallocated symbol should stay alive for as long as the new symbol.
2078 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2079 return stateRealloc;
2084 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2085 ProgramStateRef State) {
2089 if (CE->getNumArgs() < 2)
2092 SValBuilder &svalBuilder = C.getSValBuilder();
2093 const LocationContext *LCtx = C.getLocationContext();
2094 SVal count = State->getSVal(CE->getArg(0), LCtx);
2095 SVal elementSize = State->getSVal(CE->getArg(1), LCtx);
2096 SVal TotalSize = svalBuilder.evalBinOp(State, BO_Mul, count, elementSize,
2097 svalBuilder.getContext().getSizeType());
2098 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2100 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2104 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2105 CheckerContext &C) const {
2106 const LocationContext *LeakContext = N->getLocationContext();
2107 // Walk the ExplodedGraph backwards and find the first node that referred to
2108 // the tracked symbol.
2109 const ExplodedNode *AllocNode = N;
2110 const MemRegion *ReferenceRegion = nullptr;
2113 ProgramStateRef State = N->getState();
2114 if (!State->get<RegionState>(Sym))
2117 // Find the most recent expression bound to the symbol in the current
2119 if (!ReferenceRegion) {
2120 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2121 SVal Val = State->getSVal(MR);
2122 if (Val.getAsLocSymbol() == Sym) {
2123 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2124 // Do not show local variables belonging to a function other than
2125 // where the error is reported.
2127 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2128 ReferenceRegion = MR;
2133 // Allocation node, is the last node in the current or parent context in
2134 // which the symbol was tracked.
2135 const LocationContext *NContext = N->getLocationContext();
2136 if (NContext == LeakContext ||
2137 NContext->isParentOf(LeakContext))
2139 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2142 return LeakInfo(AllocNode, ReferenceRegion);
2145 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2146 CheckerContext &C) const {
2148 if (!ChecksEnabled[CK_MallocChecker] &&
2149 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2152 const RefState *RS = C.getState()->get<RegionState>(Sym);
2153 assert(RS && "cannot leak an untracked symbol");
2154 AllocationFamily Family = RS->getAllocationFamily();
2156 if (Family == AF_Alloca)
2159 Optional<MallocChecker::CheckKind>
2160 CheckKind = getCheckIfTracked(Family, true);
2162 if (!CheckKind.hasValue())
2166 if (!BT_Leak[*CheckKind]) {
2167 BT_Leak[*CheckKind].reset(
2168 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
2169 // Leaks should not be reported if they are post-dominated by a sink:
2170 // (1) Sinks are higher importance bugs.
2171 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2172 // with __noreturn functions such as assert() or exit(). We choose not
2173 // to report leaks on such paths.
2174 BT_Leak[*CheckKind]->setSuppressOnSink(true);
2177 // Most bug reports are cached at the location where they occurred.
2178 // With leaks, we want to unique them by the location where they were
2179 // allocated, and only report a single path.
2180 PathDiagnosticLocation LocUsedForUniqueing;
2181 const ExplodedNode *AllocNode = nullptr;
2182 const MemRegion *Region = nullptr;
2183 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2185 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
2187 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2188 C.getSourceManager(),
2189 AllocNode->getLocationContext());
2191 SmallString<200> buf;
2192 llvm::raw_svector_ostream os(buf);
2193 if (Region && Region->canPrintPretty()) {
2194 os << "Potential leak of memory pointed to by ";
2195 Region->printPretty(os);
2197 os << "Potential memory leak";
2200 auto R = llvm::make_unique<BugReport>(
2201 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2202 AllocNode->getLocationContext()->getDecl());
2203 R->markInteresting(Sym);
2204 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2205 C.emitReport(std::move(R));
2208 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2209 CheckerContext &C) const
2211 if (!SymReaper.hasDeadSymbols())
2214 ProgramStateRef state = C.getState();
2215 RegionStateTy RS = state->get<RegionState>();
2216 RegionStateTy::Factory &F = state->get_context<RegionState>();
2218 SmallVector<SymbolRef, 2> Errors;
2219 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2220 if (SymReaper.isDead(I->first)) {
2221 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2222 Errors.push_back(I->first);
2223 // Remove the dead symbol from the map.
2224 RS = F.remove(RS, I->first);
2229 // Cleanup the Realloc Pairs Map.
2230 ReallocPairsTy RP = state->get<ReallocPairs>();
2231 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2232 if (SymReaper.isDead(I->first) ||
2233 SymReaper.isDead(I->second.ReallocatedSym)) {
2234 state = state->remove<ReallocPairs>(I->first);
2238 // Cleanup the FreeReturnValue Map.
2239 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2240 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2241 if (SymReaper.isDead(I->first) ||
2242 SymReaper.isDead(I->second)) {
2243 state = state->remove<FreeReturnValue>(I->first);
2247 // Generate leak node.
2248 ExplodedNode *N = C.getPredecessor();
2249 if (!Errors.empty()) {
2250 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2251 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2253 for (SmallVectorImpl<SymbolRef>::iterator
2254 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2255 reportLeak(*I, N, C);
2260 C.addTransition(state->set<RegionState>(RS), N);
2263 void MallocChecker::checkPreCall(const CallEvent &Call,
2264 CheckerContext &C) const {
2266 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2267 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2268 if (!Sym || checkDoubleDelete(Sym, C))
2272 // We will check for double free in the post visit.
2273 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2274 const FunctionDecl *FD = FC->getDecl();
2278 ASTContext &Ctx = C.getASTContext();
2279 if (ChecksEnabled[CK_MallocChecker] &&
2280 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2281 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2282 MemoryOperationKind::MOK_Free)))
2285 if (ChecksEnabled[CK_NewDeleteChecker] &&
2286 isStandardNewDelete(FD, Ctx))
2290 // Check if the callee of a method is deleted.
2291 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2292 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2293 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2297 // Check arguments for being used after free.
2298 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2299 SVal ArgSVal = Call.getArgSVal(I);
2300 if (ArgSVal.getAs<Loc>()) {
2301 SymbolRef Sym = ArgSVal.getAsSymbol();
2304 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2310 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2311 const Expr *E = S->getRetValue();
2315 // Check if we are returning a symbol.
2316 ProgramStateRef State = C.getState();
2317 SVal RetVal = State->getSVal(E, C.getLocationContext());
2318 SymbolRef Sym = RetVal.getAsSymbol();
2320 // If we are returning a field of the allocated struct or an array element,
2321 // the callee could still free the memory.
2322 // TODO: This logic should be a part of generic symbol escape callback.
2323 if (const MemRegion *MR = RetVal.getAsRegion())
2324 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2325 if (const SymbolicRegion *BMR =
2326 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2327 Sym = BMR->getSymbol();
2329 // Check if we are returning freed memory.
2331 checkUseAfterFree(Sym, C, E);
2334 // TODO: Blocks should be either inlined or should call invalidate regions
2335 // upon invocation. After that's in place, special casing here will not be
2337 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2338 CheckerContext &C) const {
2340 // Scan the BlockDecRefExprs for any object the retain count checker
2342 if (!BE->getBlockDecl()->hasCaptures())
2345 ProgramStateRef state = C.getState();
2346 const BlockDataRegion *R =
2347 cast<BlockDataRegion>(state->getSVal(BE,
2348 C.getLocationContext()).getAsRegion());
2350 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2351 E = R->referenced_vars_end();
2356 SmallVector<const MemRegion*, 10> Regions;
2357 const LocationContext *LC = C.getLocationContext();
2358 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2360 for ( ; I != E; ++I) {
2361 const VarRegion *VR = I.getCapturedRegion();
2362 if (VR->getSuperRegion() == R) {
2363 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2365 Regions.push_back(VR);
2369 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2370 Regions.data() + Regions.size()).getState();
2371 C.addTransition(state);
2374 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2376 const RefState *RS = C.getState()->get<RegionState>(Sym);
2377 return (RS && RS->isReleased());
2380 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2381 const Stmt *S) const {
2383 if (isReleased(Sym, C)) {
2384 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2391 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2392 const Stmt *S) const {
2395 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2396 if (RS->isAllocatedOfSizeZero())
2397 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2399 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2400 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2404 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2406 if (isReleased(Sym, C)) {
2407 ReportDoubleDelete(C, Sym);
2413 // Check if the location is a freed symbolic region.
2414 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2415 CheckerContext &C) const {
2416 SymbolRef Sym = l.getLocSymbolInBase();
2418 checkUseAfterFree(Sym, C, S);
2419 checkUseZeroAllocated(Sym, C, S);
2423 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2424 // it - assuming that allocation failed on this path.
2425 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2427 bool Assumption) const {
2428 RegionStateTy RS = state->get<RegionState>();
2429 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2430 // If the symbol is assumed to be NULL, remove it from consideration.
2431 ConstraintManager &CMgr = state->getConstraintManager();
2432 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2433 if (AllocFailed.isConstrainedTrue())
2434 state = state->remove<RegionState>(I.getKey());
2437 // Realloc returns 0 when reallocation fails, which means that we should
2438 // restore the state of the pointer being reallocated.
2439 ReallocPairsTy RP = state->get<ReallocPairs>();
2440 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2441 // If the symbol is assumed to be NULL, remove it from consideration.
2442 ConstraintManager &CMgr = state->getConstraintManager();
2443 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2444 if (!AllocFailed.isConstrainedTrue())
2447 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2448 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2449 if (RS->isReleased()) {
2450 if (I.getData().Kind == RPToBeFreedAfterFailure)
2451 state = state->set<RegionState>(ReallocSym,
2452 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2453 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2454 state = state->remove<RegionState>(ReallocSym);
2456 assert(I.getData().Kind == RPIsFreeOnFailure);
2459 state = state->remove<ReallocPairs>(I.getKey());
2465 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2466 const CallEvent *Call,
2467 ProgramStateRef State,
2468 SymbolRef &EscapingSymbol) const {
2470 EscapingSymbol = nullptr;
2472 // For now, assume that any C++ or block call can free memory.
2473 // TODO: If we want to be more optimistic here, we'll need to make sure that
2474 // regions escape to C++ containers. They seem to do that even now, but for
2475 // mysterious reasons.
2476 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2479 // Check Objective-C messages by selector name.
2480 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2481 // If it's not a framework call, or if it takes a callback, assume it
2483 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2486 // If it's a method we know about, handle it explicitly post-call.
2487 // This should happen before the "freeWhenDone" check below.
2488 if (isKnownDeallocObjCMethodName(*Msg))
2491 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2492 // about, we can't be sure that the object will use free() to deallocate the
2493 // memory, so we can't model it explicitly. The best we can do is use it to
2494 // decide whether the pointer escapes.
2495 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2496 return *FreeWhenDone;
2498 // If the first selector piece ends with "NoCopy", and there is no
2499 // "freeWhenDone" parameter set to zero, we know ownership is being
2500 // transferred. Again, though, we can't be sure that the object will use
2501 // free() to deallocate the memory, so we can't model it explicitly.
2502 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2503 if (FirstSlot.endswith("NoCopy"))
2506 // If the first selector starts with addPointer, insertPointer,
2507 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2508 // This is similar to C++ containers (vector); we still might want to check
2509 // that the pointers get freed by following the container itself.
2510 if (FirstSlot.startswith("addPointer") ||
2511 FirstSlot.startswith("insertPointer") ||
2512 FirstSlot.startswith("replacePointer") ||
2513 FirstSlot.equals("valueWithPointer")) {
2517 // We should escape receiver on call to 'init'. This is especially relevant
2518 // to the receiver, as the corresponding symbol is usually not referenced
2520 if (Msg->getMethodFamily() == OMF_init) {
2521 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2525 // Otherwise, assume that the method does not free memory.
2526 // Most framework methods do not free memory.
2530 // At this point the only thing left to handle is straight function calls.
2531 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2535 ASTContext &ASTC = State->getStateManager().getContext();
2537 // If it's one of the allocation functions we can reason about, we model
2538 // its behavior explicitly.
2539 if (isMemFunction(FD, ASTC))
2542 // If it's not a system call, assume it frees memory.
2543 if (!Call->isInSystemHeader())
2546 // White list the system functions whose arguments escape.
2547 const IdentifierInfo *II = FD->getIdentifier();
2550 StringRef FName = II->getName();
2552 // White list the 'XXXNoCopy' CoreFoundation functions.
2553 // We specifically check these before
2554 if (FName.endswith("NoCopy")) {
2555 // Look for the deallocator argument. We know that the memory ownership
2556 // is not transferred only if the deallocator argument is
2557 // 'kCFAllocatorNull'.
2558 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2559 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2560 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2561 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2562 if (DeallocatorName == "kCFAllocatorNull")
2569 // Associating streams with malloced buffers. The pointer can escape if
2570 // 'closefn' is specified (and if that function does free memory),
2571 // but it will not if closefn is not specified.
2572 // Currently, we do not inspect the 'closefn' function (PR12101).
2573 if (FName == "funopen")
2574 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2577 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2578 // these leaks might be intentional when setting the buffer for stdio.
2579 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2580 if (FName == "setbuf" || FName =="setbuffer" ||
2581 FName == "setlinebuf" || FName == "setvbuf") {
2582 if (Call->getNumArgs() >= 1) {
2583 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2584 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2585 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2586 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2591 // A bunch of other functions which either take ownership of a pointer or
2592 // wrap the result up in a struct or object, meaning it can be freed later.
2593 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2594 // but the Malloc checker cannot differentiate between them. The right way
2595 // of doing this would be to implement a pointer escapes callback.
2596 if (FName == "CGBitmapContextCreate" ||
2597 FName == "CGBitmapContextCreateWithData" ||
2598 FName == "CVPixelBufferCreateWithBytes" ||
2599 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2600 FName == "OSAtomicEnqueue") {
2604 if (FName == "postEvent" &&
2605 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2609 if (FName == "postEvent" &&
2610 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2614 if (FName == "connectImpl" &&
2615 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2619 // Handle cases where we know a buffer's /address/ can escape.
2620 // Note that the above checks handle some special cases where we know that
2621 // even though the address escapes, it's still our responsibility to free the
2623 if (Call->argumentsMayEscape())
2626 // Otherwise, assume that the function does not free memory.
2627 // Most system calls do not free the memory.
2631 static bool retTrue(const RefState *RS) {
2635 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2636 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2637 RS->getAllocationFamily() == AF_CXXNew);
2640 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2641 const InvalidatedSymbols &Escaped,
2642 const CallEvent *Call,
2643 PointerEscapeKind Kind) const {
2644 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2647 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2648 const InvalidatedSymbols &Escaped,
2649 const CallEvent *Call,
2650 PointerEscapeKind Kind) const {
2651 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2652 &checkIfNewOrNewArrayFamily);
2655 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2656 const InvalidatedSymbols &Escaped,
2657 const CallEvent *Call,
2658 PointerEscapeKind Kind,
2659 bool(*CheckRefState)(const RefState*)) const {
2660 // If we know that the call does not free memory, or we want to process the
2661 // call later, keep tracking the top level arguments.
2662 SymbolRef EscapingSymbol = nullptr;
2663 if (Kind == PSK_DirectEscapeOnCall &&
2664 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2670 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2675 if (EscapingSymbol && EscapingSymbol != sym)
2678 if (const RefState *RS = State->get<RegionState>(sym)) {
2679 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2680 CheckRefState(RS)) {
2681 State = State->remove<RegionState>(sym);
2682 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2689 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2690 ProgramStateRef prevState) {
2691 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2692 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2694 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2696 SymbolRef sym = I.getKey();
2697 if (!currMap.lookup(sym))
2704 std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2705 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2707 ProgramStateRef state = N->getState();
2708 ProgramStateRef statePrev = PrevN->getState();
2710 const RefState *RS = state->get<RegionState>(Sym);
2711 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2715 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2719 // FIXME: We will eventually need to handle non-statement-based events
2720 // (__attribute__((cleanup))).
2722 // Find out if this is an interesting point and what is the kind.
2723 const char *Msg = nullptr;
2724 StackHintGeneratorForSymbol *StackHint = nullptr;
2725 if (Mode == Normal) {
2726 if (isAllocated(RS, RSPrev, S)) {
2727 Msg = "Memory is allocated";
2728 StackHint = new StackHintGeneratorForSymbol(Sym,
2729 "Returned allocated memory");
2730 } else if (isReleased(RS, RSPrev, S)) {
2731 Msg = "Memory is released";
2732 StackHint = new StackHintGeneratorForSymbol(Sym,
2733 "Returning; memory was released");
2734 } else if (isRelinquished(RS, RSPrev, S)) {
2735 Msg = "Memory ownership is transferred";
2736 StackHint = new StackHintGeneratorForSymbol(Sym, "");
2737 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2738 Mode = ReallocationFailed;
2739 Msg = "Reallocation failed";
2740 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2741 "Reallocation failed");
2743 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2744 // Is it possible to fail two reallocs WITHOUT testing in between?
2745 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2746 "We only support one failed realloc at a time.");
2747 BR.markInteresting(sym);
2748 FailedReallocSymbol = sym;
2752 // We are in a special mode if a reallocation failed later in the path.
2753 } else if (Mode == ReallocationFailed) {
2754 assert(FailedReallocSymbol && "No symbol to look for.");
2756 // Is this is the first appearance of the reallocated symbol?
2757 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2758 // We're at the reallocation point.
2759 Msg = "Attempt to reallocate memory";
2760 StackHint = new StackHintGeneratorForSymbol(Sym,
2761 "Returned reallocated memory");
2762 FailedReallocSymbol = nullptr;
2771 // Generate the extra diagnostic.
2772 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2773 N->getLocationContext());
2774 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
2777 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2778 const char *NL, const char *Sep) const {
2780 RegionStateTy RS = State->get<RegionState>();
2782 if (!RS.isEmpty()) {
2783 Out << Sep << "MallocChecker :" << NL;
2784 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2785 const RefState *RefS = State->get<RegionState>(I.getKey());
2786 AllocationFamily Family = RefS->getAllocationFamily();
2787 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2788 if (!CheckKind.hasValue())
2789 CheckKind = getCheckIfTracked(Family, true);
2791 I.getKey()->dumpToStream(Out);
2793 I.getData().dump(Out);
2794 if (CheckKind.hasValue())
2795 Out << " (" << CheckNames[*CheckKind].getName() << ")";
2801 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2802 registerCStringCheckerBasic(mgr);
2803 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2804 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2805 "Optimistic", false, checker);
2806 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2807 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2808 mgr.getCurrentCheckName();
2809 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2811 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2812 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2815 #define REGISTER_CHECKER(name) \
2816 void ento::register##name(CheckerManager &mgr) { \
2817 registerCStringCheckerBasic(mgr); \
2818 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2819 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2820 "Optimistic", false, checker); \
2821 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2822 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2825 REGISTER_CHECKER(MallocChecker)
2826 REGISTER_CHECKER(NewDeleteChecker)
2827 REGISTER_CHECKER(MismatchedDeallocatorChecker)