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), II_g_malloc_n(nullptr),
181 II_g_malloc0_n(nullptr), II_g_realloc_n(nullptr),
182 II_g_try_malloc_n(nullptr), II_g_try_malloc0_n(nullptr),
183 II_g_try_realloc_n(nullptr) {}
185 /// In pessimistic mode, the checker assumes that it does not know which
186 /// functions might free the memory.
190 CK_NewDeleteLeaksChecker,
191 CK_MismatchedDeallocatorChecker,
195 enum class MemoryOperationKind {
201 DefaultBool IsOptimistic;
203 DefaultBool ChecksEnabled[CK_NumCheckKinds];
204 CheckName CheckNames[CK_NumCheckKinds];
206 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
207 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
208 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
209 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
210 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
211 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
212 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
213 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
214 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
215 bool Assumption) const;
216 void checkLocation(SVal l, bool isLoad, const Stmt *S,
217 CheckerContext &C) const;
219 ProgramStateRef checkPointerEscape(ProgramStateRef State,
220 const InvalidatedSymbols &Escaped,
221 const CallEvent *Call,
222 PointerEscapeKind Kind) const;
223 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
224 const InvalidatedSymbols &Escaped,
225 const CallEvent *Call,
226 PointerEscapeKind Kind) const;
228 void printState(raw_ostream &Out, ProgramStateRef State,
229 const char *NL, const char *Sep) const override;
232 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
233 mutable std::unique_ptr<BugType> BT_DoubleDelete;
234 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
235 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
236 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
237 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
238 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
239 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
240 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
241 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
242 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
243 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
244 *II_if_nameindex, *II_if_freenameindex, *II_wcsdup,
245 *II_win_wcsdup, *II_g_malloc, *II_g_malloc0,
246 *II_g_realloc, *II_g_try_malloc, *II_g_try_malloc0,
247 *II_g_try_realloc, *II_g_free, *II_g_memdup,
248 *II_g_malloc_n, *II_g_malloc0_n, *II_g_realloc_n,
249 *II_g_try_malloc_n, *II_g_try_malloc0_n,
251 mutable Optional<uint64_t> KernelZeroFlagVal;
253 void initIdentifierInfo(ASTContext &C) const;
255 /// \brief Determine family of a deallocation expression.
256 AllocationFamily getAllocationFamily(CheckerContext &C, const Stmt *S) const;
258 /// \brief Print names of allocators and deallocators.
260 /// \returns true on success.
261 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
262 const Expr *E) const;
264 /// \brief Print expected name of an allocator based on the deallocator's
265 /// family derived from the DeallocExpr.
266 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
267 const Expr *DeallocExpr) const;
268 /// \brief Print expected name of a deallocator based on the allocator's
270 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) const;
273 /// Check if this is one of the functions which can allocate/reallocate memory
274 /// pointed to by one of its arguments.
275 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
276 bool isCMemFunction(const FunctionDecl *FD,
278 AllocationFamily Family,
279 MemoryOperationKind MemKind) const;
280 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
283 /// \brief Perform a zero-allocation check.
284 ProgramStateRef ProcessZeroAllocation(CheckerContext &C, const Expr *E,
285 const unsigned AllocationSizeArg,
286 ProgramStateRef State) const;
288 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
290 const OwnershipAttr* Att,
291 ProgramStateRef State) const;
292 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
293 const Expr *SizeEx, SVal Init,
294 ProgramStateRef State,
295 AllocationFamily Family = AF_Malloc);
296 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
297 SVal SizeEx, SVal Init,
298 ProgramStateRef State,
299 AllocationFamily Family = AF_Malloc);
301 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
302 ProgramStateRef State);
304 // Check if this malloc() for special flags. At present that means M_ZERO or
305 // __GFP_ZERO (in which case, treat it like calloc).
306 llvm::Optional<ProgramStateRef>
307 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
308 const ProgramStateRef &State) const;
310 /// Update the RefState to reflect the new memory allocation.
311 static ProgramStateRef
312 MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State,
313 AllocationFamily Family = AF_Malloc);
315 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
316 const OwnershipAttr* Att,
317 ProgramStateRef State) const;
318 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
319 ProgramStateRef state, unsigned Num,
321 bool &ReleasedAllocated,
322 bool ReturnsNullOnFailure = false) const;
323 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *Arg,
324 const Expr *ParentExpr,
325 ProgramStateRef State,
327 bool &ReleasedAllocated,
328 bool ReturnsNullOnFailure = false) const;
330 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
331 bool FreesMemOnFailure,
332 ProgramStateRef State,
333 bool SuffixWithN = false) const;
334 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
335 const Expr *BlockBytes);
336 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
337 ProgramStateRef State);
339 ///\brief Check if the memory associated with this symbol was released.
340 bool isReleased(SymbolRef Sym, CheckerContext &C) const;
342 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
344 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
345 const Stmt *S) const;
347 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
349 /// Check if the function is known free memory, or if it is
350 /// "interesting" and should be modeled explicitly.
352 /// \param [out] EscapingSymbol A function might not free memory in general,
353 /// but could be known to free a particular symbol. In this case, false is
354 /// returned and the single escaping symbol is returned through the out
357 /// We assume that pointers do not escape through calls to system functions
358 /// not handled by this checker.
359 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
360 ProgramStateRef State,
361 SymbolRef &EscapingSymbol) const;
363 // Implementation of the checkPointerEscape callabcks.
364 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
365 const InvalidatedSymbols &Escaped,
366 const CallEvent *Call,
367 PointerEscapeKind Kind,
368 bool(*CheckRefState)(const RefState*)) const;
371 /// Tells if a given family/call/symbol is tracked by the current checker.
372 /// Sets CheckKind to the kind of the checker responsible for this
373 /// family/call/symbol.
374 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
375 bool IsALeakCheck = false) const;
376 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
377 const Stmt *AllocDeallocStmt,
378 bool IsALeakCheck = false) const;
379 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
380 bool IsALeakCheck = false) const;
382 static bool SummarizeValue(raw_ostream &os, SVal V);
383 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
384 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
385 const Expr *DeallocExpr) const;
386 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
387 SourceRange Range) const;
388 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
389 const Expr *DeallocExpr, const RefState *RS,
390 SymbolRef Sym, bool OwnershipTransferred) const;
391 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
392 const Expr *DeallocExpr,
393 const Expr *AllocExpr = nullptr) const;
394 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
395 SymbolRef Sym) const;
396 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
397 SymbolRef Sym, SymbolRef PrevSym) const;
399 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
401 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
402 SymbolRef Sym) const;
404 /// Find the location of the allocation for Sym on the path leading to the
406 LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
407 CheckerContext &C) const;
409 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
411 /// The bug visitor which allows us to print extra diagnostics along the
412 /// BugReport path. For example, showing the allocation site of the leaked
414 class MallocBugVisitor final
415 : public BugReporterVisitorImpl<MallocBugVisitor> {
417 enum NotificationMode {
422 // The allocated region symbol tracked by the main analysis.
425 // The mode we are in, i.e. what kind of diagnostics will be emitted.
426 NotificationMode Mode;
428 // A symbol from when the primary region should have been reallocated.
429 SymbolRef FailedReallocSymbol;
434 MallocBugVisitor(SymbolRef S, bool isLeak = false)
435 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr), IsLeak(isLeak) {}
437 void Profile(llvm::FoldingSetNodeID &ID) const override {
443 inline bool isAllocated(const RefState *S, const RefState *SPrev,
445 // Did not track -> allocated. Other state (released) -> allocated.
446 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
447 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
448 (!SPrev || !(SPrev->isAllocated() ||
449 SPrev->isAllocatedOfSizeZero())));
452 inline bool isReleased(const RefState *S, const RefState *SPrev,
454 // Did not track -> released. Other state (allocated) -> released.
455 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt)) &&
456 (S && S->isReleased()) && (!SPrev || !SPrev->isReleased()));
459 inline bool isRelinquished(const RefState *S, const RefState *SPrev,
461 // Did not track -> relinquished. Other state (allocated) -> relinquished.
462 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
463 isa<ObjCPropertyRefExpr>(Stmt)) &&
464 (S && S->isRelinquished()) &&
465 (!SPrev || !SPrev->isRelinquished()));
468 inline bool isReallocFailedCheck(const RefState *S, const RefState *SPrev,
470 // If the expression is not a call, and the state change is
471 // released -> allocated, it must be the realloc return value
472 // check. If we have to handle more cases here, it might be cleaner just
473 // to track this extra bit in the state itself.
474 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
475 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
476 (SPrev && !(SPrev->isAllocated() ||
477 SPrev->isAllocatedOfSizeZero())));
480 std::shared_ptr<PathDiagnosticPiece> VisitNode(const ExplodedNode *N,
481 const ExplodedNode *PrevN,
482 BugReporterContext &BRC,
483 BugReport &BR) override;
485 std::unique_ptr<PathDiagnosticPiece>
486 getEndPath(BugReporterContext &BRC, const ExplodedNode *EndPathNode,
487 BugReport &BR) override {
491 PathDiagnosticLocation L =
492 PathDiagnosticLocation::createEndOfPath(EndPathNode,
493 BRC.getSourceManager());
494 // Do not add the statement itself as a range in case of leak.
495 return llvm::make_unique<PathDiagnosticEventPiece>(L, BR.getDescription(),
500 class StackHintGeneratorForReallocationFailed
501 : public StackHintGeneratorForSymbol {
503 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
504 : StackHintGeneratorForSymbol(S, M) {}
506 std::string getMessageForArg(const Expr *ArgE,
507 unsigned ArgIndex) override {
508 // Printed parameters start at 1, not 0.
511 SmallString<200> buf;
512 llvm::raw_svector_ostream os(buf);
514 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
515 << " parameter failed";
520 std::string getMessageForReturn(const CallExpr *CallExpr) override {
521 return "Reallocation of returned value failed";
526 } // end anonymous namespace
528 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
529 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
530 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
532 // A map from the freed symbol to the symbol representing the return value of
533 // the free function.
534 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
537 class StopTrackingCallback final : public SymbolVisitor {
538 ProgramStateRef state;
540 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
541 ProgramStateRef getState() const { return state; }
543 bool VisitSymbol(SymbolRef sym) override {
544 state = state->remove<RegionState>(sym);
548 } // end anonymous namespace
550 void MallocChecker::initIdentifierInfo(ASTContext &Ctx) const {
553 II_alloca = &Ctx.Idents.get("alloca");
554 II_malloc = &Ctx.Idents.get("malloc");
555 II_free = &Ctx.Idents.get("free");
556 II_realloc = &Ctx.Idents.get("realloc");
557 II_reallocf = &Ctx.Idents.get("reallocf");
558 II_calloc = &Ctx.Idents.get("calloc");
559 II_valloc = &Ctx.Idents.get("valloc");
560 II_strdup = &Ctx.Idents.get("strdup");
561 II_strndup = &Ctx.Idents.get("strndup");
562 II_wcsdup = &Ctx.Idents.get("wcsdup");
563 II_kmalloc = &Ctx.Idents.get("kmalloc");
564 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
565 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
567 //MSVC uses `_`-prefixed instead, so we check for them too.
568 II_win_strdup = &Ctx.Idents.get("_strdup");
569 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
570 II_win_alloca = &Ctx.Idents.get("_alloca");
573 II_g_malloc = &Ctx.Idents.get("g_malloc");
574 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
575 II_g_realloc = &Ctx.Idents.get("g_realloc");
576 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
577 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
578 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
579 II_g_free = &Ctx.Idents.get("g_free");
580 II_g_memdup = &Ctx.Idents.get("g_memdup");
581 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
582 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
583 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
584 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
585 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
586 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
589 bool MallocChecker::isMemFunction(const FunctionDecl *FD, ASTContext &C) const {
590 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
593 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
596 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
599 if (isStandardNewDelete(FD, C))
605 bool MallocChecker::isCMemFunction(const FunctionDecl *FD,
607 AllocationFamily Family,
608 MemoryOperationKind MemKind) const {
612 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
613 MemKind == MemoryOperationKind::MOK_Free);
614 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
615 MemKind == MemoryOperationKind::MOK_Allocate);
617 if (FD->getKind() == Decl::Function) {
618 const IdentifierInfo *FunI = FD->getIdentifier();
619 initIdentifierInfo(C);
621 if (Family == AF_Malloc && CheckFree) {
622 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
627 if (Family == AF_Malloc && CheckAlloc) {
628 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
629 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
630 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
631 FunI == II_win_wcsdup || FunI == II_kmalloc ||
632 FunI == II_g_malloc || FunI == II_g_malloc0 ||
633 FunI == II_g_realloc || FunI == II_g_try_malloc ||
634 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
635 FunI == II_g_memdup || FunI == II_g_malloc_n ||
636 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
637 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
638 FunI == II_g_try_realloc_n)
642 if (Family == AF_IfNameIndex && CheckFree) {
643 if (FunI == II_if_freenameindex)
647 if (Family == AF_IfNameIndex && CheckAlloc) {
648 if (FunI == II_if_nameindex)
652 if (Family == AF_Alloca && CheckAlloc) {
653 if (FunI == II_alloca || FunI == II_win_alloca)
658 if (Family != AF_Malloc)
661 if (IsOptimistic && FD->hasAttrs()) {
662 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
663 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
664 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
667 } else if (OwnKind == OwnershipAttr::Returns) {
677 // Tells if the callee is one of the following:
678 // 1) A global non-placement new/delete operator function.
679 // 2) A global placement operator function with the single placement argument
680 // of type std::nothrow_t.
681 bool MallocChecker::isStandardNewDelete(const FunctionDecl *FD,
682 ASTContext &C) const {
686 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
687 if (Kind != OO_New && Kind != OO_Array_New &&
688 Kind != OO_Delete && Kind != OO_Array_Delete)
691 // Skip all operator new/delete methods.
692 if (isa<CXXMethodDecl>(FD))
695 // Return true if tested operator is a standard placement nothrow operator.
696 if (FD->getNumParams() == 2) {
697 QualType T = FD->getParamDecl(1)->getType();
698 if (const IdentifierInfo *II = T.getBaseTypeIdentifier())
699 return II->getName().equals("nothrow_t");
702 // Skip placement operators.
703 if (FD->getNumParams() != 1 || FD->isVariadic())
706 // One of the standard new/new[]/delete/delete[] non-placement operators.
710 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
711 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
712 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
714 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
716 // One of the possible flags is M_ZERO, which means 'give me back an
717 // allocation which is already zeroed', like calloc.
719 // 2-argument kmalloc(), as used in the Linux kernel:
721 // void *kmalloc(size_t size, gfp_t flags);
723 // Has the similar flag value __GFP_ZERO.
725 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
726 // code could be shared.
728 ASTContext &Ctx = C.getASTContext();
729 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
731 if (!KernelZeroFlagVal.hasValue()) {
732 if (OS == llvm::Triple::FreeBSD)
733 KernelZeroFlagVal = 0x0100;
734 else if (OS == llvm::Triple::NetBSD)
735 KernelZeroFlagVal = 0x0002;
736 else if (OS == llvm::Triple::OpenBSD)
737 KernelZeroFlagVal = 0x0008;
738 else if (OS == llvm::Triple::Linux)
740 KernelZeroFlagVal = 0x8000;
742 // FIXME: We need a more general way of getting the M_ZERO value.
743 // See also: O_CREAT in UnixAPIChecker.cpp.
745 // Fall back to normal malloc behavior on platforms where we don't
750 // We treat the last argument as the flags argument, and callers fall-back to
751 // normal malloc on a None return. This works for the FreeBSD kernel malloc
752 // as well as Linux kmalloc.
753 if (CE->getNumArgs() < 2)
756 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
757 const SVal V = State->getSVal(FlagsEx, C.getLocationContext());
758 if (!V.getAs<NonLoc>()) {
759 // The case where 'V' can be a location can only be due to a bad header,
760 // so in this case bail out.
764 NonLoc Flags = V.castAs<NonLoc>();
765 NonLoc ZeroFlag = C.getSValBuilder()
766 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
768 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
771 if (MaskedFlagsUC.isUnknownOrUndef())
773 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
775 // Check if maskedFlags is non-zero.
776 ProgramStateRef TrueState, FalseState;
777 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
779 // If M_ZERO is set, treat this like calloc (initialized).
780 if (TrueState && !FalseState) {
781 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
782 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
788 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
789 const Expr *BlockBytes) {
790 SValBuilder &SB = C.getSValBuilder();
791 SVal BlocksVal = C.getSVal(Blocks);
792 SVal BlockBytesVal = C.getSVal(BlockBytes);
793 ProgramStateRef State = C.getState();
794 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
795 SB.getContext().getSizeType());
799 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
803 const FunctionDecl *FD = C.getCalleeDecl(CE);
807 ProgramStateRef State = C.getState();
808 bool ReleasedAllocatedMemory = false;
810 if (FD->getKind() == Decl::Function) {
811 initIdentifierInfo(C.getASTContext());
812 IdentifierInfo *FunI = FD->getIdentifier();
814 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
815 if (CE->getNumArgs() < 1)
817 if (CE->getNumArgs() < 3) {
818 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
819 if (CE->getNumArgs() == 1)
820 State = ProcessZeroAllocation(C, CE, 0, State);
821 } else if (CE->getNumArgs() == 3) {
822 llvm::Optional<ProgramStateRef> MaybeState =
823 performKernelMalloc(CE, C, State);
824 if (MaybeState.hasValue())
825 State = MaybeState.getValue();
827 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
829 } else if (FunI == II_kmalloc) {
830 if (CE->getNumArgs() < 1)
832 llvm::Optional<ProgramStateRef> MaybeState =
833 performKernelMalloc(CE, C, State);
834 if (MaybeState.hasValue())
835 State = MaybeState.getValue();
837 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
838 } else if (FunI == II_valloc) {
839 if (CE->getNumArgs() < 1)
841 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
842 State = ProcessZeroAllocation(C, CE, 0, State);
843 } else if (FunI == II_realloc || FunI == II_g_realloc ||
844 FunI == II_g_try_realloc) {
845 State = ReallocMemAux(C, CE, false, State);
846 State = ProcessZeroAllocation(C, CE, 1, State);
847 } else if (FunI == II_reallocf) {
848 State = ReallocMemAux(C, CE, true, State);
849 State = ProcessZeroAllocation(C, CE, 1, State);
850 } else if (FunI == II_calloc) {
851 State = CallocMem(C, CE, State);
852 State = ProcessZeroAllocation(C, CE, 0, State);
853 State = ProcessZeroAllocation(C, CE, 1, State);
854 } else if (FunI == II_free || FunI == II_g_free) {
855 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
856 } else if (FunI == II_strdup || FunI == II_win_strdup ||
857 FunI == II_wcsdup || FunI == II_win_wcsdup) {
858 State = MallocUpdateRefState(C, CE, State);
859 } else if (FunI == II_strndup) {
860 State = MallocUpdateRefState(C, CE, State);
861 } else if (FunI == II_alloca || FunI == II_win_alloca) {
862 if (CE->getNumArgs() < 1)
864 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
866 State = ProcessZeroAllocation(C, CE, 0, State);
867 } else if (isStandardNewDelete(FD, C.getASTContext())) {
868 // Process direct calls to operator new/new[]/delete/delete[] functions
869 // as distinct from new/new[]/delete/delete[] expressions that are
870 // processed by the checkPostStmt callbacks for CXXNewExpr and
872 OverloadedOperatorKind K = FD->getOverloadedOperator();
874 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
876 State = ProcessZeroAllocation(C, CE, 0, State);
878 else if (K == OO_Array_New) {
879 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
881 State = ProcessZeroAllocation(C, CE, 0, State);
883 else if (K == OO_Delete || K == OO_Array_Delete)
884 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
886 llvm_unreachable("not a new/delete operator");
887 } else if (FunI == II_if_nameindex) {
888 // Should we model this differently? We can allocate a fixed number of
889 // elements with zeros in the last one.
890 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
892 } else if (FunI == II_if_freenameindex) {
893 State = FreeMemAux(C, CE, State, 0, false, ReleasedAllocatedMemory);
894 } else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
895 if (CE->getNumArgs() < 1)
897 SValBuilder &svalBuilder = C.getSValBuilder();
898 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
899 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
900 State = ProcessZeroAllocation(C, CE, 0, State);
901 } else if (FunI == II_g_memdup) {
902 if (CE->getNumArgs() < 2)
904 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
905 State = ProcessZeroAllocation(C, CE, 1, State);
906 } else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
907 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
908 if (CE->getNumArgs() < 2)
910 SVal Init = UndefinedVal();
911 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
912 SValBuilder &SB = C.getSValBuilder();
913 Init = SB.makeZeroVal(SB.getContext().CharTy);
915 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
916 State = MallocMemAux(C, CE, TotalSize, Init, State);
917 State = ProcessZeroAllocation(C, CE, 0, State);
918 State = ProcessZeroAllocation(C, CE, 1, State);
919 } else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
920 if (CE->getNumArgs() < 3)
922 State = ReallocMemAux(C, CE, false, State, true);
923 State = ProcessZeroAllocation(C, CE, 1, State);
924 State = ProcessZeroAllocation(C, CE, 2, State);
928 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
929 // Check all the attributes, if there are any.
930 // There can be multiple of these attributes.
932 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
933 switch (I->getOwnKind()) {
934 case OwnershipAttr::Returns:
935 State = MallocMemReturnsAttr(C, CE, I, State);
937 case OwnershipAttr::Takes:
938 case OwnershipAttr::Holds:
939 State = FreeMemAttr(C, CE, I, State);
944 C.addTransition(State);
947 // Performs a 0-sized allocations check.
948 ProgramStateRef MallocChecker::ProcessZeroAllocation(CheckerContext &C,
950 const unsigned AllocationSizeArg,
951 ProgramStateRef State) const {
955 const Expr *Arg = nullptr;
957 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
958 Arg = CE->getArg(AllocationSizeArg);
960 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
962 Arg = NE->getArraySize();
967 llvm_unreachable("not a CallExpr or CXXNewExpr");
971 Optional<DefinedSVal> DefArgVal =
972 State->getSVal(Arg, C.getLocationContext()).getAs<DefinedSVal>();
977 // Check if the allocation size is 0.
978 ProgramStateRef TrueState, FalseState;
979 SValBuilder &SvalBuilder = C.getSValBuilder();
981 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
983 std::tie(TrueState, FalseState) =
984 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
986 if (TrueState && !FalseState) {
987 SVal retVal = State->getSVal(E, C.getLocationContext());
988 SymbolRef Sym = retVal.getAsLocSymbol();
992 const RefState *RS = State->get<RegionState>(Sym);
994 if (RS->isAllocated())
995 return TrueState->set<RegionState>(Sym,
996 RefState::getAllocatedOfSizeZero(RS));
1000 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1001 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1002 // tracked. Add zero-reallocated Sym to the state to catch references
1003 // to zero-allocated memory.
1004 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1008 // Assume the value is non-zero going forward.
1013 static QualType getDeepPointeeType(QualType T) {
1014 QualType Result = T, PointeeType = T->getPointeeType();
1015 while (!PointeeType.isNull()) {
1016 Result = PointeeType;
1017 PointeeType = PointeeType->getPointeeType();
1022 static bool treatUnusedNewEscaped(const CXXNewExpr *NE) {
1024 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1028 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1031 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1033 // Iterate over the constructor parameters.
1034 for (const auto *CtorParam : CtorD->parameters()) {
1036 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1037 if (CtorParamPointeeT.isNull())
1040 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1042 if (CtorParamPointeeT->getAsCXXRecordDecl())
1049 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1050 CheckerContext &C) const {
1052 if (NE->getNumPlacementArgs())
1053 for (CXXNewExpr::const_arg_iterator I = NE->placement_arg_begin(),
1054 E = NE->placement_arg_end(); I != E; ++I)
1055 if (SymbolRef Sym = C.getSVal(*I).getAsSymbol())
1056 checkUseAfterFree(Sym, C, *I);
1058 if (!isStandardNewDelete(NE->getOperatorNew(), C.getASTContext()))
1061 ParentMap &PM = C.getLocationContext()->getParentMap();
1062 if (!PM.isConsumedExpr(NE) && treatUnusedNewEscaped(NE))
1065 ProgramStateRef State = C.getState();
1066 // The return value from operator new is bound to a specified initialization
1067 // value (if any) and we don't want to loose this value. So we call
1068 // MallocUpdateRefState() instead of MallocMemAux() which breakes the
1069 // existing binding.
1070 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
1072 State = addExtentSize(C, NE, State);
1073 State = ProcessZeroAllocation(C, NE, 0, State);
1074 C.addTransition(State);
1077 // Sets the extent value of the MemRegion allocated by
1078 // new expression NE to its size in Bytes.
1080 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1081 const CXXNewExpr *NE,
1082 ProgramStateRef State) {
1085 SValBuilder &svalBuilder = C.getSValBuilder();
1087 const LocationContext *LCtx = C.getLocationContext();
1088 const SubRegion *Region;
1089 if (NE->isArray()) {
1090 const Expr *SizeExpr = NE->getArraySize();
1091 ElementCount = State->getSVal(SizeExpr, C.getLocationContext());
1092 // Store the extent size for the (symbolic)region
1093 // containing the elements.
1094 Region = (State->getSVal(NE, LCtx))
1096 ->getAs<SubRegion>()
1098 ->getAs<SubRegion>();
1100 ElementCount = svalBuilder.makeIntVal(1, true);
1101 Region = (State->getSVal(NE, LCtx)).getAsRegion()->getAs<SubRegion>();
1105 // Set the region's extent equal to the Size in Bytes.
1106 QualType ElementType = NE->getAllocatedType();
1107 ASTContext &AstContext = C.getASTContext();
1108 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1110 if (ElementCount.getAs<NonLoc>()) {
1111 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1112 // size in Bytes = ElementCount*TypeSize
1113 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1114 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1115 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1116 svalBuilder.getArrayIndexType());
1117 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1118 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1119 State = State->assume(extentMatchesSize, true);
1124 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1125 CheckerContext &C) const {
1127 if (!ChecksEnabled[CK_NewDeleteChecker])
1128 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1129 checkUseAfterFree(Sym, C, DE->getArgument());
1131 if (!isStandardNewDelete(DE->getOperatorDelete(), C.getASTContext()))
1134 ProgramStateRef State = C.getState();
1135 bool ReleasedAllocated;
1136 State = FreeMemAux(C, DE->getArgument(), DE, State,
1137 /*Hold*/false, ReleasedAllocated);
1139 C.addTransition(State);
1142 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1143 // If the first selector piece is one of the names below, assume that the
1144 // object takes ownership of the memory, promising to eventually deallocate it
1146 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1147 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1148 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1149 return FirstSlot == "dataWithBytesNoCopy" ||
1150 FirstSlot == "initWithBytesNoCopy" ||
1151 FirstSlot == "initWithCharactersNoCopy";
1154 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1155 Selector S = Call.getSelector();
1157 // FIXME: We should not rely on fully-constrained symbols being folded.
1158 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1159 if (S.getNameForSlot(i).equals("freeWhenDone"))
1160 return !Call.getArgSVal(i).isZeroConstant();
1165 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1166 CheckerContext &C) const {
1170 if (!isKnownDeallocObjCMethodName(Call))
1173 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1177 bool ReleasedAllocatedMemory;
1178 ProgramStateRef State = FreeMemAux(C, Call.getArgExpr(0),
1179 Call.getOriginExpr(), C.getState(),
1180 /*Hold=*/true, ReleasedAllocatedMemory,
1181 /*RetNullOnFailure=*/true);
1183 C.addTransition(State);
1187 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1188 const OwnershipAttr *Att,
1189 ProgramStateRef State) const {
1193 if (Att->getModule() != II_malloc)
1196 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1198 return MallocMemAux(C, CE, CE->getArg(*I), UndefinedVal(), State);
1200 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1203 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1205 const Expr *SizeEx, SVal Init,
1206 ProgramStateRef State,
1207 AllocationFamily Family) {
1211 return MallocMemAux(C, CE, State->getSVal(SizeEx, C.getLocationContext()),
1212 Init, State, Family);
1215 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1217 SVal Size, SVal Init,
1218 ProgramStateRef State,
1219 AllocationFamily Family) {
1223 // We expect the malloc functions to return a pointer.
1224 if (!Loc::isLocType(CE->getType()))
1227 // Bind the return value to the symbolic value from the heap region.
1228 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1229 // side effects other than what we model here.
1230 unsigned Count = C.blockCount();
1231 SValBuilder &svalBuilder = C.getSValBuilder();
1232 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1233 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1234 .castAs<DefinedSVal>();
1235 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1237 // Fill the region with the initialization value.
1238 State = State->bindDefault(RetVal, Init, LCtx);
1240 // Set the region's extent equal to the Size parameter.
1241 const SymbolicRegion *R =
1242 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1245 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1246 Size.getAs<DefinedOrUnknownSVal>()) {
1247 SValBuilder &svalBuilder = C.getSValBuilder();
1248 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1249 DefinedOrUnknownSVal extentMatchesSize =
1250 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1252 State = State->assume(extentMatchesSize, true);
1256 return MallocUpdateRefState(C, CE, State, Family);
1259 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1261 ProgramStateRef State,
1262 AllocationFamily Family) {
1266 // Get the return value.
1267 SVal retVal = State->getSVal(E, C.getLocationContext());
1269 // We expect the malloc functions to return a pointer.
1270 if (!retVal.getAs<Loc>())
1273 SymbolRef Sym = retVal.getAsLocSymbol();
1276 // Set the symbol's state to Allocated.
1277 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1280 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1282 const OwnershipAttr *Att,
1283 ProgramStateRef State) const {
1287 if (Att->getModule() != II_malloc)
1290 bool ReleasedAllocated = false;
1292 for (const auto &Arg : Att->args()) {
1293 ProgramStateRef StateI = FreeMemAux(C, CE, State, Arg,
1294 Att->getOwnKind() == OwnershipAttr::Holds,
1302 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1304 ProgramStateRef State,
1307 bool &ReleasedAllocated,
1308 bool ReturnsNullOnFailure) const {
1312 if (CE->getNumArgs() < (Num + 1))
1315 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold,
1316 ReleasedAllocated, ReturnsNullOnFailure);
1319 /// Checks if the previous call to free on the given symbol failed - if free
1320 /// failed, returns true. Also, returns the corresponding return value symbol.
1321 static bool didPreviousFreeFail(ProgramStateRef State,
1322 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1323 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1325 assert(*Ret && "We should not store the null return symbol");
1326 ConstraintManager &CMgr = State->getConstraintManager();
1327 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1328 RetStatusSymbol = *Ret;
1329 return FreeFailed.isConstrainedTrue();
1334 AllocationFamily MallocChecker::getAllocationFamily(CheckerContext &C,
1335 const Stmt *S) const {
1339 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1340 const FunctionDecl *FD = C.getCalleeDecl(CE);
1343 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1345 ASTContext &Ctx = C.getASTContext();
1347 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1350 if (isStandardNewDelete(FD, Ctx)) {
1351 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1352 if (Kind == OO_New || Kind == OO_Delete)
1354 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1355 return AF_CXXNewArray;
1358 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1359 return AF_IfNameIndex;
1361 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1367 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1368 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1370 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1371 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1373 if (isa<ObjCMessageExpr>(S))
1379 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1380 const Expr *E) const {
1381 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1382 // FIXME: This doesn't handle indirect calls.
1383 const FunctionDecl *FD = CE->getDirectCallee();
1388 if (!FD->isOverloadedOperator())
1393 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1394 if (Msg->isInstanceMessage())
1398 Msg->getSelector().print(os);
1402 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1404 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1409 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1411 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1419 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1420 const Expr *E) const {
1421 AllocationFamily Family = getAllocationFamily(C, E);
1424 case AF_Malloc: os << "malloc()"; return;
1425 case AF_CXXNew: os << "'new'"; return;
1426 case AF_CXXNewArray: os << "'new[]'"; return;
1427 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1429 case AF_None: llvm_unreachable("not a deallocation expression");
1433 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1434 AllocationFamily Family) const {
1436 case AF_Malloc: os << "free()"; return;
1437 case AF_CXXNew: os << "'delete'"; return;
1438 case AF_CXXNewArray: os << "'delete[]'"; return;
1439 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1441 case AF_None: llvm_unreachable("suspicious argument");
1445 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1446 const Expr *ArgExpr,
1447 const Expr *ParentExpr,
1448 ProgramStateRef State,
1450 bool &ReleasedAllocated,
1451 bool ReturnsNullOnFailure) const {
1456 SVal ArgVal = State->getSVal(ArgExpr, C.getLocationContext());
1457 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1459 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1461 // Check for null dereferences.
1462 if (!location.getAs<Loc>())
1465 // The explicit NULL case, no operation is performed.
1466 ProgramStateRef notNullState, nullState;
1467 std::tie(notNullState, nullState) = State->assume(location);
1468 if (nullState && !notNullState)
1471 // Unknown values could easily be okay
1472 // Undefined values are handled elsewhere
1473 if (ArgVal.isUnknownOrUndef())
1476 const MemRegion *R = ArgVal.getAsRegion();
1478 // Nonlocs can't be freed, of course.
1479 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1481 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1485 R = R->StripCasts();
1487 // Blocks might show up as heap data, but should not be free()d
1488 if (isa<BlockDataRegion>(R)) {
1489 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1493 const MemSpaceRegion *MS = R->getMemorySpace();
1495 // Parameters, locals, statics, globals, and memory returned by
1496 // __builtin_alloca() shouldn't be freed.
1497 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1498 // FIXME: at the time this code was written, malloc() regions were
1499 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1500 // This means that there isn't actually anything from HeapSpaceRegion
1501 // that should be freed, even though we allow it here.
1502 // Of course, free() can work on memory allocated outside the current
1503 // function, so UnknownSpaceRegion is always a possibility.
1504 // False negatives are better than false positives.
1506 if (isa<AllocaRegion>(R))
1507 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1509 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1514 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1515 // Various cases could lead to non-symbol values here.
1516 // For now, ignore them.
1520 SymbolRef SymBase = SrBase->getSymbol();
1521 const RefState *RsBase = State->get<RegionState>(SymBase);
1522 SymbolRef PreviousRetStatusSymbol = nullptr;
1526 // Memory returned by alloca() shouldn't be freed.
1527 if (RsBase->getAllocationFamily() == AF_Alloca) {
1528 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1532 // Check for double free first.
1533 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1534 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1535 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1536 SymBase, PreviousRetStatusSymbol);
1539 // If the pointer is allocated or escaped, but we are now trying to free it,
1540 // check that the call to free is proper.
1541 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1542 RsBase->isEscaped()) {
1544 // Check if an expected deallocation function matches the real one.
1545 bool DeallocMatchesAlloc =
1546 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1547 if (!DeallocMatchesAlloc) {
1548 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1549 ParentExpr, RsBase, SymBase, Hold);
1553 // Check if the memory location being freed is the actual location
1554 // allocated, or an offset.
1555 RegionOffset Offset = R->getAsOffset();
1556 if (Offset.isValid() &&
1557 !Offset.hasSymbolicOffset() &&
1558 Offset.getOffset() != 0) {
1559 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1560 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1567 ReleasedAllocated = (RsBase != nullptr) && (RsBase->isAllocated() ||
1568 RsBase->isAllocatedOfSizeZero());
1570 // Clean out the info on previous call to free return info.
1571 State = State->remove<FreeReturnValue>(SymBase);
1573 // Keep track of the return value. If it is NULL, we will know that free
1575 if (ReturnsNullOnFailure) {
1576 SVal RetVal = C.getSVal(ParentExpr);
1577 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1578 if (RetStatusSymbol) {
1579 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1580 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1584 AllocationFamily Family = RsBase ? RsBase->getAllocationFamily()
1585 : getAllocationFamily(C, ParentExpr);
1588 return State->set<RegionState>(SymBase,
1589 RefState::getRelinquished(Family,
1592 return State->set<RegionState>(SymBase,
1593 RefState::getReleased(Family, ParentExpr));
1596 Optional<MallocChecker::CheckKind>
1597 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1598 bool IsALeakCheck) const {
1602 case AF_IfNameIndex: {
1603 if (ChecksEnabled[CK_MallocChecker])
1604 return CK_MallocChecker;
1606 return Optional<MallocChecker::CheckKind>();
1609 case AF_CXXNewArray: {
1611 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1612 return CK_NewDeleteLeaksChecker;
1615 if (ChecksEnabled[CK_NewDeleteChecker])
1616 return CK_NewDeleteChecker;
1618 return Optional<MallocChecker::CheckKind>();
1621 llvm_unreachable("no family");
1624 llvm_unreachable("unhandled family");
1627 Optional<MallocChecker::CheckKind>
1628 MallocChecker::getCheckIfTracked(CheckerContext &C,
1629 const Stmt *AllocDeallocStmt,
1630 bool IsALeakCheck) const {
1631 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1635 Optional<MallocChecker::CheckKind>
1636 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1637 bool IsALeakCheck) const {
1638 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1639 return CK_MallocChecker;
1641 const RefState *RS = C.getState()->get<RegionState>(Sym);
1643 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1646 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1647 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1648 os << "an integer (" << IntVal->getValue() << ")";
1649 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1650 os << "a constant address (" << ConstAddr->getValue() << ")";
1651 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1652 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1659 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1660 const MemRegion *MR) {
1661 switch (MR->getKind()) {
1662 case MemRegion::FunctionCodeRegionKind: {
1663 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1665 os << "the address of the function '" << *FD << '\'';
1667 os << "the address of a function";
1670 case MemRegion::BlockCodeRegionKind:
1673 case MemRegion::BlockDataRegionKind:
1674 // FIXME: where the block came from?
1678 const MemSpaceRegion *MS = MR->getMemorySpace();
1680 if (isa<StackLocalsSpaceRegion>(MS)) {
1681 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1689 os << "the address of the local variable '" << VD->getName() << "'";
1691 os << "the address of a local stack variable";
1695 if (isa<StackArgumentsSpaceRegion>(MS)) {
1696 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1704 os << "the address of the parameter '" << VD->getName() << "'";
1706 os << "the address of a parameter";
1710 if (isa<GlobalsSpaceRegion>(MS)) {
1711 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1719 if (VD->isStaticLocal())
1720 os << "the address of the static variable '" << VD->getName() << "'";
1722 os << "the address of the global variable '" << VD->getName() << "'";
1724 os << "the address of a global variable";
1733 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1735 const Expr *DeallocExpr) const {
1737 if (!ChecksEnabled[CK_MallocChecker] &&
1738 !ChecksEnabled[CK_NewDeleteChecker])
1741 Optional<MallocChecker::CheckKind> CheckKind =
1742 getCheckIfTracked(C, DeallocExpr);
1743 if (!CheckKind.hasValue())
1746 if (ExplodedNode *N = C.generateErrorNode()) {
1747 if (!BT_BadFree[*CheckKind])
1748 BT_BadFree[*CheckKind].reset(
1749 new BugType(CheckNames[*CheckKind], "Bad free", "Memory Error"));
1751 SmallString<100> buf;
1752 llvm::raw_svector_ostream os(buf);
1754 const MemRegion *MR = ArgVal.getAsRegion();
1755 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1756 MR = ER->getSuperRegion();
1758 os << "Argument to ";
1759 if (!printAllocDeallocName(os, C, DeallocExpr))
1760 os << "deallocator";
1763 bool Summarized = MR ? SummarizeRegion(os, MR)
1764 : SummarizeValue(os, ArgVal);
1766 os << ", which is not memory allocated by ";
1768 os << "not memory allocated by ";
1770 printExpectedAllocName(os, C, DeallocExpr);
1772 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1773 R->markInteresting(MR);
1775 C.emitReport(std::move(R));
1779 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1780 SourceRange Range) const {
1782 Optional<MallocChecker::CheckKind> CheckKind;
1784 if (ChecksEnabled[CK_MallocChecker])
1785 CheckKind = CK_MallocChecker;
1786 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1787 CheckKind = CK_MismatchedDeallocatorChecker;
1791 if (ExplodedNode *N = C.generateErrorNode()) {
1792 if (!BT_FreeAlloca[*CheckKind])
1793 BT_FreeAlloca[*CheckKind].reset(
1794 new BugType(CheckNames[*CheckKind], "Free alloca()", "Memory Error"));
1796 auto R = llvm::make_unique<BugReport>(
1797 *BT_FreeAlloca[*CheckKind],
1798 "Memory allocated by alloca() should not be deallocated", N);
1799 R->markInteresting(ArgVal.getAsRegion());
1801 C.emitReport(std::move(R));
1805 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1807 const Expr *DeallocExpr,
1810 bool OwnershipTransferred) const {
1812 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1815 if (ExplodedNode *N = C.generateErrorNode()) {
1816 if (!BT_MismatchedDealloc)
1817 BT_MismatchedDealloc.reset(
1818 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1819 "Bad deallocator", "Memory Error"));
1821 SmallString<100> buf;
1822 llvm::raw_svector_ostream os(buf);
1824 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1825 SmallString<20> AllocBuf;
1826 llvm::raw_svector_ostream AllocOs(AllocBuf);
1827 SmallString<20> DeallocBuf;
1828 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1830 if (OwnershipTransferred) {
1831 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1832 os << DeallocOs.str() << " cannot";
1836 os << " take ownership of memory";
1838 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1839 os << " allocated by " << AllocOs.str();
1842 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1843 os << " allocated by " << AllocOs.str();
1845 os << " should be deallocated by ";
1846 printExpectedDeallocName(os, RS->getAllocationFamily());
1848 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1849 os << ", not " << DeallocOs.str();
1852 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1853 R->markInteresting(Sym);
1855 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1856 C.emitReport(std::move(R));
1860 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1861 SourceRange Range, const Expr *DeallocExpr,
1862 const Expr *AllocExpr) const {
1865 if (!ChecksEnabled[CK_MallocChecker] &&
1866 !ChecksEnabled[CK_NewDeleteChecker])
1869 Optional<MallocChecker::CheckKind> CheckKind =
1870 getCheckIfTracked(C, AllocExpr);
1871 if (!CheckKind.hasValue())
1874 ExplodedNode *N = C.generateErrorNode();
1878 if (!BT_OffsetFree[*CheckKind])
1879 BT_OffsetFree[*CheckKind].reset(
1880 new BugType(CheckNames[*CheckKind], "Offset free", "Memory Error"));
1882 SmallString<100> buf;
1883 llvm::raw_svector_ostream os(buf);
1884 SmallString<20> AllocNameBuf;
1885 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1887 const MemRegion *MR = ArgVal.getAsRegion();
1888 assert(MR && "Only MemRegion based symbols can have offset free errors");
1890 RegionOffset Offset = MR->getAsOffset();
1891 assert((Offset.isValid() &&
1892 !Offset.hasSymbolicOffset() &&
1893 Offset.getOffset() != 0) &&
1894 "Only symbols with a valid offset can have offset free errors");
1896 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
1898 os << "Argument to ";
1899 if (!printAllocDeallocName(os, C, DeallocExpr))
1900 os << "deallocator";
1901 os << " is offset by "
1904 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
1905 << " from the start of ";
1906 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1907 os << "memory allocated by " << AllocNameOs.str();
1909 os << "allocated memory";
1911 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1912 R->markInteresting(MR->getBaseRegion());
1914 C.emitReport(std::move(R));
1917 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
1918 SymbolRef Sym) const {
1920 if (!ChecksEnabled[CK_MallocChecker] &&
1921 !ChecksEnabled[CK_NewDeleteChecker])
1924 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1925 if (!CheckKind.hasValue())
1928 if (ExplodedNode *N = C.generateErrorNode()) {
1929 if (!BT_UseFree[*CheckKind])
1930 BT_UseFree[*CheckKind].reset(new BugType(
1931 CheckNames[*CheckKind], "Use-after-free", "Memory Error"));
1933 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1934 "Use of memory after it is freed", N);
1936 R->markInteresting(Sym);
1938 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1939 C.emitReport(std::move(R));
1943 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
1944 bool Released, SymbolRef Sym,
1945 SymbolRef PrevSym) const {
1947 if (!ChecksEnabled[CK_MallocChecker] &&
1948 !ChecksEnabled[CK_NewDeleteChecker])
1951 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1952 if (!CheckKind.hasValue())
1955 if (ExplodedNode *N = C.generateErrorNode()) {
1956 if (!BT_DoubleFree[*CheckKind])
1957 BT_DoubleFree[*CheckKind].reset(
1958 new BugType(CheckNames[*CheckKind], "Double free", "Memory Error"));
1960 auto R = llvm::make_unique<BugReport>(
1961 *BT_DoubleFree[*CheckKind],
1962 (Released ? "Attempt to free released memory"
1963 : "Attempt to free non-owned memory"),
1966 R->markInteresting(Sym);
1968 R->markInteresting(PrevSym);
1969 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1970 C.emitReport(std::move(R));
1974 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
1976 if (!ChecksEnabled[CK_NewDeleteChecker])
1979 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
1980 if (!CheckKind.hasValue())
1983 if (ExplodedNode *N = C.generateErrorNode()) {
1984 if (!BT_DoubleDelete)
1985 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
1986 "Double delete", "Memory Error"));
1988 auto R = llvm::make_unique<BugReport>(
1989 *BT_DoubleDelete, "Attempt to delete released memory", N);
1991 R->markInteresting(Sym);
1992 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1993 C.emitReport(std::move(R));
1997 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
1999 SymbolRef Sym) const {
2001 if (!ChecksEnabled[CK_MallocChecker] &&
2002 !ChecksEnabled[CK_NewDeleteChecker])
2005 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2007 if (!CheckKind.hasValue())
2010 if (ExplodedNode *N = C.generateErrorNode()) {
2011 if (!BT_UseZerroAllocated[*CheckKind])
2012 BT_UseZerroAllocated[*CheckKind].reset(new BugType(
2013 CheckNames[*CheckKind], "Use of zero allocated", "Memory Error"));
2015 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2016 "Use of zero-allocated memory", N);
2020 R->markInteresting(Sym);
2021 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2023 C.emitReport(std::move(R));
2027 ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2030 ProgramStateRef State,
2031 bool SuffixWithN) const {
2035 if (SuffixWithN && CE->getNumArgs() < 3)
2037 else if (CE->getNumArgs() < 2)
2040 const Expr *arg0Expr = CE->getArg(0);
2041 const LocationContext *LCtx = C.getLocationContext();
2042 SVal Arg0Val = State->getSVal(arg0Expr, LCtx);
2043 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2045 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2047 SValBuilder &svalBuilder = C.getSValBuilder();
2049 DefinedOrUnknownSVal PtrEQ =
2050 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2052 // Get the size argument.
2053 const Expr *Arg1 = CE->getArg(1);
2055 // Get the value of the size argument.
2056 SVal TotalSize = State->getSVal(Arg1, LCtx);
2058 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2059 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2062 // Compare the size argument to 0.
2063 DefinedOrUnknownSVal SizeZero =
2064 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2065 svalBuilder.makeIntValWithPtrWidth(0, false));
2067 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2068 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2069 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2070 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2071 // We only assume exceptional states if they are definitely true; if the
2072 // state is under-constrained, assume regular realloc behavior.
2073 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2074 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2076 // If the ptr is NULL and the size is not 0, the call is equivalent to
2078 if (PrtIsNull && !SizeIsZero) {
2079 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
2080 UndefinedVal(), StatePtrIsNull);
2084 if (PrtIsNull && SizeIsZero)
2087 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2089 SymbolRef FromPtr = arg0Val.getAsSymbol();
2090 SVal RetVal = State->getSVal(CE, LCtx);
2091 SymbolRef ToPtr = RetVal.getAsSymbol();
2092 if (!FromPtr || !ToPtr)
2095 bool ReleasedAllocated = false;
2097 // If the size is 0, free the memory.
2099 if (ProgramStateRef stateFree = FreeMemAux(C, CE, StateSizeIsZero, 0,
2100 false, ReleasedAllocated)){
2101 // The semantics of the return value are:
2102 // If size was equal to 0, either NULL or a pointer suitable to be passed
2103 // to free() is returned. We just free the input pointer and do not add
2104 // any constrains on the output pointer.
2108 // Default behavior.
2109 if (ProgramStateRef stateFree =
2110 FreeMemAux(C, CE, State, 0, false, ReleasedAllocated)) {
2112 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
2113 UnknownVal(), stateFree);
2117 ReallocPairKind Kind = RPToBeFreedAfterFailure;
2119 Kind = RPIsFreeOnFailure;
2120 else if (!ReleasedAllocated)
2121 Kind = RPDoNotTrackAfterFailure;
2123 // Record the info about the reallocated symbol so that we could properly
2124 // process failed reallocation.
2125 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2126 ReallocPair(FromPtr, Kind));
2127 // The reallocated symbol should stay alive for as long as the new symbol.
2128 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2129 return stateRealloc;
2134 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2135 ProgramStateRef State) {
2139 if (CE->getNumArgs() < 2)
2142 SValBuilder &svalBuilder = C.getSValBuilder();
2143 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2144 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
2146 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2150 MallocChecker::getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
2151 CheckerContext &C) const {
2152 const LocationContext *LeakContext = N->getLocationContext();
2153 // Walk the ExplodedGraph backwards and find the first node that referred to
2154 // the tracked symbol.
2155 const ExplodedNode *AllocNode = N;
2156 const MemRegion *ReferenceRegion = nullptr;
2159 ProgramStateRef State = N->getState();
2160 if (!State->get<RegionState>(Sym))
2163 // Find the most recent expression bound to the symbol in the current
2165 if (!ReferenceRegion) {
2166 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2167 SVal Val = State->getSVal(MR);
2168 if (Val.getAsLocSymbol() == Sym) {
2169 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2170 // Do not show local variables belonging to a function other than
2171 // where the error is reported.
2173 (VR->getStackFrame() == LeakContext->getCurrentStackFrame()))
2174 ReferenceRegion = MR;
2179 // Allocation node, is the last node in the current or parent context in
2180 // which the symbol was tracked.
2181 const LocationContext *NContext = N->getLocationContext();
2182 if (NContext == LeakContext ||
2183 NContext->isParentOf(LeakContext))
2185 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2188 return LeakInfo(AllocNode, ReferenceRegion);
2191 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2192 CheckerContext &C) const {
2194 if (!ChecksEnabled[CK_MallocChecker] &&
2195 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2198 const RefState *RS = C.getState()->get<RegionState>(Sym);
2199 assert(RS && "cannot leak an untracked symbol");
2200 AllocationFamily Family = RS->getAllocationFamily();
2202 if (Family == AF_Alloca)
2205 Optional<MallocChecker::CheckKind>
2206 CheckKind = getCheckIfTracked(Family, true);
2208 if (!CheckKind.hasValue())
2212 if (!BT_Leak[*CheckKind]) {
2213 BT_Leak[*CheckKind].reset(
2214 new BugType(CheckNames[*CheckKind], "Memory leak", "Memory Error"));
2215 // Leaks should not be reported if they are post-dominated by a sink:
2216 // (1) Sinks are higher importance bugs.
2217 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2218 // with __noreturn functions such as assert() or exit(). We choose not
2219 // to report leaks on such paths.
2220 BT_Leak[*CheckKind]->setSuppressOnSink(true);
2223 // Most bug reports are cached at the location where they occurred.
2224 // With leaks, we want to unique them by the location where they were
2225 // allocated, and only report a single path.
2226 PathDiagnosticLocation LocUsedForUniqueing;
2227 const ExplodedNode *AllocNode = nullptr;
2228 const MemRegion *Region = nullptr;
2229 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2231 const Stmt *AllocationStmt = PathDiagnosticLocation::getStmt(AllocNode);
2233 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2234 C.getSourceManager(),
2235 AllocNode->getLocationContext());
2237 SmallString<200> buf;
2238 llvm::raw_svector_ostream os(buf);
2239 if (Region && Region->canPrintPretty()) {
2240 os << "Potential leak of memory pointed to by ";
2241 Region->printPretty(os);
2243 os << "Potential memory leak";
2246 auto R = llvm::make_unique<BugReport>(
2247 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2248 AllocNode->getLocationContext()->getDecl());
2249 R->markInteresting(Sym);
2250 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym, true));
2251 C.emitReport(std::move(R));
2254 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2255 CheckerContext &C) const
2257 if (!SymReaper.hasDeadSymbols())
2260 ProgramStateRef state = C.getState();
2261 RegionStateTy RS = state->get<RegionState>();
2262 RegionStateTy::Factory &F = state->get_context<RegionState>();
2264 SmallVector<SymbolRef, 2> Errors;
2265 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2266 if (SymReaper.isDead(I->first)) {
2267 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2268 Errors.push_back(I->first);
2269 // Remove the dead symbol from the map.
2270 RS = F.remove(RS, I->first);
2275 // Cleanup the Realloc Pairs Map.
2276 ReallocPairsTy RP = state->get<ReallocPairs>();
2277 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2278 if (SymReaper.isDead(I->first) ||
2279 SymReaper.isDead(I->second.ReallocatedSym)) {
2280 state = state->remove<ReallocPairs>(I->first);
2284 // Cleanup the FreeReturnValue Map.
2285 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2286 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2287 if (SymReaper.isDead(I->first) ||
2288 SymReaper.isDead(I->second)) {
2289 state = state->remove<FreeReturnValue>(I->first);
2293 // Generate leak node.
2294 ExplodedNode *N = C.getPredecessor();
2295 if (!Errors.empty()) {
2296 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2297 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2299 for (SmallVectorImpl<SymbolRef>::iterator
2300 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2301 reportLeak(*I, N, C);
2306 C.addTransition(state->set<RegionState>(RS), N);
2309 void MallocChecker::checkPreCall(const CallEvent &Call,
2310 CheckerContext &C) const {
2312 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2313 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2314 if (!Sym || checkDoubleDelete(Sym, C))
2318 // We will check for double free in the post visit.
2319 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2320 const FunctionDecl *FD = FC->getDecl();
2324 ASTContext &Ctx = C.getASTContext();
2325 if (ChecksEnabled[CK_MallocChecker] &&
2326 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2327 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2328 MemoryOperationKind::MOK_Free)))
2331 if (ChecksEnabled[CK_NewDeleteChecker] &&
2332 isStandardNewDelete(FD, Ctx))
2336 // Check if the callee of a method is deleted.
2337 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2338 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2339 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2343 // Check arguments for being used after free.
2344 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2345 SVal ArgSVal = Call.getArgSVal(I);
2346 if (ArgSVal.getAs<Loc>()) {
2347 SymbolRef Sym = ArgSVal.getAsSymbol();
2350 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2356 void MallocChecker::checkPreStmt(const ReturnStmt *S, CheckerContext &C) const {
2357 const Expr *E = S->getRetValue();
2361 // Check if we are returning a symbol.
2362 ProgramStateRef State = C.getState();
2363 SVal RetVal = State->getSVal(E, C.getLocationContext());
2364 SymbolRef Sym = RetVal.getAsSymbol();
2366 // If we are returning a field of the allocated struct or an array element,
2367 // the callee could still free the memory.
2368 // TODO: This logic should be a part of generic symbol escape callback.
2369 if (const MemRegion *MR = RetVal.getAsRegion())
2370 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2371 if (const SymbolicRegion *BMR =
2372 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2373 Sym = BMR->getSymbol();
2375 // Check if we are returning freed memory.
2377 checkUseAfterFree(Sym, C, E);
2380 // TODO: Blocks should be either inlined or should call invalidate regions
2381 // upon invocation. After that's in place, special casing here will not be
2383 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2384 CheckerContext &C) const {
2386 // Scan the BlockDecRefExprs for any object the retain count checker
2388 if (!BE->getBlockDecl()->hasCaptures())
2391 ProgramStateRef state = C.getState();
2392 const BlockDataRegion *R =
2393 cast<BlockDataRegion>(state->getSVal(BE,
2394 C.getLocationContext()).getAsRegion());
2396 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2397 E = R->referenced_vars_end();
2402 SmallVector<const MemRegion*, 10> Regions;
2403 const LocationContext *LC = C.getLocationContext();
2404 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2406 for ( ; I != E; ++I) {
2407 const VarRegion *VR = I.getCapturedRegion();
2408 if (VR->getSuperRegion() == R) {
2409 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2411 Regions.push_back(VR);
2415 state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2416 Regions.data() + Regions.size()).getState();
2417 C.addTransition(state);
2420 bool MallocChecker::isReleased(SymbolRef Sym, CheckerContext &C) const {
2422 const RefState *RS = C.getState()->get<RegionState>(Sym);
2423 return (RS && RS->isReleased());
2426 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2427 const Stmt *S) const {
2429 if (isReleased(Sym, C)) {
2430 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2437 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2438 const Stmt *S) const {
2441 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2442 if (RS->isAllocatedOfSizeZero())
2443 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2445 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2446 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2450 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2452 if (isReleased(Sym, C)) {
2453 ReportDoubleDelete(C, Sym);
2459 // Check if the location is a freed symbolic region.
2460 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2461 CheckerContext &C) const {
2462 SymbolRef Sym = l.getLocSymbolInBase();
2464 checkUseAfterFree(Sym, C, S);
2465 checkUseZeroAllocated(Sym, C, S);
2469 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2470 // it - assuming that allocation failed on this path.
2471 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2473 bool Assumption) const {
2474 RegionStateTy RS = state->get<RegionState>();
2475 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2476 // If the symbol is assumed to be NULL, remove it from consideration.
2477 ConstraintManager &CMgr = state->getConstraintManager();
2478 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2479 if (AllocFailed.isConstrainedTrue())
2480 state = state->remove<RegionState>(I.getKey());
2483 // Realloc returns 0 when reallocation fails, which means that we should
2484 // restore the state of the pointer being reallocated.
2485 ReallocPairsTy RP = state->get<ReallocPairs>();
2486 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2487 // If the symbol is assumed to be NULL, remove it from consideration.
2488 ConstraintManager &CMgr = state->getConstraintManager();
2489 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2490 if (!AllocFailed.isConstrainedTrue())
2493 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2494 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2495 if (RS->isReleased()) {
2496 if (I.getData().Kind == RPToBeFreedAfterFailure)
2497 state = state->set<RegionState>(ReallocSym,
2498 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2499 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2500 state = state->remove<RegionState>(ReallocSym);
2502 assert(I.getData().Kind == RPIsFreeOnFailure);
2505 state = state->remove<ReallocPairs>(I.getKey());
2511 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2512 const CallEvent *Call,
2513 ProgramStateRef State,
2514 SymbolRef &EscapingSymbol) const {
2516 EscapingSymbol = nullptr;
2518 // For now, assume that any C++ or block call can free memory.
2519 // TODO: If we want to be more optimistic here, we'll need to make sure that
2520 // regions escape to C++ containers. They seem to do that even now, but for
2521 // mysterious reasons.
2522 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2525 // Check Objective-C messages by selector name.
2526 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2527 // If it's not a framework call, or if it takes a callback, assume it
2529 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2532 // If it's a method we know about, handle it explicitly post-call.
2533 // This should happen before the "freeWhenDone" check below.
2534 if (isKnownDeallocObjCMethodName(*Msg))
2537 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2538 // about, we can't be sure that the object will use free() to deallocate the
2539 // memory, so we can't model it explicitly. The best we can do is use it to
2540 // decide whether the pointer escapes.
2541 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2542 return *FreeWhenDone;
2544 // If the first selector piece ends with "NoCopy", and there is no
2545 // "freeWhenDone" parameter set to zero, we know ownership is being
2546 // transferred. Again, though, we can't be sure that the object will use
2547 // free() to deallocate the memory, so we can't model it explicitly.
2548 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2549 if (FirstSlot.endswith("NoCopy"))
2552 // If the first selector starts with addPointer, insertPointer,
2553 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2554 // This is similar to C++ containers (vector); we still might want to check
2555 // that the pointers get freed by following the container itself.
2556 if (FirstSlot.startswith("addPointer") ||
2557 FirstSlot.startswith("insertPointer") ||
2558 FirstSlot.startswith("replacePointer") ||
2559 FirstSlot.equals("valueWithPointer")) {
2563 // We should escape receiver on call to 'init'. This is especially relevant
2564 // to the receiver, as the corresponding symbol is usually not referenced
2566 if (Msg->getMethodFamily() == OMF_init) {
2567 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2571 // Otherwise, assume that the method does not free memory.
2572 // Most framework methods do not free memory.
2576 // At this point the only thing left to handle is straight function calls.
2577 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2581 ASTContext &ASTC = State->getStateManager().getContext();
2583 // If it's one of the allocation functions we can reason about, we model
2584 // its behavior explicitly.
2585 if (isMemFunction(FD, ASTC))
2588 // If it's not a system call, assume it frees memory.
2589 if (!Call->isInSystemHeader())
2592 // White list the system functions whose arguments escape.
2593 const IdentifierInfo *II = FD->getIdentifier();
2596 StringRef FName = II->getName();
2598 // White list the 'XXXNoCopy' CoreFoundation functions.
2599 // We specifically check these before
2600 if (FName.endswith("NoCopy")) {
2601 // Look for the deallocator argument. We know that the memory ownership
2602 // is not transferred only if the deallocator argument is
2603 // 'kCFAllocatorNull'.
2604 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
2605 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
2606 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2607 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2608 if (DeallocatorName == "kCFAllocatorNull")
2615 // Associating streams with malloced buffers. The pointer can escape if
2616 // 'closefn' is specified (and if that function does free memory),
2617 // but it will not if closefn is not specified.
2618 // Currently, we do not inspect the 'closefn' function (PR12101).
2619 if (FName == "funopen")
2620 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2623 // Do not warn on pointers passed to 'setbuf' when used with std streams,
2624 // these leaks might be intentional when setting the buffer for stdio.
2625 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
2626 if (FName == "setbuf" || FName =="setbuffer" ||
2627 FName == "setlinebuf" || FName == "setvbuf") {
2628 if (Call->getNumArgs() >= 1) {
2629 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2630 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2631 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2632 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
2637 // A bunch of other functions which either take ownership of a pointer or
2638 // wrap the result up in a struct or object, meaning it can be freed later.
2639 // (See RetainCountChecker.) Not all the parameters here are invalidated,
2640 // but the Malloc checker cannot differentiate between them. The right way
2641 // of doing this would be to implement a pointer escapes callback.
2642 if (FName == "CGBitmapContextCreate" ||
2643 FName == "CGBitmapContextCreateWithData" ||
2644 FName == "CVPixelBufferCreateWithBytes" ||
2645 FName == "CVPixelBufferCreateWithPlanarBytes" ||
2646 FName == "OSAtomicEnqueue") {
2650 if (FName == "postEvent" &&
2651 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2655 if (FName == "postEvent" &&
2656 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
2660 if (FName == "connectImpl" &&
2661 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
2665 // Handle cases where we know a buffer's /address/ can escape.
2666 // Note that the above checks handle some special cases where we know that
2667 // even though the address escapes, it's still our responsibility to free the
2669 if (Call->argumentsMayEscape())
2672 // Otherwise, assume that the function does not free memory.
2673 // Most system calls do not free the memory.
2677 static bool retTrue(const RefState *RS) {
2681 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
2682 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2683 RS->getAllocationFamily() == AF_CXXNew);
2686 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
2687 const InvalidatedSymbols &Escaped,
2688 const CallEvent *Call,
2689 PointerEscapeKind Kind) const {
2690 return checkPointerEscapeAux(State, Escaped, Call, Kind, &retTrue);
2693 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
2694 const InvalidatedSymbols &Escaped,
2695 const CallEvent *Call,
2696 PointerEscapeKind Kind) const {
2697 return checkPointerEscapeAux(State, Escaped, Call, Kind,
2698 &checkIfNewOrNewArrayFamily);
2701 ProgramStateRef MallocChecker::checkPointerEscapeAux(ProgramStateRef State,
2702 const InvalidatedSymbols &Escaped,
2703 const CallEvent *Call,
2704 PointerEscapeKind Kind,
2705 bool(*CheckRefState)(const RefState*)) const {
2706 // If we know that the call does not free memory, or we want to process the
2707 // call later, keep tracking the top level arguments.
2708 SymbolRef EscapingSymbol = nullptr;
2709 if (Kind == PSK_DirectEscapeOnCall &&
2710 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
2716 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2721 if (EscapingSymbol && EscapingSymbol != sym)
2724 if (const RefState *RS = State->get<RegionState>(sym)) {
2725 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2726 CheckRefState(RS)) {
2727 State = State->remove<RegionState>(sym);
2728 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
2735 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
2736 ProgramStateRef prevState) {
2737 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2738 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2740 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2742 SymbolRef sym = I.getKey();
2743 if (!currMap.lookup(sym))
2750 std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2751 const ExplodedNode *N, const ExplodedNode *PrevN, BugReporterContext &BRC,
2753 ProgramStateRef state = N->getState();
2754 ProgramStateRef statePrev = PrevN->getState();
2756 const RefState *RS = state->get<RegionState>(Sym);
2757 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2761 const Stmt *S = PathDiagnosticLocation::getStmt(N);
2765 // FIXME: We will eventually need to handle non-statement-based events
2766 // (__attribute__((cleanup))).
2768 // Find out if this is an interesting point and what is the kind.
2769 const char *Msg = nullptr;
2770 StackHintGeneratorForSymbol *StackHint = nullptr;
2771 if (Mode == Normal) {
2772 if (isAllocated(RS, RSPrev, S)) {
2773 Msg = "Memory is allocated";
2774 StackHint = new StackHintGeneratorForSymbol(Sym,
2775 "Returned allocated memory");
2776 } else if (isReleased(RS, RSPrev, S)) {
2777 Msg = "Memory is released";
2778 StackHint = new StackHintGeneratorForSymbol(Sym,
2779 "Returning; memory was released");
2780 } else if (isRelinquished(RS, RSPrev, S)) {
2781 Msg = "Memory ownership is transferred";
2782 StackHint = new StackHintGeneratorForSymbol(Sym, "");
2783 } else if (isReallocFailedCheck(RS, RSPrev, S)) {
2784 Mode = ReallocationFailed;
2785 Msg = "Reallocation failed";
2786 StackHint = new StackHintGeneratorForReallocationFailed(Sym,
2787 "Reallocation failed");
2789 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
2790 // Is it possible to fail two reallocs WITHOUT testing in between?
2791 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
2792 "We only support one failed realloc at a time.");
2793 BR.markInteresting(sym);
2794 FailedReallocSymbol = sym;
2798 // We are in a special mode if a reallocation failed later in the path.
2799 } else if (Mode == ReallocationFailed) {
2800 assert(FailedReallocSymbol && "No symbol to look for.");
2802 // Is this is the first appearance of the reallocated symbol?
2803 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
2804 // We're at the reallocation point.
2805 Msg = "Attempt to reallocate memory";
2806 StackHint = new StackHintGeneratorForSymbol(Sym,
2807 "Returned reallocated memory");
2808 FailedReallocSymbol = nullptr;
2817 // Generate the extra diagnostic.
2818 PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2819 N->getLocationContext());
2820 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true, StackHint);
2823 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
2824 const char *NL, const char *Sep) const {
2826 RegionStateTy RS = State->get<RegionState>();
2828 if (!RS.isEmpty()) {
2829 Out << Sep << "MallocChecker :" << NL;
2830 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2831 const RefState *RefS = State->get<RegionState>(I.getKey());
2832 AllocationFamily Family = RefS->getAllocationFamily();
2833 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2834 if (!CheckKind.hasValue())
2835 CheckKind = getCheckIfTracked(Family, true);
2837 I.getKey()->dumpToStream(Out);
2839 I.getData().dump(Out);
2840 if (CheckKind.hasValue())
2841 Out << " (" << CheckNames[*CheckKind].getName() << ")";
2847 void ento::registerNewDeleteLeaksChecker(CheckerManager &mgr) {
2848 registerCStringCheckerBasic(mgr);
2849 MallocChecker *checker = mgr.registerChecker<MallocChecker>();
2850 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption(
2851 "Optimistic", false, checker);
2852 checker->ChecksEnabled[MallocChecker::CK_NewDeleteLeaksChecker] = true;
2853 checker->CheckNames[MallocChecker::CK_NewDeleteLeaksChecker] =
2854 mgr.getCurrentCheckName();
2855 // We currently treat NewDeleteLeaks checker as a subchecker of NewDelete
2857 if (!checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker])
2858 checker->ChecksEnabled[MallocChecker::CK_NewDeleteChecker] = true;
2861 #define REGISTER_CHECKER(name) \
2862 void ento::register##name(CheckerManager &mgr) { \
2863 registerCStringCheckerBasic(mgr); \
2864 MallocChecker *checker = mgr.registerChecker<MallocChecker>(); \
2865 checker->IsOptimistic = mgr.getAnalyzerOptions().getBooleanOption( \
2866 "Optimistic", false, checker); \
2867 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
2868 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \
2871 REGISTER_CHECKER(MallocChecker)
2872 REGISTER_CHECKER(NewDeleteChecker)
2873 REGISTER_CHECKER(MismatchedDeallocatorChecker)