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/BugReporter/CommonBugCategories.h"
23 #include "clang/StaticAnalyzer/Core/Checker.h"
24 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
26 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
27 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
28 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
29 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
36 using namespace clang;
41 // Used to check correspondence between allocators and deallocators.
42 enum AllocationFamily {
52 enum Kind { // Reference to allocated memory.
54 // Reference to zero-allocated memory.
56 // Reference to released/freed memory.
58 // The responsibility for freeing resources has transferred from
59 // this reference. A relinquished symbol should not be freed.
61 // We are no longer guaranteed to have observed all manipulations
62 // of this pointer/memory. For example, it could have been
63 // passed as a parameter to an opaque function.
68 unsigned K : 3; // Kind enum, but stored as a bitfield.
69 unsigned Family : 29; // Rest of 32-bit word, currently just an allocation
72 RefState(Kind k, const Stmt *s, unsigned family)
73 : S(s), K(k), Family(family) {
74 assert(family != AF_None);
77 bool isAllocated() const { return K == Allocated; }
78 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
79 bool isReleased() const { return K == Released; }
80 bool isRelinquished() const { return K == Relinquished; }
81 bool isEscaped() const { return K == Escaped; }
82 AllocationFamily getAllocationFamily() const {
83 return (AllocationFamily)Family;
85 const Stmt *getStmt() const { return S; }
87 bool operator==(const RefState &X) const {
88 return K == X.K && S == X.S && Family == X.Family;
91 static RefState getAllocated(unsigned family, const Stmt *s) {
92 return RefState(Allocated, s, family);
94 static RefState getAllocatedOfSizeZero(const RefState *RS) {
95 return RefState(AllocatedOfSizeZero, RS->getStmt(),
96 RS->getAllocationFamily());
98 static RefState getReleased(unsigned family, const Stmt *s) {
99 return RefState(Released, s, family);
101 static RefState getRelinquished(unsigned family, const Stmt *s) {
102 return RefState(Relinquished, s, family);
104 static RefState getEscaped(const RefState *RS) {
105 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
108 void Profile(llvm::FoldingSetNodeID &ID) const {
111 ID.AddInteger(Family);
114 void dump(raw_ostream &OS) const {
115 switch (static_cast<Kind>(K)) {
116 #define CASE(ID) case ID: OS << #ID; break;
118 CASE(AllocatedOfSizeZero)
125 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
128 enum ReallocPairKind {
129 RPToBeFreedAfterFailure,
130 // The symbol has been freed when reallocation failed.
132 // The symbol does not need to be freed after reallocation fails.
133 RPDoNotTrackAfterFailure
136 /// \class ReallocPair
137 /// \brief Stores information about the symbol being reallocated by a call to
138 /// 'realloc' to allow modeling failed reallocation later in the path.
140 // \brief The symbol which realloc reallocated.
141 SymbolRef ReallocatedSym;
142 ReallocPairKind Kind;
144 ReallocPair(SymbolRef S, ReallocPairKind K) :
145 ReallocatedSym(S), Kind(K) {}
146 void Profile(llvm::FoldingSetNodeID &ID) const {
148 ID.AddPointer(ReallocatedSym);
150 bool operator==(const ReallocPair &X) const {
151 return ReallocatedSym == X.ReallocatedSym &&
156 typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
158 class MallocChecker : public Checker<check::DeadSymbols,
159 check::PointerEscape,
160 check::ConstPointerEscape,
161 check::PreStmt<ReturnStmt>,
163 check::PostStmt<CallExpr>,
164 check::PostStmt<CXXNewExpr>,
165 check::PreStmt<CXXDeleteExpr>,
166 check::PostStmt<BlockExpr>,
167 check::PostObjCMessage,
173 : II_alloca(nullptr), II_win_alloca(nullptr), II_malloc(nullptr),
174 II_free(nullptr), II_realloc(nullptr), II_calloc(nullptr),
175 II_valloc(nullptr), II_reallocf(nullptr), II_strndup(nullptr),
176 II_strdup(nullptr), II_win_strdup(nullptr), II_kmalloc(nullptr),
177 II_if_nameindex(nullptr), II_if_freenameindex(nullptr),
178 II_wcsdup(nullptr), II_win_wcsdup(nullptr), II_g_malloc(nullptr),
179 II_g_malloc0(nullptr), II_g_realloc(nullptr), II_g_try_malloc(nullptr),
180 II_g_try_malloc0(nullptr), II_g_try_realloc(nullptr),
181 II_g_free(nullptr), II_g_memdup(nullptr), II_g_malloc_n(nullptr),
182 II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
183 II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
184 II_g_try_realloc_n(nullptr) {}
186 /// In pessimistic mode, the checker assumes that it does not know which
187 /// functions might free the memory.
191 CK_NewDeleteLeaksChecker,
192 CK_MismatchedDeallocatorChecker,
196 enum class MemoryOperationKind {
202 DefaultBool IsOptimistic;
204 DefaultBool ChecksEnabled[CK_NumCheckKinds];
205 CheckName CheckNames[CK_NumCheckKinds];
207 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
208 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
209 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
210 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
211 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
212 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
213 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
214 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
215 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
216 bool Assumption) const;
217 void checkLocation(SVal l, bool isLoad, const Stmt *S,
218 CheckerContext &C) const;
220 ProgramStateRef checkPointerEscape(ProgramStateRef State,
221 const InvalidatedSymbols &Escaped,
222 const CallEvent *Call,
223 PointerEscapeKind Kind) const;
224 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
225 const InvalidatedSymbols &Escaped,
226 const CallEvent *Call,
227 PointerEscapeKind Kind) const;
229 void printState(raw_ostream &Out, ProgramStateRef State,
230 const char *NL, const char *Sep) const override;
233 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
234 mutable std::unique_ptr<BugType> BT_DoubleDelete;
235 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
236 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
237 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
238 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
239 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
240 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
241 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
242 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
243 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
244 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
245 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
246 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
247 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
248 *II_g_try_realloc, *II_g_free, *II_g_memdup,
249 *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
250 *II_g_try_malloc_n, *II_g_try_malloc0_n,
252 mutable Optional<uint64_t> KernelZeroFlagVal;
254 void initIdentifierInfo(ASTContext &C) const;
256 /// \brief Determine family of a deallocation expression.
257 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
259 /// \brief Print names of allocators and deallocators.
261 /// \returns true on success.
262 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
263 const Expr *E) const;
265 /// \brief Print expected name of an allocator based on the deallocator's
266 /// family derived from the DeallocExpr.
267 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
268 const Expr *DeallocExpr) const;
269 /// \brief Print expected name of a deallocator based on the allocator's
271 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
274 /// Check if this is one of the functions which can allocate/reallocate memory
275 /// pointed to by one of its arguments.
276 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
277 bool isCMemFunction(const FunctionDecl *FD,
279 AllocationFamily Family,
280 MemoryOperationKind MemKind) const;
281 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
284 /// \brief Perform a zero-allocation check.
285 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
286 const unsigned AllocationSizeArg,
287 ProgramStateRef State) const;
289 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
291 const OwnershipAttr* Att,
292 ProgramStateRef State) const;
293 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
294 const Expr *SizeEx, SVal Init,
295 ProgramStateRef State,
296 AllocationFamily Family = AF_Malloc);
297 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
298 SVal SizeEx, SVal Init,
299 ProgramStateRef State,
300 AllocationFamily Family = AF_Malloc);
302 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
303 ProgramStateRef State);
305 // Check if this malloc() for special flags. At present that means M_ZERO or
306 // __GFP_ZERO (in which case, treat it like calloc).
307 llvm::Optional<ProgramStateRef>
308 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
309 const ProgramStateRef &State) const;
311 /// Update the RefState to reflect the new memory allocation.
312 static ProgramStateRef
313 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
314 AllocationFamily Family = AF_Malloc);
316 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
317 const OwnershipAttr* Att,
318 ProgramStateRef State) const;
319 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
320 ProgramStateRef state, unsigned Num,
322 bool &ReleasedAllocated,
323 bool ReturnsNullOnFailure = false) const;
324 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
325 const Expr *ParentExpr,
326 ProgramStateRef State,
328 bool &ReleasedAllocated,
329 bool ReturnsNullOnFailure = false) const;
331 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
332 bool FreesMemOnFailure,
333 ProgramStateRef State,
334 bool SuffixWithN = false) const;
335 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
336 const Expr *BlockBytes);
337 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
338 ProgramStateRef State);
340 ///\brief Check if the memory associated with this symbol was released.
341 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
343 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
345 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
346 const Stmt *S) const;
348 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
350 /// Check if the function is known free memory, or if it is
351 /// "interesting" and should be modeled explicitly.
353 /// \param [out] EscapingSymbol A function might not free memory in general,
354 /// but could be known to free a particular symbol. In this case, false is
355 /// returned and the single escaping symbol is returned through the out
358 /// We assume that pointers do not escape through calls to system functions
359 /// not handled by this checker.
360 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
361 ProgramStateRef State,
362 SymbolRef &EscapingSymbol) const;
364 // Implementation of the checkPointerEscape callabcks.
365 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
366 const InvalidatedSymbols &Escaped,
367 const CallEvent *Call,
368 PointerEscapeKind Kind,
369 bool(*CheckRefState)(const RefState*)) const;
372 /// Tells if a given family/call/symbol is tracked by the current checker.
373 /// Sets CheckKind to the kind of the checker responsible for this
374 /// family/call/symbol.
375 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
376 bool IsALeakCheck = false) const;
377 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
378 const Stmt *AllocDeallocStmt,
379 bool IsALeakCheck = false) const;
380 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
381 bool IsALeakCheck = false) const;
383 static bool SummarizeValue(raw_ostream &os, SVal V);
384 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
385 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
386 const Expr *DeallocExpr) const;
387 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
388 SourceRange Range) const;
389 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
390 const Expr *DeallocExpr, const RefState *RS,
391 SymbolRef Sym, bool OwnershipTransferred) const;
392 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
393 const Expr *DeallocExpr,
394 const Expr *AllocExpr = nullptr) const;
395 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
396 SymbolRef Sym) const;
397 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
398 SymbolRef Sym, SymbolRef PrevSym) const;
400 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
402 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
403 SymbolRef Sym) const;
405 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
406 SourceRange Range, const Expr *FreeExpr) const;
408 /// Find the location of the allocation for Sym on the path leading to the
410 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
411 CheckerContext &C) const;
413 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
415 /// The bug visitor which allows us to print extra diagnostics along the
416 /// BugReport path. For example, showing the allocation site of the leaked
418 class MallocBugVisitor final
419 : public BugReporterVisitorImpl<MallocBugVisitor> {
421 enum NotificationMode {
426 // The allocated region symbol tracked by the main analysis.
429 // The mode we are in, i.e. what kind of diagnostics will be emitted.
430 NotificationMode Mode;
432 // A symbol from when the primary region should have been reallocated.
433 SymbolRef FailedReallocSymbol;
438 MallocBugVisitor(SymbolRef S, bool isLeak = false)
439 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
441 void Profile(llvm::FoldingSetNodeID &ID) const override {
447 inline bool isAllocated(const RefState *S, const RefState *SPrev,
449 // Did not track -> allocated. Other state (released) -> allocated.
450 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
451 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
452 (!SPrev || !(SPrev->isAllocated() ||
453 SPrev->isAllocatedOfSizeZero())));
456 inline bool isReleased(const RefState *S, const RefState *SPrev,
458 // Did not track -> released. Other state (allocated) -> released.
459 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
460 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
463 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
465 // Did not track -> relinquished. Other state (allocated) -> relinquished.
466 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
467 isa<ObjCPropertyRefExpr>(Stmt)) &&
468 (S && S->isRelinquished()) &&
469 (!SPrev || !SPrev->isRelinquished()));
472 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
474 // If the expression is not a call, and the state change is
475 // released -> allocated, it must be the realloc return value
476 // check. If we have to handle more cases here, it might be cleaner just
477 // to track this extra bit in the state itself.
478 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
479 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
480 (SPrev && !(SPrev->isAllocated() ||
481 SPrev->isAllocatedOfSizeZero())));
484 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
485 const ExplodedNode *PrevN,
486 BugReporterContext &BRC,
487 BugReport &BR) override;
489 std::unique_ptr<PathDiagnosticPiece>
490 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
491 BugReport &BR) override {
495 PathDiagnosticLocation L =
496 PathDiagnosticLocation::createEndOfPath(EndPathNode,
497 BRC.getSourceManager());
498 // Do not add the statement itself as a range in case of leak.
499 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
504 class StackHintGeneratorForReallocationFailed
505 : public StackHintGeneratorForSymbol {
507 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
508 : StackHintGeneratorForSymbol(S, M) {}
510 std::string getMessageForArg(const Expr *ArgE,
511 unsigned ArgIndex) override {
512 // Printed parameters start at 1, not 0.
515 SmallString<200> buf;
516 llvm::raw_svector_ostream os(buf);
518 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
519 << " parameter failed";
524 std::string getMessageForReturn(const CallExpr *CallExpr) override {
525 return "Reallocation of returned value failed";
530 } // end anonymous namespace
532 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
533 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
534 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
536 // A map from the freed symbol to the symbol representing the return value of
537 // the free function.
538 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
541 class StopTrackingCallback final : public SymbolVisitor {
542 ProgramStateRef state;
544 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
545 ProgramStateRef getState() const { return state; }
547 bool VisitSymbol(SymbolRef sym) override {
548 state = state->remove<RegionState>(sym);
552 } // end anonymous namespace
554 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
557 II_alloca = &Ctx.Idents.get("alloca");
558 II_malloc = &Ctx.Idents.get("malloc");
559 II_free = &Ctx.Idents.get("free");
560 II_realloc = &Ctx.Idents.get("realloc");
561 II_reallocf = &Ctx.Idents.get("reallocf");
562 II_calloc = &Ctx.Idents.get("calloc");
563 II_valloc = &Ctx.Idents.get("valloc");
564 II_strdup = &Ctx.Idents.get("strdup");
565 II_strndup = &Ctx.Idents.get("strndup");
566 II_wcsdup = &Ctx.Idents.get("wcsdup");
567 II_kmalloc = &Ctx.Idents.get("kmalloc");
568 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
569 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
571 //MSVC uses `_`-prefixed instead, so we check for them too.
572 II_win_strdup = &Ctx.Idents.get("_strdup");
573 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
574 II_win_alloca = &Ctx.Idents.get("_alloca");
577 II_g_malloc = &Ctx.Idents.get("g_malloc");
578 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
579 II_g_realloc = &Ctx.Idents.get("g_realloc");
580 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
581 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
582 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
583 II_g_free = &Ctx.Idents.get("g_free");
584 II_g_memdup = &Ctx.Idents.get("g_memdup");
585 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
586 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
587 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
588 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
589 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
590 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
593 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
594 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
597 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
600 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
603 if (isStandardNewDelete(FD, C))
609 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
611 AllocationFamily Family,
612 MemoryOperationKind MemKind) const {
616 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
617 MemKind == MemoryOperationKind::MOK_Free);
618 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
619 MemKind == MemoryOperationKind::MOK_Allocate);
621 if (FD->getKind() == Decl::Function) {
622 const IdentifierInfo *FunI = FD->getIdentifier();
623 initIdentifierInfo(C);
625 if (Family == AF_Malloc && CheckFree) {
626 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
631 if (Family == AF_Malloc && CheckAlloc) {
632 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
633 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
634 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
635 FunI == II_win_wcsdup || FunI == II_kmalloc ||
636 FunI == II_g_malloc || FunI == II_g_malloc0 ||
637 FunI == II_g_realloc || FunI == II_g_try_malloc ||
638 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
639 FunI == II_g_memdup || FunI == II_g_malloc_n ||
640 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
641 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
642 FunI == II_g_try_realloc_n)
646 if (Family == AF_IfNameIndex && CheckFree) {
647 if (FunI == II_if_freenameindex)
651 if (Family == AF_IfNameIndex && CheckAlloc) {
652 if (FunI == II_if_nameindex)
656 if (Family == AF_Alloca && CheckAlloc) {
657 if (FunI == II_alloca || FunI == II_win_alloca)
662 if (Family != AF_Malloc)
665 if (IsOptimistic && FD->hasAttrs()) {
666 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
667 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
668 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
671 } else if (OwnKind == OwnershipAttr::Returns) {
681 // Tells if the callee is one of the following:
682 // 1) A global non-placement new/delete operator function.
683 // 2) A global placement operator function with the single placement argument
684 // of type std::nothrow_t.
685 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
686 ASTContext &C) const {
690 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
691 if (Kind != OO_New && Kind != OO_Array_New &&
692 Kind != OO_Delete && Kind != OO_Array_Delete)
695 // Skip all operator new/delete methods.
696 if (isa<CXXMethodDecl>(FD))
699 // Return true if tested operator is a standard placement nothrow operator.
700 if (FD->getNumParams() == 2) {
701 QualType T = FD->getParamDecl(1)->getType();
702 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
703 return II->getName().equals("nothrow_t");
706 // Skip placement operators.
707 if (FD->getNumParams() != 1 || FD->isVariadic())
710 // One of the standard new/new[]/delete/delete[] non-placement operators.
714 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
715 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
716 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
718 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
720 // One of the possible flags is M_ZERO, which means 'give me back an
721 // allocation which is already zeroed', like calloc.
723 // 2-argument kmalloc(), as used in the Linux kernel:
725 // void *kmalloc(size_t size, gfp_t flags);
727 // Has the similar flag value __GFP_ZERO.
729 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
730 // code could be shared.
732 ASTContext &Ctx = C.getASTContext();
733 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
735 if (!KernelZeroFlagVal.hasValue()) {
736 if (OS == llvm::Triple::FreeBSD)
737 KernelZeroFlagVal = 0x0100;
738 else if (OS == llvm::Triple::NetBSD)
739 KernelZeroFlagVal = 0x0002;
740 else if (OS == llvm::Triple::OpenBSD)
741 KernelZeroFlagVal = 0x0008;
742 else if (OS == llvm::Triple::Linux)
744 KernelZeroFlagVal = 0x8000;
746 // FIXME: We need a more general way of getting the M_ZERO value.
747 // See also: O_CREAT in UnixAPIChecker.cpp.
749 // Fall back to normal malloc behavior on platforms where we don't
754 // We treat the last argument as the flags argument, and callers fall-back to
755 // normal malloc on a None return. This works for the FreeBSD kernel malloc
756 // as well as Linux kmalloc.
757 if (CE->getNumArgs() < 2)
760 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
761 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
762 if (!V.getAs<NonLoc>()) {
763 // The case where 'V' can be a location can only be due to a bad header,
764 // so in this case bail out.
768 NonLoc Flags = V.castAs<NonLoc>();
769 NonLoc ZeroFlag = C.getSValBuilder()
770 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
772 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
775 if (MaskedFlagsUC.isUnknownOrUndef())
777 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
779 // Check if maskedFlags is non-zero.
780 ProgramStateRef TrueState, FalseState;
781 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
783 // If M_ZERO is set, treat this like calloc (initialized).
784 if (TrueState && !FalseState) {
785 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
786 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
792 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
793 const Expr *BlockBytes) {
794 SValBuilder &SB = C.getSValBuilder();
795 SVal BlocksVal = C.getSVal(Blocks);
796 SVal BlockBytesVal = C.getSVal(BlockBytes);
797 ProgramStateRef State = C.getState();
798 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
799 SB.getContext().getSizeType());
803 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
807 const FunctionDecl *FD = C.getCalleeDecl(CE);
811 ProgramStateRef State = C.getState();
812 bool ReleasedAllocatedMemory = false;
814 if (FD->getKind() == Decl::Function) {
815 initIdentifierInfo(C.getASTContext());
816 IdentifierInfo *FunI = FD->getIdentifier();
818 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
819 if (CE->getNumArgs() < 1)
821 if (CE->getNumArgs() < 3) {
822 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
823 if (CE->getNumArgs() == 1)
824 State = ProcessZeroAllocation(C, CE, 0, State);
825 } else if (CE->getNumArgs() == 3) {
826 llvm::Optional<ProgramStateRef> MaybeState =
827 performKernelMalloc(CE, C, State);
828 if (MaybeState.hasValue())
829 State = MaybeState.getValue();
831 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
833 } else if (FunI == II_kmalloc) {
834 if (CE->getNumArgs() < 1)
836 llvm::Optional<ProgramStateRef> MaybeState =
837 performKernelMalloc(CE, C, State);
838 if (MaybeState.hasValue())
839 State = MaybeState.getValue();
841 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
842 } else if (FunI == II_valloc) {
843 if (CE->getNumArgs() < 1)
845 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
846 State = ProcessZeroAllocation(C, CE, 0, State);
847 } else if (FunI == II_realloc || FunI == II_g_realloc ||
848 FunI == II_g_try_realloc) {
849 State = ReallocMemAux(C, CE, false, State);
850 State = ProcessZeroAllocation(C, CE, 1, State);
851 } else if (FunI == II_reallocf) {
852 State = ReallocMemAux(C, CE, true, State);
853 State = ProcessZeroAllocation(C, CE, 1, State);
854 } else if (FunI == II_calloc) {
855 State = CallocMem(C, CE, State);
856 State = ProcessZeroAllocation(C, CE, 0, State);
857 State = ProcessZeroAllocation(C, CE, 1, State);
858 } else if (FunI == II_free || FunI == II_g_free) {
859 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
860 } else if (FunI == II_strdup || FunI == II_win_strdup ||
861 FunI == II_wcsdup || FunI == II_win_wcsdup) {
862 State = MallocUpdateRefState(C, CE, State);
863 } else if (FunI == II_strndup) {
864 State = MallocUpdateRefState(C, CE, State);
865 } else if (FunI == II_alloca || FunI == II_win_alloca) {
866 if (CE->getNumArgs() < 1)
868 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
870 State = ProcessZeroAllocation(C, CE, 0, State);
871 } else if (isStandardNewDelete(FD, C.getASTContext())) {
872 // Process direct calls to operator new/new[]/delete/delete[] functions
873 // as distinct from new/new[]/delete/delete[] expressions that are
874 // processed by the checkPostStmt callbacks for CXXNewExpr and
876 OverloadedOperatorKind K = FD->getOverloadedOperator();
878 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
880 State = ProcessZeroAllocation(C, CE, 0, State);
882 else if (K == OO_Array_New) {
883 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
885 State = ProcessZeroAllocation(C, CE, 0, State);
887 else if (K == OO_Delete || K == OO_Array_Delete)
888 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
890 llvm_unreachable("not a new/delete operator");
891 } else if (FunI == II_if_nameindex) {
892 // Should we model this differently? We can allocate a fixed number of
893 // elements with zeros in the last one.
894 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
896 } else if (FunI == II_if_freenameindex) {
897 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
898 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
899 if (CE->getNumArgs() < 1)
901 SValBuilder &svalBuilder = C.getSValBuilder();
902 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
903 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
904 State = ProcessZeroAllocation(C, CE, 0, State);
905 } else if (FunI == II_g_memdup) {
906 if (CE->getNumArgs() < 2)
908 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
909 State = ProcessZeroAllocation(C, CE, 1, State);
910 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
911 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
912 if (CE->getNumArgs() < 2)
914 SVal Init = UndefinedVal();
915 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
916 SValBuilder &SB = C.getSValBuilder();
917 Init = SB.makeZeroVal(SB.getContext().CharTy);
919 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
920 State = MallocMemAux(C, CE, TotalSize, Init, State);
921 State = ProcessZeroAllocation(C, CE, 0, State);
922 State = ProcessZeroAllocation(C, CE, 1, State);
923 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
924 if (CE->getNumArgs() < 3)
926 State = ReallocMemAux(C, CE, false, State, true);
927 State = ProcessZeroAllocation(C, CE, 1, State);
928 State = ProcessZeroAllocation(C, CE, 2, State);
932 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
933 // Check all the attributes, if there are any.
934 // There can be multiple of these attributes.
936 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
937 switch (I->getOwnKind()) {
938 case OwnershipAttr::Returns:
939 State = MallocMemReturnsAttr(C, CE, I, State);
941 case OwnershipAttr::Takes:
942 case OwnershipAttr::Holds:
943 State = FreeMemAttr(C, CE, I, State);
948 C.addTransition(State);
951 // Performs a 0-sized allocations check.
952 ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
954 const unsigned AllocationSizeArg,
955 ProgramStateRef State) const {
959 const Expr *Arg = nullptr;
961 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
962 Arg = CE->getArg(AllocationSizeArg);
964 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
966 Arg = NE->getArraySize();
971 llvm_unreachable("not a CallExpr or CXXNewExpr");
975 Optional<DefinedSVal> DefArgVal =
976 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
981 // Check if the allocation size is 0.
982 ProgramStateRef TrueState, FalseState;
983 SValBuilder &SvalBuilder = C.getSValBuilder();
985 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
987 std::tie(TrueState, FalseState) =
988 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
990 if (TrueState && !FalseState) {
991 SVal retVal = State->getSVal(E, C.getLocationContext());
992 SymbolRef Sym = retVal.getAsLocSymbol();
996 const RefState *RS = State->get<RegionState>(Sym);
998 if (RS->isAllocated())
999 return TrueState->set<RegionState>(Sym,
1000 RefState::getAllocatedOfSizeZero(RS));
1004 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1005 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1006 // tracked. Add zero-reallocated Sym to the state to catch references
1007 // to zero-allocated memory.
1008 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1012 // Assume the value is non-zero going forward.
1017 static QualType getDeepPointeeType(QualType T) {
1018 QualType Result = T, PointeeType = T->getPointeeType();
1019 while (!PointeeType.isNull()) {
1020 Result = PointeeType;
1021 PointeeType = PointeeType->getPointeeType();
1026 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1028 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1032 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1035 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1037 // Iterate over the constructor parameters.
1038 for (const auto *CtorParam : CtorD->parameters()) {
1040 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1041 if (CtorParamPointeeT.isNull())
1044 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1046 if (CtorParamPointeeT->getAsCXXRecordDecl())
1053 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1054 CheckerContext &C) const {
1056 if (NE->getNumPlacementArgs())
1057 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1058 E = NE->placement_arg_end(); I != E; ++I)
1059 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1060 checkUseAfterFree(Sym, C, *I);
1062 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1065 ParentMap &PM = C.getLocationContext()->getParentMap();
1066 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1069 ProgramStateRef State = C.getState();
1070 // The return value from operator new is bound to a specified initialization
1071 // value (if any) and we don't want to loose this value. So we call
1072 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
1073 // existing binding.
1074 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
1076 State = addExtentSize(C, NE, State);
1077 State = ProcessZeroAllocation(C, NE, 0, State);
1078 C.addTransition(State);
1081 // Sets the extent value of the MemRegion allocated by
1082 // new expression NE to its size in Bytes.
1084 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1085 const CXXNewExpr *NE,
1086 ProgramStateRef State) {
1089 SValBuilder &svalBuilder = C.getSValBuilder();
1091 const LocationContext *LCtx = C.getLocationContext();
1092 const SubRegion *Region;
1093 if (NE->isArray()) {
1094 const Expr *SizeExpr = NE->getArraySize();
1095 ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1096 // Store the extent size for the (symbolic)region
1097 // containing the elements.
1098 Region = (State->getSVal(NE, LCtx))
1100 ->getAs<SubRegion>()
1102 ->getAs<SubRegion>();
1104 ElementCount = svalBuilder.makeIntVal(1, true);
1105 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1109 // Set the region's extent equal to the Size in Bytes.
1110 QualType ElementType = NE->getAllocatedType();
1111 ASTContext &AstContext = C.getASTContext();
1112 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1114 if (ElementCount.getAs<NonLoc>()) {
1115 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1116 // size in Bytes = ElementCount*TypeSize
1117 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1118 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1119 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1120 svalBuilder.getArrayIndexType());
1121 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1122 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1123 State = State->assume(extentMatchesSize, true);
1128 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1129 CheckerContext &C) const {
1131 if (!ChecksEnabled[CK_NewDeleteChecker])
1132 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1133 checkUseAfterFree(Sym, C, DE->getArgument());
1135 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1138 ProgramStateRef State = C.getState();
1139 bool ReleasedAllocated;
1140 State = FreeMemAux(C, DE->getArgument(), DE, State,
1141 /*Hold*/false, ReleasedAllocated);
1143 C.addTransition(State);
1146 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1147 // If the first selector piece is one of the names below, assume that the
1148 // object takes ownership of the memory, promising to eventually deallocate it
1150 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1151 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1152 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1153 return FirstSlot == "dataWithBytesNoCopy" ||
1154 FirstSlot == "initWithBytesNoCopy" ||
1155 FirstSlot == "initWithCharactersNoCopy";
1158 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1159 Selector S = Call.getSelector();
1161 // FIXME: We should not rely on fully-constrained symbols being folded.
1162 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1163 if (S.getNameForSlot(i).equals("freeWhenDone"))
1164 return !Call.getArgSVal(i).isZeroConstant();
1169 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1170 CheckerContext &C) const {
1174 if (!isKnownDeallocObjCMethodName(Call))
1177 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1181 bool ReleasedAllocatedMemory;
1182 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1183 Call.getOriginExpr(), C.getState(),
1184 /*Hold=*/true, ReleasedAllocatedMemory,
1185 /*RetNullOnFailure=*/true);
1187 C.addTransition(State);
1191 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1192 const OwnershipAttr *Att,
1193 ProgramStateRef State) const {
1197 if (Att->getModule() != II_malloc)
1200 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1202 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
1204 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1207 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1209 const Expr *SizeEx, SVal Init,
1210 ProgramStateRef State,
1211 AllocationFamily Family) {
1215 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1216 Init, State, Family);
1219 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1221 SVal Size, SVal Init,
1222 ProgramStateRef State,
1223 AllocationFamily Family) {
1227 // We expect the malloc functions to return a pointer.
1228 if (!Loc::isLocType(CE->getType()))
1231 // Bind the return value to the symbolic value from the heap region.
1232 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1233 // side effects other than what we model here.
1234 unsigned Count = C.blockCount();
1235 SValBuilder &svalBuilder = C.getSValBuilder();
1236 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1237 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1238 .castAs<DefinedSVal>();
1239 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1241 // Fill the region with the initialization value.
1242 State = State->bindDefault(RetVal, Init, LCtx);
1244 // Set the region's extent equal to the Size parameter.
1245 const SymbolicRegion *R =
1246 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1249 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1250 Size.getAs<DefinedOrUnknownSVal>()) {
1251 SValBuilder &svalBuilder = C.getSValBuilder();
1252 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1253 DefinedOrUnknownSVal extentMatchesSize =
1254 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1256 State = State->assume(extentMatchesSize, true);
1260 return MallocUpdateRefState(C, CE, State, Family);
1263 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1265 ProgramStateRef State,
1266 AllocationFamily Family) {
1270 // Get the return value.
1271 SVal retVal = State->getSVal(E, C.getLocationContext());
1273 // We expect the malloc functions to return a pointer.
1274 if (!retVal.getAs<Loc>())
1277 SymbolRef Sym = retVal.getAsLocSymbol();
1280 // Set the symbol's state to Allocated.
1281 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1284 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1286 const OwnershipAttr *Att,
1287 ProgramStateRef State) const {
1291 if (Att->getModule() != II_malloc)
1294 bool ReleasedAllocated = false;
1296 for (const auto &Arg : Att->args()) {
1297 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1298 Att->getOwnKind() == OwnershipAttr::Holds,
1306 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1308 ProgramStateRef State,
1311 bool &ReleasedAllocated,
1312 bool ReturnsNullOnFailure) const {
1316 if (CE->getNumArgs() < (Num + 1))
1319 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1320 ReleasedAllocated, ReturnsNullOnFailure);
1323 /// Checks if the previous call to free on the given symbol failed - if free
1324 /// failed, returns true. Also, returns the corresponding return value symbol.
1325 static bool didPreviousFreeFail(ProgramStateRef State,
1326 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1327 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1329 assert(*Ret && "We should not store the null return symbol");
1330 ConstraintManager &CMgr = State->getConstraintManager();
1331 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1332 RetStatusSymbol = *Ret;
1333 return FreeFailed.isConstrainedTrue();
1338 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1339 const Stmt *S) const {
1343 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1344 const FunctionDecl *FD = C.getCalleeDecl(CE);
1347 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1349 ASTContext &Ctx = C.getASTContext();
1351 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1354 if (isStandardNewDelete(FD, Ctx)) {
1355 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1356 if (Kind == OO_New || Kind == OO_Delete)
1358 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1359 return AF_CXXNewArray;
1362 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1363 return AF_IfNameIndex;
1365 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1371 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1372 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1374 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1375 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1377 if (isa<ObjCMessageExpr>(S))
1383 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1384 const Expr *E) const {
1385 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1386 // FIXME: This doesn't handle indirect calls.
1387 const FunctionDecl *FD = CE->getDirectCallee();
1392 if (!FD->isOverloadedOperator())
1397 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1398 if (Msg->isInstanceMessage())
1402 Msg->getSelector().print(os);
1406 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1408 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1413 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1415 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1423 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1424 const Expr *E) const {
1425 AllocationFamily Family = getAllocationFamily(C, E);
1428 case AF_Malloc: os << "malloc()"; return;
1429 case AF_CXXNew: os << "'new'"; return;
1430 case AF_CXXNewArray: os << "'new[]'"; return;
1431 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1433 case AF_None: llvm_unreachable("not a deallocation expression");
1437 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1438 AllocationFamily Family) const {
1440 case AF_Malloc: os << "free()"; return;
1441 case AF_CXXNew: os << "'delete'"; return;
1442 case AF_CXXNewArray: os << "'delete[]'"; return;
1443 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1445 case AF_None: llvm_unreachable("suspicious argument");
1449 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1450 const Expr *ArgExpr,
1451 const Expr *ParentExpr,
1452 ProgramStateRef State,
1454 bool &ReleasedAllocated,
1455 bool ReturnsNullOnFailure) const {
1460 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1461 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1463 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1465 // Check for null dereferences.
1466 if (!location.getAs<Loc>())
1469 // The explicit NULL case, no operation is performed.
1470 ProgramStateRef notNullState, nullState;
1471 std::tie(notNullState, nullState) = State->assume(location);
1472 if (nullState && !notNullState)
1475 // Unknown values could easily be okay
1476 // Undefined values are handled elsewhere
1477 if (ArgVal.isUnknownOrUndef())
1480 const MemRegion *R = ArgVal.getAsRegion();
1482 // Nonlocs can't be freed, of course.
1483 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1485 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1489 R = R->StripCasts();
1491 // Blocks might show up as heap data, but should not be free()d
1492 if (isa<BlockDataRegion>(R)) {
1493 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1497 const MemSpaceRegion *MS = R->getMemorySpace();
1499 // Parameters, locals, statics, globals, and memory returned by
1500 // __builtin_alloca() shouldn't be freed.
1501 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1502 // FIXME: at the time this code was written, malloc() regions were
1503 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1504 // This means that there isn't actually anything from HeapSpaceRegion
1505 // that should be freed, even though we allow it here.
1506 // Of course, free() can work on memory allocated outside the current
1507 // function, so UnknownSpaceRegion is always a possibility.
1508 // False negatives are better than false positives.
1510 if (isa<AllocaRegion>(R))
1511 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1513 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1518 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1519 // Various cases could lead to non-symbol values here.
1520 // For now, ignore them.
1524 SymbolRef SymBase = SrBase->getSymbol();
1525 const RefState *RsBase = State->get<RegionState>(SymBase);
1526 SymbolRef PreviousRetStatusSymbol = nullptr;
1530 // Memory returned by alloca() shouldn't be freed.
1531 if (RsBase->getAllocationFamily() == AF_Alloca) {
1532 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1536 // Check for double free first.
1537 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1538 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1539 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1540 SymBase, PreviousRetStatusSymbol);
1543 // If the pointer is allocated or escaped, but we are now trying to free it,
1544 // check that the call to free is proper.
1545 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1546 RsBase->isEscaped()) {
1548 // Check if an expected deallocation function matches the real one.
1549 bool DeallocMatchesAlloc =
1550 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1551 if (!DeallocMatchesAlloc) {
1552 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1553 ParentExpr, RsBase, SymBase, Hold);
1557 // Check if the memory location being freed is the actual location
1558 // allocated, or an offset.
1559 RegionOffset Offset = R->getAsOffset();
1560 if (Offset.isValid() &&
1561 !Offset.hasSymbolicOffset() &&
1562 Offset.getOffset() != 0) {
1563 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1564 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1571 if (SymBase->getType()->isFunctionPointerType()) {
1572 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1576 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1577 RsBase->isAllocatedOfSizeZero());
1579 // Clean out the info on previous call to free return info.
1580 State = State->remove<FreeReturnValue>(SymBase);
1582 // Keep track of the return value. If it is NULL, we will know that free
1584 if (ReturnsNullOnFailure) {
1585 SVal RetVal = C.getSVal(ParentExpr);
1586 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1587 if (RetStatusSymbol) {
1588 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1589 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1593 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1594 : getAllocationFamily(C, ParentExpr);
1597 return State->set<RegionState>(SymBase,
1598 RefState::getRelinquished(Family,
1601 return State->set<RegionState>(SymBase,
1602 RefState::getReleased(Family, ParentExpr));
1605 Optional<MallocChecker::CheckKind>
1606 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1607 bool IsALeakCheck) const {
1611 case AF_IfNameIndex: {
1612 if (ChecksEnabled[CK_MallocChecker])
1613 return CK_MallocChecker;
1615 return Optional<MallocChecker::CheckKind>();
1618 case AF_CXXNewArray: {
1620 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1621 return CK_NewDeleteLeaksChecker;
1624 if (ChecksEnabled[CK_NewDeleteChecker])
1625 return CK_NewDeleteChecker;
1627 return Optional<MallocChecker::CheckKind>();
1630 llvm_unreachable("no family");
1633 llvm_unreachable("unhandled family");
1636 Optional<MallocChecker::CheckKind>
1637 MallocChecker::getCheckIfTracked(CheckerContext &C,
1638 const Stmt *AllocDeallocStmt,
1639 bool IsALeakCheck) const {
1640 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1644 Optional<MallocChecker::CheckKind>
1645 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1646 bool IsALeakCheck) const {
1647 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1648 return CK_MallocChecker;
1650 const RefState *RS = C.getState()->get<RegionState>(Sym);
1652 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1655 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1656 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1657 os << "an integer (" << IntVal->getValue() << ")";
1658 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1659 os << "a constant address (" << ConstAddr->getValue() << ")";
1660 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1661 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1668 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1669 const MemRegion *MR) {
1670 switch (MR->getKind()) {
1671 case MemRegion::FunctionCodeRegionKind: {
1672 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1674 os << "the address of the function '" << *FD << '\'';
1676 os << "the address of a function";
1679 case MemRegion::BlockCodeRegionKind:
1682 case MemRegion::BlockDataRegionKind:
1683 // FIXME: where the block came from?
1687 const MemSpaceRegion *MS = MR->getMemorySpace();
1689 if (isa<StackLocalsSpaceRegion>(MS)) {
1690 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1698 os << "the address of the local variable '" << VD->getName() << "'";
1700 os << "the address of a local stack variable";
1704 if (isa<StackArgumentsSpaceRegion>(MS)) {
1705 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1713 os << "the address of the parameter '" << VD->getName() << "'";
1715 os << "the address of a parameter";
1719 if (isa<GlobalsSpaceRegion>(MS)) {
1720 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1728 if (VD->isStaticLocal())
1729 os << "the address of the static variable '" << VD->getName() << "'";
1731 os << "the address of the global variable '" << VD->getName() << "'";
1733 os << "the address of a global variable";
1742 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1744 const Expr *DeallocExpr) const {
1746 if (!ChecksEnabled[CK_MallocChecker] &&
1747 !ChecksEnabled[CK_NewDeleteChecker])
1750 Optional<MallocChecker::CheckKind> CheckKind =
1751 getCheckIfTracked(C, DeallocExpr);
1752 if (!CheckKind.hasValue())
1755 if (ExplodedNode *N = C.generateErrorNode()) {
1756 if (!BT_BadFree[*CheckKind])
1757 BT_BadFree[*CheckKind].reset(new BugType(
1758 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
1760 SmallString<100> buf;
1761 llvm::raw_svector_ostream os(buf);
1763 const MemRegion *MR = ArgVal.getAsRegion();
1764 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1765 MR = ER->getSuperRegion();
1767 os << "Argument to ";
1768 if (!printAllocDeallocName(os, C, DeallocExpr))
1769 os << "deallocator";
1772 bool Summarized = MR ? SummarizeRegion(os, MR)
1773 : SummarizeValue(os, ArgVal);
1775 os << ", which is not memory allocated by ";
1777 os << "not memory allocated by ";
1779 printExpectedAllocName(os, C, DeallocExpr);
1781 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1782 R->markInteresting(MR);
1784 C.emitReport(std::move(R));
1788 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1789 SourceRange Range) const {
1791 Optional<MallocChecker::CheckKind> CheckKind;
1793 if (ChecksEnabled[CK_MallocChecker])
1794 CheckKind = CK_MallocChecker;
1795 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1796 CheckKind = CK_MismatchedDeallocatorChecker;
1800 if (ExplodedNode *N = C.generateErrorNode()) {
1801 if (!BT_FreeAlloca[*CheckKind])
1802 BT_FreeAlloca[*CheckKind].reset(new BugType(
1803 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
1805 auto R = llvm::make_unique<BugReport>(
1806 *BT_FreeAlloca[*CheckKind],
1807 "Memory allocated by alloca() should not be deallocated", N);
1808 R->markInteresting(ArgVal.getAsRegion());
1810 C.emitReport(std::move(R));
1814 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1816 const Expr *DeallocExpr,
1819 bool OwnershipTransferred) const {
1821 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1824 if (ExplodedNode *N = C.generateErrorNode()) {
1825 if (!BT_MismatchedDealloc)
1826 BT_MismatchedDealloc.reset(
1827 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1828 "Bad deallocator", categories::MemoryError));
1830 SmallString<100> buf;
1831 llvm::raw_svector_ostream os(buf);
1833 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1834 SmallString<20> AllocBuf;
1835 llvm::raw_svector_ostream AllocOs(AllocBuf);
1836 SmallString<20> DeallocBuf;
1837 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1839 if (OwnershipTransferred) {
1840 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1841 os << DeallocOs.str() << " cannot";
1845 os << " take ownership of memory";
1847 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1848 os << " allocated by " << AllocOs.str();
1851 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1852 os << " allocated by " << AllocOs.str();
1854 os << " should be deallocated by ";
1855 printExpectedDeallocName(os, RS->getAllocationFamily());
1857 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1858 os << ", not " << DeallocOs.str();
1861 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1862 R->markInteresting(Sym);
1864 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1865 C.emitReport(std::move(R));
1869 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1870 SourceRange Range, const Expr *DeallocExpr,
1871 const Expr *AllocExpr) const {
1874 if (!ChecksEnabled[CK_MallocChecker] &&
1875 !ChecksEnabled[CK_NewDeleteChecker])
1878 Optional<MallocChecker::CheckKind> CheckKind =
1879 getCheckIfTracked(C, AllocExpr);
1880 if (!CheckKind.hasValue())
1883 ExplodedNode *N = C.generateErrorNode();
1887 if (!BT_OffsetFree[*CheckKind])
1888 BT_OffsetFree[*CheckKind].reset(new BugType(
1889 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
1891 SmallString<100> buf;
1892 llvm::raw_svector_ostream os(buf);
1893 SmallString<20> AllocNameBuf;
1894 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1896 const MemRegion *MR = ArgVal.getAsRegion();
1897 assert(MR && "Only MemRegion based symbols can have offset free errors");
1899 RegionOffset Offset = MR->getAsOffset();
1900 assert((Offset.isValid() &&
1901 !Offset.hasSymbolicOffset() &&
1902 Offset.getOffset() != 0) &&
1903 "Only symbols with a valid offset can have offset free errors");
1905 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1907 os << "Argument to ";
1908 if (!printAllocDeallocName(os, C, DeallocExpr))
1909 os << "deallocator";
1910 os << " is offset by "
1913 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1914 << " from the start of ";
1915 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1916 os << "memory allocated by " << AllocNameOs.str();
1918 os << "allocated memory";
1920 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1921 R->markInteresting(MR->getBaseRegion());
1923 C.emitReport(std::move(R));
1926 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1927 SymbolRef Sym) const {
1929 if (!ChecksEnabled[CK_MallocChecker] &&
1930 !ChecksEnabled[CK_NewDeleteChecker])
1933 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1934 if (!CheckKind.hasValue())
1937 if (ExplodedNode *N = C.generateErrorNode()) {
1938 if (!BT_UseFree[*CheckKind])
1939 BT_UseFree[*CheckKind].reset(new BugType(
1940 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
1942 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1943 "Use of memory after it is freed", N);
1945 R->markInteresting(Sym);
1947 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1948 C.emitReport(std::move(R));
1952 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1953 bool Released, SymbolRef Sym,
1954 SymbolRef PrevSym) const {
1956 if (!ChecksEnabled[CK_MallocChecker] &&
1957 !ChecksEnabled[CK_NewDeleteChecker])
1960 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1961 if (!CheckKind.hasValue())
1964 if (ExplodedNode *N = C.generateErrorNode()) {
1965 if (!BT_DoubleFree[*CheckKind])
1966 BT_DoubleFree[*CheckKind].reset(new BugType(
1967 CheckNames[*CheckKind], "Double free", categories::MemoryError));
1969 auto R = llvm::make_unique<BugReport>(
1970 *BT_DoubleFree[*CheckKind],
1971 (Released ? "Attempt to free released memory"
1972 : "Attempt to free non-owned memory"),
1975 R->markInteresting(Sym);
1977 R->markInteresting(PrevSym);
1978 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1979 C.emitReport(std::move(R));
1983 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1985 if (!ChecksEnabled[CK_NewDeleteChecker])
1988 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1989 if (!CheckKind.hasValue())
1992 if (ExplodedNode *N = C.generateErrorNode()) {
1993 if (!BT_DoubleDelete)
1994 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1996 categories::MemoryError));
1998 auto R = llvm::make_unique<BugReport>(
1999 *BT_DoubleDelete, "Attempt to delete released memory", N);
2001 R->markInteresting(Sym);
2002 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2003 C.emitReport(std::move(R));
2007 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2009 SymbolRef Sym) const {
2011 if (!ChecksEnabled[CK_MallocChecker] &&
2012 !ChecksEnabled[CK_NewDeleteChecker])
2015 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2017 if (!CheckKind.hasValue())
2020 if (ExplodedNode *N = C.generateErrorNode()) {
2021 if (!BT_UseZerroAllocated[*CheckKind])
2022 BT_UseZerroAllocated[*CheckKind].reset(
2023 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2024 categories::MemoryError));
2026 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2027 "Use of zero-allocated memory", N);
2031 R->markInteresting(Sym);
2032 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2034 C.emitReport(std::move(R));
2038 void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2040 const Expr *FreeExpr) const {
2041 if (!ChecksEnabled[CK_MallocChecker])
2044 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2045 if (!CheckKind.hasValue())
2048 if (ExplodedNode *N = C.generateErrorNode()) {
2049 if (!BT_BadFree[*CheckKind])
2050 BT_BadFree[*CheckKind].reset(
2051 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
2053 SmallString<100> Buf;
2054 llvm::raw_svector_ostream Os(Buf);
2056 const MemRegion *MR = ArgVal.getAsRegion();
2057 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2058 MR = ER->getSuperRegion();
2060 Os << "Argument to ";
2061 if (!printAllocDeallocName(Os, C, FreeExpr))
2062 Os << "deallocator";
2064 Os << " is a function pointer";
2066 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2067 R->markInteresting(MR);
2069 C.emitReport(std::move(R));
2073 ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2076 ProgramStateRef State,
2077 bool SuffixWithN) const {
2081 if (SuffixWithN && CE->getNumArgs() < 3)
2083 else if (CE->getNumArgs() < 2)
2086 const Expr *arg0Expr = CE->getArg(0);
2087 const LocationContext *LCtx = C.getLocationContext();
2088 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
2089 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2091 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2093 SValBuilder &svalBuilder = C.getSValBuilder();
2095 DefinedOrUnknownSVal PtrEQ =
2096 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2098 // Get the size argument.
2099 const Expr *Arg1 = CE->getArg(1);
2101 // Get the value of the size argument.
2102 SVal TotalSize = State->getSVal(Arg1, LCtx);
2104 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2105 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2108 // Compare the size argument to 0.
2109 DefinedOrUnknownSVal SizeZero =
2110 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2111 svalBuilder.makeIntValWithPtrWidth(0, false));
2113 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2114 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2115 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2116 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2117 // We only assume exceptional states if they are definitely true; if the
2118 // state is under-constrained, assume regular realloc behavior.
2119 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2120 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2122 // If the ptr is NULL and the size is not 0, the call is equivalent to
2124 if (PrtIsNull && !SizeIsZero) {
2125 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
2126 UndefinedVal(), StatePtrIsNull);
2130 if (PrtIsNull && SizeIsZero)
2133 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2135 SymbolRef FromPtr = arg0Val.getAsSymbol();
2136 SVal RetVal = State->getSVal(CE, LCtx);
2137 SymbolRef ToPtr = RetVal.getAsSymbol();
2138 if (!FromPtr || !ToPtr)
2141 bool ReleasedAllocated = false;
2143 // If the size is 0, free the memory.
2145 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2146 false, ReleasedAllocated)){
2147 // The semantics of the return value are:
2148 // If size was equal to 0, either NULL or a pointer suitable to be passed
2149 // to free() is returned. We just free the input pointer and do not add
2150 // any constrains on the output pointer.
2154 // Default behavior.
2155 if (ProgramStateRef stateFree =
2156 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
2158 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
2159 UnknownVal(), stateFree);
2163 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2165 Kind = RPIsFreeOnFailure;
2166 else if (!ReleasedAllocated)
2167 Kind = RPDoNotTrackAfterFailure;
2169 // Record the info about the reallocated symbol so that we could properly
2170 // process failed reallocation.
2171 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2172 ReallocPair(FromPtr, Kind));
2173 // The reallocated symbol should stay alive for as long as the new symbol.
2174 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2175 return stateRealloc;
2180 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2181 ProgramStateRef State) {
2185 if (CE->getNumArgs() < 2)
2188 SValBuilder &svalBuilder = C.getSValBuilder();
2189 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2190 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
2192 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2196 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2197 CheckerContext &C) const {
2198 const LocationContext *LeakContext = N->getLocationContext();
2199 // Walk the ExplodedGraph backwards and find the first node that referred to
2200 // the tracked symbol.
2201 const ExplodedNode *AllocNode = N;
2202 const MemRegion *ReferenceRegion = nullptr;
2205 ProgramStateRef State = N->getState();
2206 if (!State->get<RegionState>(Sym))
2209 // Find the most recent expression bound to the symbol in the current
2211 if (!ReferenceRegion) {
2212 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2213 SVal Val = State->getSVal(MR);
2214 if (Val.getAsLocSymbol() == Sym) {
2215 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2216 // Do not show local variables belonging to a function other than
2217 // where the error is reported.
2219 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2220 ReferenceRegion = MR;
2225 // Allocation node, is the last node in the current or parent context in
2226 // which the symbol was tracked.
2227 const LocationContext *NContext = N->getLocationContext();
2228 if (NContext == LeakContext ||
2229 NContext->isParentOf(LeakContext))
2231 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2234 return LeakInfo(AllocNode, ReferenceRegion);
2237 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2238 CheckerContext &C) const {
2240 if (!ChecksEnabled[CK_MallocChecker] &&
2241 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2244 const RefState *RS = C.getState()->get<RegionState>(Sym);
2245 assert(RS && "cannot leak an untracked symbol");
2246 AllocationFamily Family = RS->getAllocationFamily();
2248 if (Family == AF_Alloca)
2251 Optional<MallocChecker::CheckKind>
2252 CheckKind = getCheckIfTracked(Family, true);
2254 if (!CheckKind.hasValue())
2258 if (!BT_Leak[*CheckKind]) {
2259 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2260 categories::MemoryError));
2261 // Leaks should not be reported if they are post-dominated by a sink:
2262 // (1) Sinks are higher importance bugs.
2263 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2264 // with __noreturn functions such as assert() or exit(). We choose not
2265 // to report leaks on such paths.
2266 BT_Leak[*CheckKind]->setSuppressOnSink(true);
2269 // Most bug reports are cached at the location where they occurred.
2270 // With leaks, we want to unique them by the location where they were
2271 // allocated, and only report a single path.
2272 PathDiagnosticLocation LocUsedForUniqueing;
2273 const ExplodedNode *AllocNode = nullptr;
2274 const MemRegion *Region = nullptr;
2275 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2277 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
2279 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2280 C.getSourceManager(),
2281 AllocNode->getLocationContext());
2283 SmallString<200> buf;
2284 llvm::raw_svector_ostream os(buf);
2285 if (Region && Region->canPrintPretty()) {
2286 os << "Potential leak of memory pointed to by ";
2287 Region->printPretty(os);
2289 os << "Potential memory leak";
2292 auto R = llvm::make_unique<BugReport>(
2293 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2294 AllocNode->getLocationContext()->getDecl());
2295 R->markInteresting(Sym);
2296 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2297 C.emitReport(std::move(R));
2300 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2301 CheckerContext &C) const
2303 if (!SymReaper.hasDeadSymbols())
2306 ProgramStateRef state = C.getState();
2307 RegionStateTy RS = state->get<RegionState>();
2308 RegionStateTy::Factory &F = state->get_context<RegionState>();
2310 SmallVector<SymbolRef, 2> Errors;
2311 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2312 if (SymReaper.isDead(I->first)) {
2313 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2314 Errors.push_back(I->first);
2315 // Remove the dead symbol from the map.
2316 RS = F.remove(RS, I->first);
2321 // Cleanup the Realloc Pairs Map.
2322 ReallocPairsTy RP = state->get<ReallocPairs>();
2323 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2324 if (SymReaper.isDead(I->first) ||
2325 SymReaper.isDead(I->second.ReallocatedSym)) {
2326 state = state->remove<ReallocPairs>(I->first);
2330 // Cleanup the FreeReturnValue Map.
2331 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2332 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2333 if (SymReaper.isDead(I->first) ||
2334 SymReaper.isDead(I->second)) {
2335 state = state->remove<FreeReturnValue>(I->first);
2339 // Generate leak node.
2340 ExplodedNode *N = C.getPredecessor();
2341 if (!Errors.empty()) {
2342 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2343 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2345 for (SmallVectorImpl<SymbolRef>::iterator
2346 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2347 reportLeak(*I, N, C);
2352 C.addTransition(state->set<RegionState>(RS), N);
2355 void MallocChecker::checkPreCall(const CallEvent &Call,
2356 CheckerContext &C) const {
2358 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2359 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2360 if (!Sym || checkDoubleDelete(Sym, C))
2364 // We will check for double free in the post visit.
2365 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2366 const FunctionDecl *FD = FC->getDecl();
2370 ASTContext &Ctx = C.getASTContext();
2371 if (ChecksEnabled[CK_MallocChecker] &&
2372 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2373 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2374 MemoryOperationKind::MOK_Free)))
2377 if (ChecksEnabled[CK_NewDeleteChecker] &&
2378 isStandardNewDelete(FD, Ctx))
2382 // Check if the callee of a method is deleted.
2383 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2384 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2385 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2389 // Check arguments for being used after free.
2390 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2391 SVal ArgSVal = Call.getArgSVal(I);
2392 if (ArgSVal.getAs<Loc>()) {
2393 SymbolRef Sym = ArgSVal.getAsSymbol();
2396 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2402 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2403 const Expr *E = S->getRetValue();
2407 // Check if we are returning a symbol.
2408 ProgramStateRef State = C.getState();
2409 SVal RetVal = State->getSVal(E, C.getLocationContext());
2410 SymbolRef Sym = RetVal.getAsSymbol();
2412 // If we are returning a field of the allocated struct or an array element,
2413 // the callee could still free the memory.
2414 // TODO: This logic should be a part of generic symbol escape callback.
2415 if (const MemRegion *MR = RetVal.getAsRegion())
2416 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2417 if (const SymbolicRegion *BMR =
2418 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2419 Sym = BMR->getSymbol();
2421 // Check if we are returning freed memory.
2423 checkUseAfterFree(Sym, C, E);
2426 // TODO: Blocks should be either inlined or should call invalidate regions
2427 // upon invocation. After that's in place, special casing here will not be
2429 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2430 CheckerContext &C) const {
2432 // Scan the BlockDecRefExprs for any object the retain count checker
2434 if (!BE->getBlockDecl()->hasCaptures())
2437 ProgramStateRef state = C.getState();
2438 const BlockDataRegion *R =
2439 cast<BlockDataRegion>(state->getSVal(BE,
2440 C.getLocationContext()).getAsRegion());
2442 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2443 E = R->referenced_vars_end();
2448 SmallVector<const MemRegion*, 10> Regions;
2449 const LocationContext *LC = C.getLocationContext();
2450 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2452 for ( ; I != E; ++I) {
2453 const VarRegion *VR = I.getCapturedRegion();
2454 if (VR->getSuperRegion() == R) {
2455 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2457 Regions.push_back(VR);
2461 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2462 Regions.data() + Regions.size()).getState();
2463 C.addTransition(state);
2466 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2468 const RefState *RS = C.getState()->get<RegionState>(Sym);
2469 return (RS && RS->isReleased());
2472 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2473 const Stmt *S) const {
2475 if (isReleased(Sym, C)) {
2476 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2483 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2484 const Stmt *S) const {
2487 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2488 if (RS->isAllocatedOfSizeZero())
2489 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2491 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2492 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2496 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2498 if (isReleased(Sym, C)) {
2499 ReportDoubleDelete(C, Sym);
2505 // Check if the location is a freed symbolic region.
2506 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2507 CheckerContext &C) const {
2508 SymbolRef Sym = l.getLocSymbolInBase();
2510 checkUseAfterFree(Sym, C, S);
2511 checkUseZeroAllocated(Sym, C, S);
2515 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2516 // it - assuming that allocation failed on this path.
2517 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2519 bool Assumption) const {
2520 RegionStateTy RS = state->get<RegionState>();
2521 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2522 // If the symbol is assumed to be NULL, remove it from consideration.
2523 ConstraintManager &CMgr = state->getConstraintManager();
2524 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2525 if (AllocFailed.isConstrainedTrue())
2526 state = state->remove<RegionState>(I.getKey());
2529 // Realloc returns 0 when reallocation fails, which means that we should
2530 // restore the state of the pointer being reallocated.
2531 ReallocPairsTy RP = state->get<ReallocPairs>();
2532 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2533 // If the symbol is assumed to be NULL, remove it from consideration.
2534 ConstraintManager &CMgr = state->getConstraintManager();
2535 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2536 if (!AllocFailed.isConstrainedTrue())
2539 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2540 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2541 if (RS->isReleased()) {
2542 if (I.getData().Kind == RPToBeFreedAfterFailure)
2543 state = state->set<RegionState>(ReallocSym,
2544 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2545 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2546 state = state->remove<RegionState>(ReallocSym);
2548 assert(I.getData().Kind == RPIsFreeOnFailure);
2551 state = state->remove<ReallocPairs>(I.getKey());
2557 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2558 const CallEvent *Call,
2559 ProgramStateRef State,
2560 SymbolRef &EscapingSymbol) const {
2562 EscapingSymbol = nullptr;
2564 // For now, assume that any C++ or block call can free memory.
2565 // TODO: If we want to be more optimistic here, we'll need to make sure that
2566 // regions escape to C++ containers. They seem to do that even now, but for
2567 // mysterious reasons.
2568 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2571 // Check Objective-C messages by selector name.
2572 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2573 // If it's not a framework call, or if it takes a callback, assume it
2575 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2578 // If it's a method we know about, handle it explicitly post-call.
2579 // This should happen before the "freeWhenDone" check below.
2580 if (isKnownDeallocObjCMethodName(*Msg))
2583 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2584 // about, we can't be sure that the object will use free() to deallocate the
2585 // memory, so we can't model it explicitly. The best we can do is use it to
2586 // decide whether the pointer escapes.
2587 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2588 return *FreeWhenDone;
2590 // If the first selector piece ends with "NoCopy", and there is no
2591 // "freeWhenDone" parameter set to zero, we know ownership is being
2592 // transferred. Again, though, we can't be sure that the object will use
2593 // free() to deallocate the memory, so we can't model it explicitly.
2594 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2595 if (FirstSlot.endswith("NoCopy"))
2598 // If the first selector starts with addPointer, insertPointer,
2599 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2600 // This is similar to C++ containers (vector); we still might want to check
2601 // that the pointers get freed by following the container itself.
2602 if (FirstSlot.startswith("addPointer") ||
2603 FirstSlot.startswith("insertPointer") ||
2604 FirstSlot.startswith("replacePointer") ||
2605 FirstSlot.equals("valueWithPointer")) {
2609 // We should escape receiver on call to 'init'. This is especially relevant
2610 // to the receiver, as the corresponding symbol is usually not referenced
2612 if (Msg->getMethodFamily() == OMF_init) {
2613 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2617 // Otherwise, assume that the method does not free memory.
2618 // Most framework methods do not free memory.
2622 // At this point the only thing left to handle is straight function calls.
2623 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2627 ASTContext &ASTC = State->getStateManager().getContext();
2629 // If it's one of the allocation functions we can reason about, we model
2630 // its behavior explicitly.
2631 if (isMemFunction(FD, ASTC))
2634 // If it's not a system call, assume it frees memory.
2635 if (!Call->isInSystemHeader())
2638 // White list the system functions whose arguments escape.
2639 const IdentifierInfo *II = FD->getIdentifier();
2642 StringRef FName = II->getName();
2644 // White list the 'XXXNoCopy' CoreFoundation functions.
2645 // We specifically check these before
2646 if (FName.endswith("NoCopy")) {
2647 // Look for the deallocator argument. We know that the memory ownership
2648 // is not transferred only if the deallocator argument is
2649 // 'kCFAllocatorNull'.
2650 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2651 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2652 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2653 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2654 if (DeallocatorName == "kCFAllocatorNull")
2661 // Associating streams with malloced buffers. The pointer can escape if
2662 // 'closefn' is specified (and if that function does free memory),
2663 // but it will not if closefn is not specified.
2664 // Currently, we do not inspect the 'closefn' function (PR12101).
2665 if (FName == "funopen")
2666 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2669 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2670 // these leaks might be intentional when setting the buffer for stdio.
2671 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2672 if (FName == "setbuf" || FName =="setbuffer" ||
2673 FName == "setlinebuf" || FName == "setvbuf") {
2674 if (Call->getNumArgs() >= 1) {
2675 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2676 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2677 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2678 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2683 // A bunch of other functions which either take ownership of a pointer or
2684 // wrap the result up in a struct or object, meaning it can be freed later.
2685 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2686 // but the Malloc checker cannot differentiate between them. The right way
2687 // of doing this would be to implement a pointer escapes callback.
2688 if (FName == "CGBitmapContextCreate" ||
2689 FName == "CGBitmapContextCreateWithData" ||
2690 FName == "CVPixelBufferCreateWithBytes" ||
2691 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2692 FName == "OSAtomicEnqueue") {
2696 if (FName == "postEvent" &&
2697 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2701 if (FName == "postEvent" &&
2702 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2706 if (FName == "connectImpl" &&
2707 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2711 // Handle cases where we know a buffer's /address/ can escape.
2712 // Note that the above checks handle some special cases where we know that
2713 // even though the address escapes, it's still our responsibility to free the
2715 if (Call->argumentsMayEscape())
2718 // Otherwise, assume that the function does not free memory.
2719 // Most system calls do not free the memory.
2723 static bool retTrue(const RefState *RS) {
2727 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2728 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2729 RS->getAllocationFamily() == AF_CXXNew);
2732 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2733 const InvalidatedSymbols &Escaped,
2734 const CallEvent *Call,
2735 PointerEscapeKind Kind) const {
2736 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2739 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2740 const InvalidatedSymbols &Escaped,
2741 const CallEvent *Call,
2742 PointerEscapeKind Kind) const {
2743 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2744 &checkIfNewOrNewArrayFamily);
2747 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2748 const InvalidatedSymbols &Escaped,
2749 const CallEvent *Call,
2750 PointerEscapeKind Kind,
2751 bool(*CheckRefState)(const RefState*)) const {
2752 // If we know that the call does not free memory, or we want to process the
2753 // call later, keep tracking the top level arguments.
2754 SymbolRef EscapingSymbol = nullptr;
2755 if (Kind == PSK_DirectEscapeOnCall &&
2756 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2762 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2767 if (EscapingSymbol && EscapingSymbol != sym)
2770 if (const RefState *RS = State->get<RegionState>(sym)) {
2771 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2772 CheckRefState(RS)) {
2773 State = State->remove<RegionState>(sym);
2774 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2781 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2782 ProgramStateRef prevState) {
2783 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2784 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2786 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2788 SymbolRef sym = I.getKey();
2789 if (!currMap.lookup(sym))
2796 std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2797 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2799 ProgramStateRef state = N->getState();
2800 ProgramStateRef statePrev = PrevN->getState();
2802 const RefState *RS = state->get<RegionState>(Sym);
2803 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2807 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2811 // FIXME: We will eventually need to handle non-statement-based events
2812 // (__attribute__((cleanup))).
2814 // Find out if this is an interesting point and what is the kind.
2815 const char *Msg = nullptr;
2816 StackHintGeneratorForSymbol *StackHint = nullptr;
2817 if (Mode == Normal) {
2818 if (isAllocated(RS, RSPrev, S)) {
2819 Msg = "Memory is allocated";
2820 StackHint = new StackHintGeneratorForSymbol(Sym,
2821 "Returned allocated memory");
2822 } else if (isReleased(RS, RSPrev, S)) {
2823 Msg = "Memory is released";
2824 StackHint = new StackHintGeneratorForSymbol(Sym,
2825 "Returning; memory was released");
2826 } else if (isRelinquished(RS, RSPrev, S)) {
2827 Msg = "Memory ownership is transferred";
2828 StackHint = new StackHintGeneratorForSymbol(Sym, "");
2829 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2830 Mode = ReallocationFailed;
2831 Msg = "Reallocation failed";
2832 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2833 "Reallocation failed");
2835 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2836 // Is it possible to fail two reallocs WITHOUT testing in between?
2837 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2838 "We only support one failed realloc at a time.");
2839 BR.markInteresting(sym);
2840 FailedReallocSymbol = sym;
2844 // We are in a special mode if a reallocation failed later in the path.
2845 } else if (Mode == ReallocationFailed) {
2846 assert(FailedReallocSymbol && "No symbol to look for.");
2848 // Is this is the first appearance of the reallocated symbol?
2849 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2850 // We're at the reallocation point.
2851 Msg = "Attempt to reallocate memory";
2852 StackHint = new StackHintGeneratorForSymbol(Sym,
2853 "Returned reallocated memory");
2854 FailedReallocSymbol = nullptr;
2863 // Generate the extra diagnostic.
2864 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2865 N->getLocationContext());
2866 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
2869 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2870 const char *NL, const char *Sep) const {
2872 RegionStateTy RS = State->get<RegionState>();
2874 if (!RS.isEmpty()) {
2875 Out << Sep << "MallocChecker :" << NL;
2876 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2877 const RefState *RefS = State->get<RegionState>(I.getKey());
2878 AllocationFamily Family = RefS->getAllocationFamily();
2879 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2880 if (!CheckKind.hasValue())
2881 CheckKind = getCheckIfTracked(Family, true);
2883 I.getKey()->dumpToStream(Out);
2885 I.getData().dump(Out);
2886 if (CheckKind.hasValue())
2887 Out << " (" << CheckNames[*CheckKind].getName() << ")";
2893 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2894 registerCStringCheckerBasic(mgr);
2895 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2896 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2897 "Optimistic", false, checker);
2898 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2899 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2900 mgr.getCurrentCheckName();
2901 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2903 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker]) {
2904 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2905 // FIXME: This does not set the correct name, but without this workaround
2906 // no name will be set at all.
2907 checker->CheckNames[MallocChecker::CK_NewDeleteChecker] =
2908 mgr.getCurrentCheckName();
2912 #define REGISTER_CHECKER(name) \
2913 void ento::register##name(CheckerManager &mgr) { \
2914 registerCStringCheckerBasic(mgr); \
2915 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2916 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2917 "Optimistic", false, checker); \
2918 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2919 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2922 REGISTER_CHECKER(MallocChecker)
2923 REGISTER_CHECKER(NewDeleteChecker)
2924 REGISTER_CHECKER(MismatchedDeallocatorChecker)