1 //=== MallocChecker.cpp - A malloc/free checker -------------------*- C++ -*--//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines a variety of memory management related checkers, such as
10 // leak, double free, and use-after-free.
12 // The following checkers are defined here:
15 // Despite its name, it models all sorts of memory allocations and
16 // de- or reallocation, including but not limited to malloc, free,
17 // relloc, new, delete. It also reports on a variety of memory misuse
19 // Many other checkers interact very closely with this checker, in fact,
20 // most are merely options to this one. Other checkers may register
21 // MallocChecker, but do not enable MallocChecker's reports (more details
22 // to follow around its field, ChecksEnabled).
23 // It also has a boolean "Optimistic" checker option, which if set to true
24 // will cause the checker to model user defined memory management related
25 // functions annotated via the attribute ownership_takes, ownership_holds
26 // and ownership_returns.
29 // Enables the modeling of new, new[], delete, delete[] in MallocChecker,
30 // and checks for related double-free and use-after-free errors.
32 // * NewDeleteLeaksChecker
33 // Checks for leaks related to new, new[], delete, delete[].
34 // Depends on NewDeleteChecker.
36 // * MismatchedDeallocatorChecker
37 // Enables checking whether memory is deallocated with the correspending
38 // allocation function in MallocChecker, such as malloc() allocated
39 // regions are only freed by free(), new by delete, new[] by delete[].
41 // InnerPointerChecker interacts very closely with MallocChecker, but unlike
42 // the above checkers, it has it's own file, hence the many InnerPointerChecker
43 // related headers and non-static functions.
45 //===----------------------------------------------------------------------===//
47 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
48 #include "InterCheckerAPI.h"
49 #include "clang/AST/Attr.h"
50 #include "clang/AST/ParentMap.h"
51 #include "clang/Basic/SourceManager.h"
52 #include "clang/Basic/TargetInfo.h"
53 #include "clang/Lex/Lexer.h"
54 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
55 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
56 #include "clang/StaticAnalyzer/Core/Checker.h"
57 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
58 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
59 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
60 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
61 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
62 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include "llvm/ADT/SmallString.h"
65 #include "llvm/ADT/StringExtras.h"
66 #include "AllocationState.h"
70 using namespace clang;
73 //===----------------------------------------------------------------------===//
74 // The types of allocation we're modeling.
75 //===----------------------------------------------------------------------===//
79 // Used to check correspondence between allocators and deallocators.
80 enum AllocationFamily {
90 struct MemFunctionInfoTy;
92 } // end of anonymous namespace
94 /// Determine family of a deallocation expression.
95 static AllocationFamily
96 getAllocationFamily(const MemFunctionInfoTy &MemFunctionInfo, CheckerContext &C,
99 /// Print names of allocators and deallocators.
101 /// \returns true on success.
102 static bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
105 /// Print expected name of an allocator based on the deallocator's
106 /// family derived from the DeallocExpr.
107 static void printExpectedAllocName(raw_ostream &os,
108 const MemFunctionInfoTy &MemFunctionInfo,
109 CheckerContext &C, const Expr *E);
111 /// Print expected name of a deallocator based on the allocator's
113 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family);
115 //===----------------------------------------------------------------------===//
116 // The state of a symbol, in terms of memory management.
117 //===----------------------------------------------------------------------===//
123 // Reference to allocated memory.
125 // Reference to zero-allocated memory.
127 // Reference to released/freed memory.
129 // The responsibility for freeing resources has transferred from
130 // this reference. A relinquished symbol should not be freed.
132 // We are no longer guaranteed to have observed all manipulations
133 // of this pointer/memory. For example, it could have been
134 // passed as a parameter to an opaque function.
141 AllocationFamily Family;
143 RefState(Kind k, const Stmt *s, AllocationFamily family)
144 : S(s), K(k), Family(family) {
145 assert(family != AF_None);
149 bool isAllocated() const { return K == Allocated; }
150 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
151 bool isReleased() const { return K == Released; }
152 bool isRelinquished() const { return K == Relinquished; }
153 bool isEscaped() const { return K == Escaped; }
154 AllocationFamily getAllocationFamily() const { return Family; }
155 const Stmt *getStmt() const { return S; }
157 bool operator==(const RefState &X) const {
158 return K == X.K && S == X.S && Family == X.Family;
161 static RefState getAllocated(AllocationFamily family, const Stmt *s) {
162 return RefState(Allocated, s, family);
164 static RefState getAllocatedOfSizeZero(const RefState *RS) {
165 return RefState(AllocatedOfSizeZero, RS->getStmt(),
166 RS->getAllocationFamily());
168 static RefState getReleased(AllocationFamily family, const Stmt *s) {
169 return RefState(Released, s, family);
171 static RefState getRelinquished(AllocationFamily family, const Stmt *s) {
172 return RefState(Relinquished, s, family);
174 static RefState getEscaped(const RefState *RS) {
175 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
178 void Profile(llvm::FoldingSetNodeID &ID) const {
181 ID.AddInteger(Family);
184 LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
186 #define CASE(ID) case ID: OS << #ID; break;
188 CASE(AllocatedOfSizeZero)
195 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
198 } // end of anonymous namespace
200 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
202 /// Check if the memory associated with this symbol was released.
203 static bool isReleased(SymbolRef Sym, CheckerContext &C);
205 /// Update the RefState to reflect the new memory allocation.
206 /// The optional \p RetVal parameter specifies the newly allocated pointer
207 /// value; if unspecified, the value of expression \p E is used.
208 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
209 ProgramStateRef State,
210 AllocationFamily Family = AF_Malloc,
211 Optional<SVal> RetVal = None);
213 //===----------------------------------------------------------------------===//
214 // The modeling of memory reallocation.
216 // The terminology 'toPtr' and 'fromPtr' will be used:
217 // toPtr = realloc(fromPtr, 20);
218 //===----------------------------------------------------------------------===//
220 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
224 /// The state of 'fromPtr' after reallocation is known to have failed.
225 enum OwnershipAfterReallocKind {
226 // The symbol needs to be freed (e.g.: realloc)
227 OAR_ToBeFreedAfterFailure,
228 // The symbol has been freed (e.g.: reallocf)
230 // The symbol doesn't have to freed (e.g.: we aren't sure if, how and where
231 // 'fromPtr' was allocated:
232 // void Haha(int *ptr) {
233 // ptr = realloc(ptr, 67);
237 OAR_DoNotTrackAfterFailure
240 /// Stores information about the 'fromPtr' symbol after reallocation.
242 /// This is important because realloc may fail, and that needs special modeling.
243 /// Whether reallocation failed or not will not be known until later, so we'll
244 /// store whether upon failure 'fromPtr' will be freed, or needs to be freed
249 SymbolRef ReallocatedSym;
250 OwnershipAfterReallocKind Kind;
252 ReallocPair(SymbolRef S, OwnershipAfterReallocKind K)
253 : ReallocatedSym(S), Kind(K) {}
254 void Profile(llvm::FoldingSetNodeID &ID) const {
256 ID.AddPointer(ReallocatedSym);
258 bool operator==(const ReallocPair &X) const {
259 return ReallocatedSym == X.ReallocatedSym &&
264 } // end of anonymous namespace
266 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
268 //===----------------------------------------------------------------------===//
269 // Kinds of memory operations, information about resource managing functions.
270 //===----------------------------------------------------------------------===//
274 enum class MemoryOperationKind { MOK_Allocate, MOK_Free, MOK_Any };
276 struct MemFunctionInfoTy {
277 /// The value of the MallocChecker:Optimistic is stored in this variable.
279 /// In pessimistic mode, the checker assumes that it does not know which
280 /// functions might free the memory.
281 /// In optimistic mode, the checker assumes that all user-defined functions
282 /// which might free a pointer are annotated.
283 DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
285 // TODO: Change these to CallDescription, and get rid of lazy initialization.
286 mutable IdentifierInfo *II_alloca = nullptr, *II_win_alloca = nullptr,
287 *II_malloc = nullptr, *II_free = nullptr,
288 *II_realloc = nullptr, *II_calloc = nullptr,
289 *II_valloc = nullptr, *II_reallocf = nullptr,
290 *II_strndup = nullptr, *II_strdup = nullptr,
291 *II_win_strdup = nullptr, *II_kmalloc = nullptr,
292 *II_if_nameindex = nullptr,
293 *II_if_freenameindex = nullptr, *II_wcsdup = nullptr,
294 *II_win_wcsdup = nullptr, *II_g_malloc = nullptr,
295 *II_g_malloc0 = nullptr, *II_g_realloc = nullptr,
296 *II_g_try_malloc = nullptr,
297 *II_g_try_malloc0 = nullptr,
298 *II_g_try_realloc = nullptr, *II_g_free = nullptr,
299 *II_g_memdup = nullptr, *II_g_malloc_n = nullptr,
300 *II_g_malloc0_n = nullptr, *II_g_realloc_n = nullptr,
301 *II_g_try_malloc_n = nullptr,
302 *II_g_try_malloc0_n = nullptr, *II_kfree = nullptr,
303 *II_g_try_realloc_n = nullptr;
305 void initIdentifierInfo(ASTContext &C) const;
308 /// Check if this is one of the functions which can allocate/reallocate
309 /// memory pointed to by one of its arguments.
310 bool isMemFunction(const FunctionDecl *FD, ASTContext &C) const;
311 bool isCMemFunction(const FunctionDecl *FD, ASTContext &C,
312 AllocationFamily Family,
313 MemoryOperationKind MemKind) const;
315 /// Tells if the callee is one of the builtin new/delete operators, including
316 /// placement operators and other standard overloads.
317 bool isStandardNewDelete(const FunctionDecl *FD, ASTContext &C) const;
321 } // end of anonymous namespace
323 //===----------------------------------------------------------------------===//
324 // Definition of the MallocChecker class.
325 //===----------------------------------------------------------------------===//
330 : public Checker<check::DeadSymbols, check::PointerEscape,
331 check::ConstPointerEscape, check::PreStmt<ReturnStmt>,
332 check::EndFunction, check::PreCall,
333 check::PostStmt<CallExpr>, check::PostStmt<CXXNewExpr>,
334 check::NewAllocator, check::PreStmt<CXXDeleteExpr>,
335 check::PostStmt<BlockExpr>, check::PostObjCMessage,
336 check::Location, eval::Assume> {
338 MemFunctionInfoTy MemFunctionInfo;
340 /// Many checkers are essentially built into this one, so enabling them will
341 /// make MallocChecker perform additional modeling and reporting.
343 /// When a subchecker is enabled but MallocChecker isn't, model memory
344 /// management but do not emit warnings emitted with MallocChecker only
348 CK_NewDeleteLeaksChecker,
349 CK_MismatchedDeallocatorChecker,
350 CK_InnerPointerChecker,
354 using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
356 DefaultBool ChecksEnabled[CK_NumCheckKinds];
357 CheckerNameRef CheckNames[CK_NumCheckKinds];
359 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
360 void checkPostStmt(const CallExpr *CE, CheckerContext &C) const;
361 void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
362 void checkNewAllocator(const CXXNewExpr *NE, SVal Target,
363 CheckerContext &C) const;
364 void checkPreStmt(const CXXDeleteExpr *DE, CheckerContext &C) const;
365 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
366 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
367 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
368 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
369 void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
370 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
371 bool Assumption) const;
372 void checkLocation(SVal l, bool isLoad, const Stmt *S,
373 CheckerContext &C) const;
375 ProgramStateRef checkPointerEscape(ProgramStateRef State,
376 const InvalidatedSymbols &Escaped,
377 const CallEvent *Call,
378 PointerEscapeKind Kind) const;
379 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
380 const InvalidatedSymbols &Escaped,
381 const CallEvent *Call,
382 PointerEscapeKind Kind) const;
384 void printState(raw_ostream &Out, ProgramStateRef State,
385 const char *NL, const char *Sep) const override;
388 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
389 mutable std::unique_ptr<BugType> BT_DoubleDelete;
390 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
391 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
392 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
393 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
394 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
395 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
396 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
398 // TODO: Remove mutable by moving the initializtaion to the registry function.
399 mutable Optional<uint64_t> KernelZeroFlagVal;
401 /// Process C++ operator new()'s allocation, which is the part of C++
402 /// new-expression that goes before the constructor.
403 void processNewAllocation(const CXXNewExpr *NE, CheckerContext &C,
406 /// Perform a zero-allocation check.
408 /// \param [in] E The expression that allocates memory.
409 /// \param [in] IndexOfSizeArg Index of the argument that specifies the size
410 /// of the memory that needs to be allocated. E.g. for malloc, this would be
412 /// \param [in] RetVal Specifies the newly allocated pointer value;
413 /// if unspecified, the value of expression \p E is used.
414 static ProgramStateRef ProcessZeroAllocCheck(CheckerContext &C, const Expr *E,
415 const unsigned IndexOfSizeArg,
416 ProgramStateRef State,
417 Optional<SVal> RetVal = None);
419 /// Model functions with the ownership_returns attribute.
421 /// User-defined function may have the ownership_returns attribute, which
422 /// annotates that the function returns with an object that was allocated on
423 /// the heap, and passes the ownertship to the callee.
425 /// void __attribute((ownership_returns(malloc, 1))) *my_malloc(size_t);
427 /// It has two parameters:
428 /// - first: name of the resource (e.g. 'malloc')
429 /// - (OPTIONAL) second: size of the allocated region
431 /// \param [in] CE The expression that allocates memory.
432 /// \param [in] Att The ownership_returns attribute.
433 /// \param [in] State The \c ProgramState right before allocation.
434 /// \returns The ProgramState right after allocation.
435 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C,
437 const OwnershipAttr* Att,
438 ProgramStateRef State) const;
440 /// Models memory allocation.
442 /// \param [in] CE The expression that allocates memory.
443 /// \param [in] SizeEx Size of the memory that needs to be allocated.
444 /// \param [in] Init The value the allocated memory needs to be initialized.
445 /// with. For example, \c calloc initializes the allocated memory to 0,
446 /// malloc leaves it undefined.
447 /// \param [in] State The \c ProgramState right before allocation.
448 /// \returns The ProgramState right after allocation.
449 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
450 const Expr *SizeEx, SVal Init,
451 ProgramStateRef State,
452 AllocationFamily Family = AF_Malloc);
454 /// Models memory allocation.
456 /// \param [in] CE The expression that allocates memory.
457 /// \param [in] Size Size of the memory that needs to be allocated.
458 /// \param [in] Init The value the allocated memory needs to be initialized.
459 /// with. For example, \c calloc initializes the allocated memory to 0,
460 /// malloc leaves it undefined.
461 /// \param [in] State The \c ProgramState right before allocation.
462 /// \returns The ProgramState right after allocation.
463 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallExpr *CE,
464 SVal Size, SVal Init,
465 ProgramStateRef State,
466 AllocationFamily Family = AF_Malloc);
468 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
469 ProgramStateRef State, SVal Target);
471 // Check if this malloc() for special flags. At present that means M_ZERO or
472 // __GFP_ZERO (in which case, treat it like calloc).
473 llvm::Optional<ProgramStateRef>
474 performKernelMalloc(const CallExpr *CE, CheckerContext &C,
475 const ProgramStateRef &State) const;
477 /// Model functions with the ownership_takes and ownership_holds attributes.
479 /// User-defined function may have the ownership_takes and/or ownership_holds
480 /// attributes, which annotates that the function frees the memory passed as a
483 /// void __attribute((ownership_takes(malloc, 1))) my_free(void *);
484 /// void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
486 /// They have two parameters:
487 /// - first: name of the resource (e.g. 'malloc')
488 /// - second: index of the parameter the attribute applies to
490 /// \param [in] CE The expression that frees memory.
491 /// \param [in] Att The ownership_takes or ownership_holds attribute.
492 /// \param [in] State The \c ProgramState right before allocation.
493 /// \returns The ProgramState right after deallocation.
494 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallExpr *CE,
495 const OwnershipAttr* Att,
496 ProgramStateRef State) const;
498 /// Models memory deallocation.
500 /// \param [in] CE The expression that frees memory.
501 /// \param [in] State The \c ProgramState right before allocation.
502 /// \param [in] Num Index of the argument that needs to be freed. This is
503 /// normally 0, but for custom free functions it may be different.
504 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
506 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
507 /// to have been allocated, or in other words, the symbol to be freed was
508 /// registered as allocated by this checker. In the following case, \c ptr
509 /// isn't known to be allocated.
510 /// void Haha(int *ptr) {
511 /// ptr = realloc(ptr, 67);
514 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
515 /// we're modeling returns with Null on failure.
516 /// \returns The ProgramState right after deallocation.
517 ProgramStateRef FreeMemAux(CheckerContext &C, const CallExpr *CE,
518 ProgramStateRef State, unsigned Num, bool Hold,
519 bool &IsKnownToBeAllocated,
520 bool ReturnsNullOnFailure = false) const;
522 /// Models memory deallocation.
524 /// \param [in] ArgExpr The variable who's pointee needs to be freed.
525 /// \param [in] ParentExpr The expression that frees the memory.
526 /// \param [in] State The \c ProgramState right before allocation.
527 /// normally 0, but for custom free functions it may be different.
528 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
530 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
531 /// to have been allocated, or in other words, the symbol to be freed was
532 /// registered as allocated by this checker. In the following case, \c ptr
533 /// isn't known to be allocated.
534 /// void Haha(int *ptr) {
535 /// ptr = realloc(ptr, 67);
538 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
539 /// we're modeling returns with Null on failure.
540 /// \returns The ProgramState right after deallocation.
541 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *ArgExpr,
542 const Expr *ParentExpr, ProgramStateRef State,
543 bool Hold, bool &IsKnownToBeAllocated,
544 bool ReturnsNullOnFailure = false) const;
546 // TODO: Needs some refactoring, as all other deallocation modeling
547 // functions are suffering from out parameters and messy code due to how
548 // realloc is handled.
550 /// Models memory reallocation.
552 /// \param [in] CE The expression that reallocated memory
553 /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied
554 /// memory should be freed.
555 /// \param [in] State The \c ProgramState right before reallocation.
556 /// \param [in] SuffixWithN Whether the reallocation function we're modeling
557 /// has an '_n' suffix, such as g_realloc_n.
558 /// \returns The ProgramState right after reallocation.
559 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallExpr *CE,
560 bool ShouldFreeOnFail, ProgramStateRef State,
561 bool SuffixWithN = false) const;
563 /// Evaluates the buffer size that needs to be allocated.
565 /// \param [in] Blocks The amount of blocks that needs to be allocated.
566 /// \param [in] BlockBytes The size of a block.
567 /// \returns The symbolic value of \p Blocks * \p BlockBytes.
568 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
569 const Expr *BlockBytes);
571 /// Models zero initialized array allocation.
573 /// \param [in] CE The expression that reallocated memory
574 /// \param [in] State The \c ProgramState right before reallocation.
575 /// \returns The ProgramState right after allocation.
576 static ProgramStateRef CallocMem(CheckerContext &C, const CallExpr *CE,
577 ProgramStateRef State);
579 /// See if deallocation happens in a suspicious context. If so, escape the
580 /// pointers that otherwise would have been deallocated and return true.
581 bool suppressDeallocationsInSuspiciousContexts(const CallExpr *CE,
582 CheckerContext &C) const;
584 /// If in \p S \p Sym is used, check whether \p Sym was already freed.
585 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
587 /// If in \p S \p Sym is used, check whether \p Sym was allocated as a zero
588 /// sized memory region.
589 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
590 const Stmt *S) const;
592 /// If in \p S \p Sym is being freed, check whether \p Sym was already freed.
593 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
595 /// Check if the function is known to free memory, or if it is
596 /// "interesting" and should be modeled explicitly.
598 /// \param [out] EscapingSymbol A function might not free memory in general,
599 /// but could be known to free a particular symbol. In this case, false is
600 /// returned and the single escaping symbol is returned through the out
603 /// We assume that pointers do not escape through calls to system functions
604 /// not handled by this checker.
605 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
606 ProgramStateRef State,
607 SymbolRef &EscapingSymbol) const;
609 /// Implementation of the checkPointerEscape callbacks.
610 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
611 const InvalidatedSymbols &Escaped,
612 const CallEvent *Call,
613 PointerEscapeKind Kind,
614 bool IsConstPointerEscape) const;
616 // Implementation of the checkPreStmt and checkEndFunction callbacks.
617 void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
620 /// Tells if a given family/call/symbol is tracked by the current checker.
621 /// Sets CheckKind to the kind of the checker responsible for this
622 /// family/call/symbol.
623 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
624 bool IsALeakCheck = false) const;
625 Optional<CheckKind> getCheckIfTracked(CheckerContext &C,
626 const Stmt *AllocDeallocStmt,
627 bool IsALeakCheck = false) const;
628 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
629 bool IsALeakCheck = false) const;
631 static bool SummarizeValue(raw_ostream &os, SVal V);
632 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
634 void ReportBadFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
635 const Expr *DeallocExpr) const;
636 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
637 SourceRange Range) const;
638 void ReportMismatchedDealloc(CheckerContext &C, SourceRange Range,
639 const Expr *DeallocExpr, const RefState *RS,
640 SymbolRef Sym, bool OwnershipTransferred) const;
641 void ReportOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
642 const Expr *DeallocExpr,
643 const Expr *AllocExpr = nullptr) const;
644 void ReportUseAfterFree(CheckerContext &C, SourceRange Range,
645 SymbolRef Sym) const;
646 void ReportDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
647 SymbolRef Sym, SymbolRef PrevSym) const;
649 void ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
651 void ReportUseZeroAllocated(CheckerContext &C, SourceRange Range,
652 SymbolRef Sym) const;
654 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
655 SourceRange Range, const Expr *FreeExpr) const;
657 /// Find the location of the allocation for Sym on the path leading to the
659 static LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
662 void reportLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
665 //===----------------------------------------------------------------------===//
666 // Definition of MallocBugVisitor.
667 //===----------------------------------------------------------------------===//
669 /// The bug visitor which allows us to print extra diagnostics along the
670 /// BugReport path. For example, showing the allocation site of the leaked
672 class MallocBugVisitor final : public BugReporterVisitor {
674 enum NotificationMode { Normal, ReallocationFailed };
676 // The allocated region symbol tracked by the main analysis.
679 // The mode we are in, i.e. what kind of diagnostics will be emitted.
680 NotificationMode Mode;
682 // A symbol from when the primary region should have been reallocated.
683 SymbolRef FailedReallocSymbol;
685 // A C++ destructor stack frame in which memory was released. Used for
686 // miscellaneous false positive suppression.
687 const StackFrameContext *ReleaseDestructorLC;
692 MallocBugVisitor(SymbolRef S, bool isLeak = false)
693 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
694 ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
696 static void *getTag() {
701 void Profile(llvm::FoldingSetNodeID &ID) const override {
702 ID.AddPointer(getTag());
706 /// Did not track -> allocated. Other state (released) -> allocated.
707 static inline bool isAllocated(const RefState *RSCurr, const RefState *RSPrev,
709 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
711 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
713 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
716 /// Did not track -> released. Other state (allocated) -> released.
717 /// The statement associated with the release might be missing.
718 static inline bool isReleased(const RefState *RSCurr, const RefState *RSPrev,
721 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
722 assert(!IsReleased ||
723 (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
724 (!Stmt && RSCurr->getAllocationFamily() == AF_InnerBuffer));
728 /// Did not track -> relinquished. Other state (allocated) -> relinquished.
729 static inline bool isRelinquished(const RefState *RSCurr,
730 const RefState *RSPrev, const Stmt *Stmt) {
732 (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
733 isa<ObjCPropertyRefExpr>(Stmt)) &&
734 (RSCurr && RSCurr->isRelinquished()) &&
735 (!RSPrev || !RSPrev->isRelinquished()));
738 /// If the expression is not a call, and the state change is
739 /// released -> allocated, it must be the realloc return value
740 /// check. If we have to handle more cases here, it might be cleaner just
741 /// to track this extra bit in the state itself.
742 static inline bool hasReallocFailed(const RefState *RSCurr,
743 const RefState *RSPrev,
745 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
747 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
749 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
752 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
753 BugReporterContext &BRC,
754 PathSensitiveBugReport &BR) override;
756 PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
757 const ExplodedNode *EndPathNode,
758 PathSensitiveBugReport &BR) override {
762 PathDiagnosticLocation L = BR.getLocation();
763 // Do not add the statement itself as a range in case of leak.
764 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
769 class StackHintGeneratorForReallocationFailed
770 : public StackHintGeneratorForSymbol {
772 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
773 : StackHintGeneratorForSymbol(S, M) {}
775 std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) override {
776 // Printed parameters start at 1, not 0.
779 SmallString<200> buf;
780 llvm::raw_svector_ostream os(buf);
782 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
783 << " parameter failed";
788 std::string getMessageForReturn(const CallExpr *CallExpr) override {
789 return "Reallocation of returned value failed";
794 } // end anonymous namespace
796 // A map from the freed symbol to the symbol representing the return value of
797 // the free function.
798 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
801 class StopTrackingCallback final : public SymbolVisitor {
802 ProgramStateRef state;
804 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
805 ProgramStateRef getState() const { return state; }
807 bool VisitSymbol(SymbolRef sym) override {
808 state = state->remove<RegionState>(sym);
812 } // end anonymous namespace
814 //===----------------------------------------------------------------------===//
815 // Methods of MemFunctionInfoTy.
816 //===----------------------------------------------------------------------===//
818 void MemFunctionInfoTy::initIdentifierInfo(ASTContext &Ctx) const {
821 II_alloca = &Ctx.Idents.get("alloca");
822 II_malloc = &Ctx.Idents.get("malloc");
823 II_free = &Ctx.Idents.get("free");
824 II_realloc = &Ctx.Idents.get("realloc");
825 II_reallocf = &Ctx.Idents.get("reallocf");
826 II_calloc = &Ctx.Idents.get("calloc");
827 II_valloc = &Ctx.Idents.get("valloc");
828 II_strdup = &Ctx.Idents.get("strdup");
829 II_strndup = &Ctx.Idents.get("strndup");
830 II_wcsdup = &Ctx.Idents.get("wcsdup");
831 II_kmalloc = &Ctx.Idents.get("kmalloc");
832 II_kfree = &Ctx.Idents.get("kfree");
833 II_if_nameindex = &Ctx.Idents.get("if_nameindex");
834 II_if_freenameindex = &Ctx.Idents.get("if_freenameindex");
836 //MSVC uses `_`-prefixed instead, so we check for them too.
837 II_win_strdup = &Ctx.Idents.get("_strdup");
838 II_win_wcsdup = &Ctx.Idents.get("_wcsdup");
839 II_win_alloca = &Ctx.Idents.get("_alloca");
842 II_g_malloc = &Ctx.Idents.get("g_malloc");
843 II_g_malloc0 = &Ctx.Idents.get("g_malloc0");
844 II_g_realloc = &Ctx.Idents.get("g_realloc");
845 II_g_try_malloc = &Ctx.Idents.get("g_try_malloc");
846 II_g_try_malloc0 = &Ctx.Idents.get("g_try_malloc0");
847 II_g_try_realloc = &Ctx.Idents.get("g_try_realloc");
848 II_g_free = &Ctx.Idents.get("g_free");
849 II_g_memdup = &Ctx.Idents.get("g_memdup");
850 II_g_malloc_n = &Ctx.Idents.get("g_malloc_n");
851 II_g_malloc0_n = &Ctx.Idents.get("g_malloc0_n");
852 II_g_realloc_n = &Ctx.Idents.get("g_realloc_n");
853 II_g_try_malloc_n = &Ctx.Idents.get("g_try_malloc_n");
854 II_g_try_malloc0_n = &Ctx.Idents.get("g_try_malloc0_n");
855 II_g_try_realloc_n = &Ctx.Idents.get("g_try_realloc_n");
858 bool MemFunctionInfoTy::isMemFunction(const FunctionDecl *FD,
859 ASTContext &C) const {
860 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
863 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
866 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
869 if (isStandardNewDelete(FD, C))
875 bool MemFunctionInfoTy::isCMemFunction(const FunctionDecl *FD, ASTContext &C,
876 AllocationFamily Family,
877 MemoryOperationKind MemKind) const {
881 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
882 MemKind == MemoryOperationKind::MOK_Free);
883 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
884 MemKind == MemoryOperationKind::MOK_Allocate);
886 if (FD->getKind() == Decl::Function) {
887 const IdentifierInfo *FunI = FD->getIdentifier();
888 initIdentifierInfo(C);
890 if (Family == AF_Malloc && CheckFree) {
891 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
892 FunI == II_g_free || FunI == II_kfree)
896 if (Family == AF_Malloc && CheckAlloc) {
897 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
898 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
899 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
900 FunI == II_win_wcsdup || FunI == II_kmalloc ||
901 FunI == II_g_malloc || FunI == II_g_malloc0 ||
902 FunI == II_g_realloc || FunI == II_g_try_malloc ||
903 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
904 FunI == II_g_memdup || FunI == II_g_malloc_n ||
905 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
906 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
907 FunI == II_g_try_realloc_n)
911 if (Family == AF_IfNameIndex && CheckFree) {
912 if (FunI == II_if_freenameindex)
916 if (Family == AF_IfNameIndex && CheckAlloc) {
917 if (FunI == II_if_nameindex)
921 if (Family == AF_Alloca && CheckAlloc) {
922 if (FunI == II_alloca || FunI == II_win_alloca)
927 if (Family != AF_Malloc)
930 if (ShouldIncludeOwnershipAnnotatedFunctions && FD->hasAttrs()) {
931 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
932 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
933 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
936 } else if (OwnKind == OwnershipAttr::Returns) {
945 bool MemFunctionInfoTy::isStandardNewDelete(const FunctionDecl *FD,
946 ASTContext &C) const {
950 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
951 if (Kind != OO_New && Kind != OO_Array_New &&
952 Kind != OO_Delete && Kind != OO_Array_Delete)
955 // This is standard if and only if it's not defined in a user file.
956 SourceLocation L = FD->getLocation();
957 // If the header for operator delete is not included, it's still defined
958 // in an invalid source location. Check to make sure we don't crash.
959 return !L.isValid() || C.getSourceManager().isInSystemHeader(L);
962 //===----------------------------------------------------------------------===//
963 // Methods of MallocChecker and MallocBugVisitor.
964 //===----------------------------------------------------------------------===//
966 llvm::Optional<ProgramStateRef> MallocChecker::performKernelMalloc(
967 const CallExpr *CE, CheckerContext &C, const ProgramStateRef &State) const {
968 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
970 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
972 // One of the possible flags is M_ZERO, which means 'give me back an
973 // allocation which is already zeroed', like calloc.
975 // 2-argument kmalloc(), as used in the Linux kernel:
977 // void *kmalloc(size_t size, gfp_t flags);
979 // Has the similar flag value __GFP_ZERO.
981 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
982 // code could be shared.
984 ASTContext &Ctx = C.getASTContext();
985 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
987 if (!KernelZeroFlagVal.hasValue()) {
988 if (OS == llvm::Triple::FreeBSD)
989 KernelZeroFlagVal = 0x0100;
990 else if (OS == llvm::Triple::NetBSD)
991 KernelZeroFlagVal = 0x0002;
992 else if (OS == llvm::Triple::OpenBSD)
993 KernelZeroFlagVal = 0x0008;
994 else if (OS == llvm::Triple::Linux)
996 KernelZeroFlagVal = 0x8000;
998 // FIXME: We need a more general way of getting the M_ZERO value.
999 // See also: O_CREAT in UnixAPIChecker.cpp.
1001 // Fall back to normal malloc behavior on platforms where we don't
1006 // We treat the last argument as the flags argument, and callers fall-back to
1007 // normal malloc on a None return. This works for the FreeBSD kernel malloc
1008 // as well as Linux kmalloc.
1009 if (CE->getNumArgs() < 2)
1012 const Expr *FlagsEx = CE->getArg(CE->getNumArgs() - 1);
1013 const SVal V = C.getSVal(FlagsEx);
1014 if (!V.getAs<NonLoc>()) {
1015 // The case where 'V' can be a location can only be due to a bad header,
1016 // so in this case bail out.
1020 NonLoc Flags = V.castAs<NonLoc>();
1021 NonLoc ZeroFlag = C.getSValBuilder()
1022 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
1024 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
1026 FlagsEx->getType());
1027 if (MaskedFlagsUC.isUnknownOrUndef())
1029 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
1031 // Check if maskedFlags is non-zero.
1032 ProgramStateRef TrueState, FalseState;
1033 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
1035 // If M_ZERO is set, treat this like calloc (initialized).
1036 if (TrueState && !FalseState) {
1037 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
1038 return MallocMemAux(C, CE, CE->getArg(0), ZeroVal, TrueState);
1044 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
1045 const Expr *BlockBytes) {
1046 SValBuilder &SB = C.getSValBuilder();
1047 SVal BlocksVal = C.getSVal(Blocks);
1048 SVal BlockBytesVal = C.getSVal(BlockBytes);
1049 ProgramStateRef State = C.getState();
1050 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1051 SB.getContext().getSizeType());
1055 void MallocChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const {
1059 const FunctionDecl *FD = C.getCalleeDecl(CE);
1063 ProgramStateRef State = C.getState();
1064 bool IsKnownToBeAllocatedMemory = false;
1066 if (FD->getKind() == Decl::Function) {
1067 MemFunctionInfo.initIdentifierInfo(C.getASTContext());
1068 IdentifierInfo *FunI = FD->getIdentifier();
1070 if (FunI == MemFunctionInfo.II_malloc ||
1071 FunI == MemFunctionInfo.II_g_malloc ||
1072 FunI == MemFunctionInfo.II_g_try_malloc) {
1073 switch (CE->getNumArgs()) {
1077 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
1078 State = ProcessZeroAllocCheck(C, CE, 0, State);
1081 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
1084 llvm::Optional<ProgramStateRef> MaybeState =
1085 performKernelMalloc(CE, C, State);
1086 if (MaybeState.hasValue())
1087 State = MaybeState.getValue();
1089 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
1092 } else if (FunI == MemFunctionInfo.II_kmalloc) {
1093 if (CE->getNumArgs() < 1)
1095 llvm::Optional<ProgramStateRef> MaybeState =
1096 performKernelMalloc(CE, C, State);
1097 if (MaybeState.hasValue())
1098 State = MaybeState.getValue();
1100 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
1101 } else if (FunI == MemFunctionInfo.II_valloc) {
1102 if (CE->getNumArgs() < 1)
1104 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State);
1105 State = ProcessZeroAllocCheck(C, CE, 0, State);
1106 } else if (FunI == MemFunctionInfo.II_realloc ||
1107 FunI == MemFunctionInfo.II_g_realloc ||
1108 FunI == MemFunctionInfo.II_g_try_realloc) {
1109 State = ReallocMemAux(C, CE, /*ShouldFreeOnFail*/ false, State);
1110 State = ProcessZeroAllocCheck(C, CE, 1, State);
1111 } else if (FunI == MemFunctionInfo.II_reallocf) {
1112 State = ReallocMemAux(C, CE, /*ShouldFreeOnFail*/ true, State);
1113 State = ProcessZeroAllocCheck(C, CE, 1, State);
1114 } else if (FunI == MemFunctionInfo.II_calloc) {
1115 State = CallocMem(C, CE, State);
1116 State = ProcessZeroAllocCheck(C, CE, 0, State);
1117 State = ProcessZeroAllocCheck(C, CE, 1, State);
1118 } else if (FunI == MemFunctionInfo.II_free ||
1119 FunI == MemFunctionInfo.II_g_free ||
1120 FunI == MemFunctionInfo.II_kfree) {
1121 if (suppressDeallocationsInSuspiciousContexts(CE, C))
1124 State = FreeMemAux(C, CE, State, 0, false, IsKnownToBeAllocatedMemory);
1125 } else if (FunI == MemFunctionInfo.II_strdup ||
1126 FunI == MemFunctionInfo.II_win_strdup ||
1127 FunI == MemFunctionInfo.II_wcsdup ||
1128 FunI == MemFunctionInfo.II_win_wcsdup) {
1129 State = MallocUpdateRefState(C, CE, State);
1130 } else if (FunI == MemFunctionInfo.II_strndup) {
1131 State = MallocUpdateRefState(C, CE, State);
1132 } else if (FunI == MemFunctionInfo.II_alloca ||
1133 FunI == MemFunctionInfo.II_win_alloca) {
1134 if (CE->getNumArgs() < 1)
1136 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
1138 State = ProcessZeroAllocCheck(C, CE, 0, State);
1139 } else if (MemFunctionInfo.isStandardNewDelete(FD, C.getASTContext())) {
1140 // Process direct calls to operator new/new[]/delete/delete[] functions
1141 // as distinct from new/new[]/delete/delete[] expressions that are
1142 // processed by the checkPostStmt callbacks for CXXNewExpr and
1144 switch (FD->getOverloadedOperator()) {
1146 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
1148 State = ProcessZeroAllocCheck(C, CE, 0, State);
1151 State = MallocMemAux(C, CE, CE->getArg(0), UndefinedVal(), State,
1153 State = ProcessZeroAllocCheck(C, CE, 0, State);
1156 case OO_Array_Delete:
1157 State = FreeMemAux(C, CE, State, 0, false, IsKnownToBeAllocatedMemory);
1160 llvm_unreachable("not a new/delete operator");
1162 } else if (FunI == MemFunctionInfo.II_if_nameindex) {
1163 // Should we model this differently? We can allocate a fixed number of
1164 // elements with zeros in the last one.
1165 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
1167 } else if (FunI == MemFunctionInfo.II_if_freenameindex) {
1168 State = FreeMemAux(C, CE, State, 0, false, IsKnownToBeAllocatedMemory);
1169 } else if (FunI == MemFunctionInfo.II_g_malloc0 ||
1170 FunI == MemFunctionInfo.II_g_try_malloc0) {
1171 if (CE->getNumArgs() < 1)
1173 SValBuilder &svalBuilder = C.getSValBuilder();
1174 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1175 State = MallocMemAux(C, CE, CE->getArg(0), zeroVal, State);
1176 State = ProcessZeroAllocCheck(C, CE, 0, State);
1177 } else if (FunI == MemFunctionInfo.II_g_memdup) {
1178 if (CE->getNumArgs() < 2)
1180 State = MallocMemAux(C, CE, CE->getArg(1), UndefinedVal(), State);
1181 State = ProcessZeroAllocCheck(C, CE, 1, State);
1182 } else if (FunI == MemFunctionInfo.II_g_malloc_n ||
1183 FunI == MemFunctionInfo.II_g_try_malloc_n ||
1184 FunI == MemFunctionInfo.II_g_malloc0_n ||
1185 FunI == MemFunctionInfo.II_g_try_malloc0_n) {
1186 if (CE->getNumArgs() < 2)
1188 SVal Init = UndefinedVal();
1189 if (FunI == MemFunctionInfo.II_g_malloc0_n ||
1190 FunI == MemFunctionInfo.II_g_try_malloc0_n) {
1191 SValBuilder &SB = C.getSValBuilder();
1192 Init = SB.makeZeroVal(SB.getContext().CharTy);
1194 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
1195 State = MallocMemAux(C, CE, TotalSize, Init, State);
1196 State = ProcessZeroAllocCheck(C, CE, 0, State);
1197 State = ProcessZeroAllocCheck(C, CE, 1, State);
1198 } else if (FunI == MemFunctionInfo.II_g_realloc_n ||
1199 FunI == MemFunctionInfo.II_g_try_realloc_n) {
1200 if (CE->getNumArgs() < 3)
1202 State = ReallocMemAux(C, CE, /*ShouldFreeOnFail*/ false, State,
1203 /*SuffixWithN*/ true);
1204 State = ProcessZeroAllocCheck(C, CE, 1, State);
1205 State = ProcessZeroAllocCheck(C, CE, 2, State);
1209 if (MemFunctionInfo.ShouldIncludeOwnershipAnnotatedFunctions ||
1210 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
1211 // Check all the attributes, if there are any.
1212 // There can be multiple of these attributes.
1214 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
1215 switch (I->getOwnKind()) {
1216 case OwnershipAttr::Returns:
1217 State = MallocMemReturnsAttr(C, CE, I, State);
1219 case OwnershipAttr::Takes:
1220 case OwnershipAttr::Holds:
1221 State = FreeMemAttr(C, CE, I, State);
1226 C.addTransition(State);
1229 // Performs a 0-sized allocations check.
1230 ProgramStateRef MallocChecker::ProcessZeroAllocCheck(
1231 CheckerContext &C, const Expr *E, const unsigned IndexOfSizeArg,
1232 ProgramStateRef State, Optional<SVal> RetVal) {
1237 RetVal = C.getSVal(E);
1239 const Expr *Arg = nullptr;
1241 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1242 Arg = CE->getArg(IndexOfSizeArg);
1244 else if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1246 Arg = *NE->getArraySize();
1251 llvm_unreachable("not a CallExpr or CXXNewExpr");
1255 Optional<DefinedSVal> DefArgVal = C.getSVal(Arg).getAs<DefinedSVal>();
1260 // Check if the allocation size is 0.
1261 ProgramStateRef TrueState, FalseState;
1262 SValBuilder &SvalBuilder = C.getSValBuilder();
1264 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1266 std::tie(TrueState, FalseState) =
1267 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1269 if (TrueState && !FalseState) {
1270 SymbolRef Sym = RetVal->getAsLocSymbol();
1274 const RefState *RS = State->get<RegionState>(Sym);
1276 if (RS->isAllocated())
1277 return TrueState->set<RegionState>(Sym,
1278 RefState::getAllocatedOfSizeZero(RS));
1282 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1283 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1284 // tracked. Add zero-reallocated Sym to the state to catch references
1285 // to zero-allocated memory.
1286 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1290 // Assume the value is non-zero going forward.
1295 static QualType getDeepPointeeType(QualType T) {
1296 QualType Result = T, PointeeType = T->getPointeeType();
1297 while (!PointeeType.isNull()) {
1298 Result = PointeeType;
1299 PointeeType = PointeeType->getPointeeType();
1304 /// \returns true if the constructor invoked by \p NE has an argument of a
1305 /// pointer/reference to a record type.
1306 static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE) {
1308 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1312 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1315 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1317 // Iterate over the constructor parameters.
1318 for (const auto *CtorParam : CtorD->parameters()) {
1320 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1321 if (CtorParamPointeeT.isNull())
1324 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1326 if (CtorParamPointeeT->getAsCXXRecordDecl())
1333 void MallocChecker::processNewAllocation(const CXXNewExpr *NE,
1335 SVal Target) const {
1336 if (!MemFunctionInfo.isStandardNewDelete(NE->getOperatorNew(),
1340 const ParentMap &PM = C.getLocationContext()->getParentMap();
1342 // Non-trivial constructors have a chance to escape 'this', but marking all
1343 // invocations of trivial constructors as escaped would cause too great of
1344 // reduction of true positives, so let's just do that for constructors that
1345 // have an argument of a pointer-to-record type.
1346 if (!PM.isConsumedExpr(NE) && hasNonTrivialConstructorCall(NE))
1349 ProgramStateRef State = C.getState();
1350 // The return value from operator new is bound to a specified initialization
1351 // value (if any) and we don't want to loose this value. So we call
1352 // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1353 // existing binding.
1354 State = MallocUpdateRefState(C, NE, State, NE->isArray() ? AF_CXXNewArray
1355 : AF_CXXNew, Target);
1356 State = addExtentSize(C, NE, State, Target);
1357 State = ProcessZeroAllocCheck(C, NE, 0, State, Target);
1358 C.addTransition(State);
1361 void MallocChecker::checkPostStmt(const CXXNewExpr *NE,
1362 CheckerContext &C) const {
1363 if (!C.getAnalysisManager().getAnalyzerOptions().MayInlineCXXAllocator)
1364 processNewAllocation(NE, C, C.getSVal(NE));
1367 void MallocChecker::checkNewAllocator(const CXXNewExpr *NE, SVal Target,
1368 CheckerContext &C) const {
1370 processNewAllocation(NE, C, Target);
1373 // Sets the extent value of the MemRegion allocated by
1374 // new expression NE to its size in Bytes.
1376 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1377 const CXXNewExpr *NE,
1378 ProgramStateRef State,
1382 SValBuilder &svalBuilder = C.getSValBuilder();
1384 const SubRegion *Region;
1385 if (NE->isArray()) {
1386 const Expr *SizeExpr = *NE->getArraySize();
1387 ElementCount = C.getSVal(SizeExpr);
1388 // Store the extent size for the (symbolic)region
1389 // containing the elements.
1390 Region = Target.getAsRegion()
1391 ->castAs<SubRegion>()
1393 ->castAs<SubRegion>();
1395 ElementCount = svalBuilder.makeIntVal(1, true);
1396 Region = Target.getAsRegion()->castAs<SubRegion>();
1399 // Set the region's extent equal to the Size in Bytes.
1400 QualType ElementType = NE->getAllocatedType();
1401 ASTContext &AstContext = C.getASTContext();
1402 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1404 if (ElementCount.getAs<NonLoc>()) {
1405 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1406 // size in Bytes = ElementCount*TypeSize
1407 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1408 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1409 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1410 svalBuilder.getArrayIndexType());
1411 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1412 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1413 State = State->assume(extentMatchesSize, true);
1418 void MallocChecker::checkPreStmt(const CXXDeleteExpr *DE,
1419 CheckerContext &C) const {
1421 if (!ChecksEnabled[CK_NewDeleteChecker])
1422 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
1423 checkUseAfterFree(Sym, C, DE->getArgument());
1425 if (!MemFunctionInfo.isStandardNewDelete(DE->getOperatorDelete(),
1429 ProgramStateRef State = C.getState();
1430 bool IsKnownToBeAllocated;
1431 State = FreeMemAux(C, DE->getArgument(), DE, State,
1432 /*Hold*/ false, IsKnownToBeAllocated);
1434 C.addTransition(State);
1437 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1438 // If the first selector piece is one of the names below, assume that the
1439 // object takes ownership of the memory, promising to eventually deallocate it
1441 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1442 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1443 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1444 return FirstSlot == "dataWithBytesNoCopy" ||
1445 FirstSlot == "initWithBytesNoCopy" ||
1446 FirstSlot == "initWithCharactersNoCopy";
1449 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1450 Selector S = Call.getSelector();
1452 // FIXME: We should not rely on fully-constrained symbols being folded.
1453 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1454 if (S.getNameForSlot(i).equals("freeWhenDone"))
1455 return !Call.getArgSVal(i).isZeroConstant();
1460 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1461 CheckerContext &C) const {
1465 if (!isKnownDeallocObjCMethodName(Call))
1468 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1472 if (Call.hasNonZeroCallbackArg())
1475 bool IsKnownToBeAllocatedMemory;
1476 ProgramStateRef State =
1477 FreeMemAux(C, Call.getArgExpr(0), Call.getOriginExpr(), C.getState(),
1478 /*Hold=*/true, IsKnownToBeAllocatedMemory,
1479 /*RetNullOnFailure=*/true);
1481 C.addTransition(State);
1485 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallExpr *CE,
1486 const OwnershipAttr *Att,
1487 ProgramStateRef State) const {
1491 if (Att->getModule() != MemFunctionInfo.II_malloc)
1494 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1496 return MallocMemAux(C, CE, CE->getArg(I->getASTIndex()), UndefinedVal(),
1499 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1502 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1504 const Expr *SizeEx, SVal Init,
1505 ProgramStateRef State,
1506 AllocationFamily Family) {
1510 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init, State, Family);
1513 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1515 SVal Size, SVal Init,
1516 ProgramStateRef State,
1517 AllocationFamily Family) {
1521 // We expect the malloc functions to return a pointer.
1522 if (!Loc::isLocType(CE->getType()))
1525 // Bind the return value to the symbolic value from the heap region.
1526 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1527 // side effects other than what we model here.
1528 unsigned Count = C.blockCount();
1529 SValBuilder &svalBuilder = C.getSValBuilder();
1530 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1531 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1532 .castAs<DefinedSVal>();
1533 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1535 // Fill the region with the initialization value.
1536 State = State->bindDefaultInitial(RetVal, Init, LCtx);
1538 // Set the region's extent equal to the Size parameter.
1539 const SymbolicRegion *R =
1540 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1543 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1544 Size.getAs<DefinedOrUnknownSVal>()) {
1545 SValBuilder &svalBuilder = C.getSValBuilder();
1546 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1547 DefinedOrUnknownSVal extentMatchesSize =
1548 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1550 State = State->assume(extentMatchesSize, true);
1554 return MallocUpdateRefState(C, CE, State, Family);
1557 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
1558 ProgramStateRef State,
1559 AllocationFamily Family,
1560 Optional<SVal> RetVal) {
1564 // Get the return value.
1566 RetVal = C.getSVal(E);
1568 // We expect the malloc functions to return a pointer.
1569 if (!RetVal->getAs<Loc>())
1572 SymbolRef Sym = RetVal->getAsLocSymbol();
1573 // This is a return value of a function that was not inlined, such as malloc()
1574 // or new(). We've checked that in the caller. Therefore, it must be a symbol.
1577 // Set the symbol's state to Allocated.
1578 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1581 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1583 const OwnershipAttr *Att,
1584 ProgramStateRef State) const {
1588 if (Att->getModule() != MemFunctionInfo.II_malloc)
1591 bool IsKnownToBeAllocated = false;
1593 for (const auto &Arg : Att->args()) {
1594 ProgramStateRef StateI = FreeMemAux(
1595 C, CE, State, Arg.getASTIndex(),
1596 Att->getOwnKind() == OwnershipAttr::Holds, IsKnownToBeAllocated);
1603 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C, const CallExpr *CE,
1604 ProgramStateRef State, unsigned Num,
1605 bool Hold, bool &IsKnownToBeAllocated,
1606 bool ReturnsNullOnFailure) const {
1610 if (CE->getNumArgs() < (Num + 1))
1613 return FreeMemAux(C, CE->getArg(Num), CE, State, Hold, IsKnownToBeAllocated,
1614 ReturnsNullOnFailure);
1617 /// Checks if the previous call to free on the given symbol failed - if free
1618 /// failed, returns true. Also, returns the corresponding return value symbol.
1619 static bool didPreviousFreeFail(ProgramStateRef State,
1620 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1621 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1623 assert(*Ret && "We should not store the null return symbol");
1624 ConstraintManager &CMgr = State->getConstraintManager();
1625 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1626 RetStatusSymbol = *Ret;
1627 return FreeFailed.isConstrainedTrue();
1632 static AllocationFamily
1633 getAllocationFamily(const MemFunctionInfoTy &MemFunctionInfo, CheckerContext &C,
1639 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1640 const FunctionDecl *FD = C.getCalleeDecl(CE);
1643 FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1645 ASTContext &Ctx = C.getASTContext();
1647 if (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_Malloc,
1648 MemoryOperationKind::MOK_Any))
1651 if (MemFunctionInfo.isStandardNewDelete(FD, Ctx)) {
1652 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
1653 if (Kind == OO_New || Kind == OO_Delete)
1655 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1656 return AF_CXXNewArray;
1659 if (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_IfNameIndex,
1660 MemoryOperationKind::MOK_Any))
1661 return AF_IfNameIndex;
1663 if (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_Alloca,
1664 MemoryOperationKind::MOK_Any))
1670 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1671 return NE->isArray() ? AF_CXXNewArray : AF_CXXNew;
1673 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(S))
1674 return DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1676 if (isa<ObjCMessageExpr>(S))
1682 static bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1684 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1685 // FIXME: This doesn't handle indirect calls.
1686 const FunctionDecl *FD = CE->getDirectCallee();
1691 if (!FD->isOverloadedOperator())
1696 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1697 if (Msg->isInstanceMessage())
1701 Msg->getSelector().print(os);
1705 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1707 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1712 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1714 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1722 static void printExpectedAllocName(raw_ostream &os,
1723 const MemFunctionInfoTy &MemFunctionInfo,
1724 CheckerContext &C, const Expr *E) {
1725 AllocationFamily Family = getAllocationFamily(MemFunctionInfo, C, E);
1728 case AF_Malloc: os << "malloc()"; return;
1729 case AF_CXXNew: os << "'new'"; return;
1730 case AF_CXXNewArray: os << "'new[]'"; return;
1731 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1732 case AF_InnerBuffer: os << "container-specific allocator"; return;
1734 case AF_None: llvm_unreachable("not a deallocation expression");
1738 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) {
1740 case AF_Malloc: os << "free()"; return;
1741 case AF_CXXNew: os << "'delete'"; return;
1742 case AF_CXXNewArray: os << "'delete[]'"; return;
1743 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1744 case AF_InnerBuffer: os << "container-specific deallocator"; return;
1746 case AF_None: llvm_unreachable("suspicious argument");
1750 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1751 const Expr *ArgExpr,
1752 const Expr *ParentExpr,
1753 ProgramStateRef State, bool Hold,
1754 bool &IsKnownToBeAllocated,
1755 bool ReturnsNullOnFailure) const {
1760 SVal ArgVal = C.getSVal(ArgExpr);
1761 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1763 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1765 // Check for null dereferences.
1766 if (!location.getAs<Loc>())
1769 // The explicit NULL case, no operation is performed.
1770 ProgramStateRef notNullState, nullState;
1771 std::tie(notNullState, nullState) = State->assume(location);
1772 if (nullState && !notNullState)
1775 // Unknown values could easily be okay
1776 // Undefined values are handled elsewhere
1777 if (ArgVal.isUnknownOrUndef())
1780 const MemRegion *R = ArgVal.getAsRegion();
1782 // Nonlocs can't be freed, of course.
1783 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1785 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1789 R = R->StripCasts();
1791 // Blocks might show up as heap data, but should not be free()d
1792 if (isa<BlockDataRegion>(R)) {
1793 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1797 const MemSpaceRegion *MS = R->getMemorySpace();
1799 // Parameters, locals, statics, globals, and memory returned by
1800 // __builtin_alloca() shouldn't be freed.
1801 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1802 // FIXME: at the time this code was written, malloc() regions were
1803 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1804 // This means that there isn't actually anything from HeapSpaceRegion
1805 // that should be freed, even though we allow it here.
1806 // Of course, free() can work on memory allocated outside the current
1807 // function, so UnknownSpaceRegion is always a possibility.
1808 // False negatives are better than false positives.
1810 if (isa<AllocaRegion>(R))
1811 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1813 ReportBadFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1818 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1819 // Various cases could lead to non-symbol values here.
1820 // For now, ignore them.
1824 SymbolRef SymBase = SrBase->getSymbol();
1825 const RefState *RsBase = State->get<RegionState>(SymBase);
1826 SymbolRef PreviousRetStatusSymbol = nullptr;
1828 IsKnownToBeAllocated =
1829 RsBase && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero());
1833 // Memory returned by alloca() shouldn't be freed.
1834 if (RsBase->getAllocationFamily() == AF_Alloca) {
1835 ReportFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1839 // Check for double free first.
1840 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1841 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1842 ReportDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1843 SymBase, PreviousRetStatusSymbol);
1846 // If the pointer is allocated or escaped, but we are now trying to free it,
1847 // check that the call to free is proper.
1848 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1849 RsBase->isEscaped()) {
1851 // Check if an expected deallocation function matches the real one.
1852 bool DeallocMatchesAlloc =
1853 RsBase->getAllocationFamily() ==
1854 getAllocationFamily(MemFunctionInfo, C, ParentExpr);
1855 if (!DeallocMatchesAlloc) {
1856 ReportMismatchedDealloc(C, ArgExpr->getSourceRange(),
1857 ParentExpr, RsBase, SymBase, Hold);
1861 // Check if the memory location being freed is the actual location
1862 // allocated, or an offset.
1863 RegionOffset Offset = R->getAsOffset();
1864 if (Offset.isValid() &&
1865 !Offset.hasSymbolicOffset() &&
1866 Offset.getOffset() != 0) {
1867 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1868 ReportOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1875 if (SymBase->getType()->isFunctionPointerType()) {
1876 ReportFunctionPointerFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr);
1880 // Clean out the info on previous call to free return info.
1881 State = State->remove<FreeReturnValue>(SymBase);
1883 // Keep track of the return value. If it is NULL, we will know that free
1885 if (ReturnsNullOnFailure) {
1886 SVal RetVal = C.getSVal(ParentExpr);
1887 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1888 if (RetStatusSymbol) {
1889 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1890 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1894 AllocationFamily Family =
1895 RsBase ? RsBase->getAllocationFamily()
1896 : getAllocationFamily(MemFunctionInfo, C, ParentExpr);
1899 return State->set<RegionState>(SymBase,
1900 RefState::getRelinquished(Family,
1903 return State->set<RegionState>(SymBase,
1904 RefState::getReleased(Family, ParentExpr));
1907 Optional<MallocChecker::CheckKind>
1908 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1909 bool IsALeakCheck) const {
1913 case AF_IfNameIndex: {
1914 if (ChecksEnabled[CK_MallocChecker])
1915 return CK_MallocChecker;
1919 case AF_CXXNewArray: {
1921 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1922 return CK_NewDeleteLeaksChecker;
1925 if (ChecksEnabled[CK_NewDeleteChecker])
1926 return CK_NewDeleteChecker;
1930 case AF_InnerBuffer: {
1931 if (ChecksEnabled[CK_InnerPointerChecker])
1932 return CK_InnerPointerChecker;
1936 llvm_unreachable("no family");
1939 llvm_unreachable("unhandled family");
1942 Optional<MallocChecker::CheckKind>
1943 MallocChecker::getCheckIfTracked(CheckerContext &C,
1944 const Stmt *AllocDeallocStmt,
1945 bool IsALeakCheck) const {
1946 return getCheckIfTracked(
1947 getAllocationFamily(MemFunctionInfo, C, AllocDeallocStmt), IsALeakCheck);
1950 Optional<MallocChecker::CheckKind>
1951 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1952 bool IsALeakCheck) const {
1953 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1954 return CK_MallocChecker;
1956 const RefState *RS = C.getState()->get<RegionState>(Sym);
1958 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1961 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1962 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1963 os << "an integer (" << IntVal->getValue() << ")";
1964 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1965 os << "a constant address (" << ConstAddr->getValue() << ")";
1966 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1967 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1974 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1975 const MemRegion *MR) {
1976 switch (MR->getKind()) {
1977 case MemRegion::FunctionCodeRegionKind: {
1978 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1980 os << "the address of the function '" << *FD << '\'';
1982 os << "the address of a function";
1985 case MemRegion::BlockCodeRegionKind:
1988 case MemRegion::BlockDataRegionKind:
1989 // FIXME: where the block came from?
1993 const MemSpaceRegion *MS = MR->getMemorySpace();
1995 if (isa<StackLocalsSpaceRegion>(MS)) {
1996 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2004 os << "the address of the local variable '" << VD->getName() << "'";
2006 os << "the address of a local stack variable";
2010 if (isa<StackArgumentsSpaceRegion>(MS)) {
2011 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2019 os << "the address of the parameter '" << VD->getName() << "'";
2021 os << "the address of a parameter";
2025 if (isa<GlobalsSpaceRegion>(MS)) {
2026 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2034 if (VD->isStaticLocal())
2035 os << "the address of the static variable '" << VD->getName() << "'";
2037 os << "the address of the global variable '" << VD->getName() << "'";
2039 os << "the address of a global variable";
2048 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
2050 const Expr *DeallocExpr) const {
2052 if (!ChecksEnabled[CK_MallocChecker] &&
2053 !ChecksEnabled[CK_NewDeleteChecker])
2056 Optional<MallocChecker::CheckKind> CheckKind =
2057 getCheckIfTracked(C, DeallocExpr);
2058 if (!CheckKind.hasValue())
2061 if (ExplodedNode *N = C.generateErrorNode()) {
2062 if (!BT_BadFree[*CheckKind])
2063 BT_BadFree[*CheckKind].reset(new BugType(
2064 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2066 SmallString<100> buf;
2067 llvm::raw_svector_ostream os(buf);
2069 const MemRegion *MR = ArgVal.getAsRegion();
2070 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2071 MR = ER->getSuperRegion();
2073 os << "Argument to ";
2074 if (!printAllocDeallocName(os, C, DeallocExpr))
2075 os << "deallocator";
2078 bool Summarized = MR ? SummarizeRegion(os, MR)
2079 : SummarizeValue(os, ArgVal);
2081 os << ", which is not memory allocated by ";
2083 os << "not memory allocated by ";
2085 printExpectedAllocName(os, MemFunctionInfo, C, DeallocExpr);
2087 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2089 R->markInteresting(MR);
2091 C.emitReport(std::move(R));
2095 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
2096 SourceRange Range) const {
2098 Optional<MallocChecker::CheckKind> CheckKind;
2100 if (ChecksEnabled[CK_MallocChecker])
2101 CheckKind = CK_MallocChecker;
2102 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
2103 CheckKind = CK_MismatchedDeallocatorChecker;
2107 if (ExplodedNode *N = C.generateErrorNode()) {
2108 if (!BT_FreeAlloca[*CheckKind])
2109 BT_FreeAlloca[*CheckKind].reset(new BugType(
2110 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
2112 auto R = std::make_unique<PathSensitiveBugReport>(
2113 *BT_FreeAlloca[*CheckKind],
2114 "Memory allocated by alloca() should not be deallocated", N);
2115 R->markInteresting(ArgVal.getAsRegion());
2117 C.emitReport(std::move(R));
2121 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
2123 const Expr *DeallocExpr,
2126 bool OwnershipTransferred) const {
2128 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
2131 if (ExplodedNode *N = C.generateErrorNode()) {
2132 if (!BT_MismatchedDealloc)
2133 BT_MismatchedDealloc.reset(
2134 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
2135 "Bad deallocator", categories::MemoryError));
2137 SmallString<100> buf;
2138 llvm::raw_svector_ostream os(buf);
2140 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2141 SmallString<20> AllocBuf;
2142 llvm::raw_svector_ostream AllocOs(AllocBuf);
2143 SmallString<20> DeallocBuf;
2144 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2146 if (OwnershipTransferred) {
2147 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
2148 os << DeallocOs.str() << " cannot";
2152 os << " take ownership of memory";
2154 if (printAllocDeallocName(AllocOs, C, AllocExpr))
2155 os << " allocated by " << AllocOs.str();
2158 if (printAllocDeallocName(AllocOs, C, AllocExpr))
2159 os << " allocated by " << AllocOs.str();
2161 os << " should be deallocated by ";
2162 printExpectedDeallocName(os, RS->getAllocationFamily());
2164 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
2165 os << ", not " << DeallocOs.str();
2168 auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc,
2170 R->markInteresting(Sym);
2172 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2173 C.emitReport(std::move(R));
2177 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
2178 SourceRange Range, const Expr *DeallocExpr,
2179 const Expr *AllocExpr) const {
2182 if (!ChecksEnabled[CK_MallocChecker] &&
2183 !ChecksEnabled[CK_NewDeleteChecker])
2186 Optional<MallocChecker::CheckKind> CheckKind =
2187 getCheckIfTracked(C, AllocExpr);
2188 if (!CheckKind.hasValue())
2191 ExplodedNode *N = C.generateErrorNode();
2195 if (!BT_OffsetFree[*CheckKind])
2196 BT_OffsetFree[*CheckKind].reset(new BugType(
2197 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
2199 SmallString<100> buf;
2200 llvm::raw_svector_ostream os(buf);
2201 SmallString<20> AllocNameBuf;
2202 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2204 const MemRegion *MR = ArgVal.getAsRegion();
2205 assert(MR && "Only MemRegion based symbols can have offset free errors");
2207 RegionOffset Offset = MR->getAsOffset();
2208 assert((Offset.isValid() &&
2209 !Offset.hasSymbolicOffset() &&
2210 Offset.getOffset() != 0) &&
2211 "Only symbols with a valid offset can have offset free errors");
2213 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
2215 os << "Argument to ";
2216 if (!printAllocDeallocName(os, C, DeallocExpr))
2217 os << "deallocator";
2218 os << " is offset by "
2221 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
2222 << " from the start of ";
2223 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
2224 os << "memory allocated by " << AllocNameOs.str();
2226 os << "allocated memory";
2228 auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind],
2230 R->markInteresting(MR->getBaseRegion());
2232 C.emitReport(std::move(R));
2235 void MallocChecker::ReportUseAfterFree(CheckerContext &C, SourceRange Range,
2236 SymbolRef Sym) const {
2238 if (!ChecksEnabled[CK_MallocChecker] &&
2239 !ChecksEnabled[CK_NewDeleteChecker] &&
2240 !ChecksEnabled[CK_InnerPointerChecker])
2243 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2244 if (!CheckKind.hasValue())
2247 if (ExplodedNode *N = C.generateErrorNode()) {
2248 if (!BT_UseFree[*CheckKind])
2249 BT_UseFree[*CheckKind].reset(new BugType(
2250 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
2252 AllocationFamily AF =
2253 C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2255 auto R = std::make_unique<PathSensitiveBugReport>(
2256 *BT_UseFree[*CheckKind],
2257 AF == AF_InnerBuffer
2258 ? "Inner pointer of container used after re/deallocation"
2259 : "Use of memory after it is freed",
2262 R->markInteresting(Sym);
2264 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2266 if (AF == AF_InnerBuffer)
2267 R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2269 C.emitReport(std::move(R));
2273 void MallocChecker::ReportDoubleFree(CheckerContext &C, SourceRange Range,
2274 bool Released, SymbolRef Sym,
2275 SymbolRef PrevSym) const {
2277 if (!ChecksEnabled[CK_MallocChecker] &&
2278 !ChecksEnabled[CK_NewDeleteChecker])
2281 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2282 if (!CheckKind.hasValue())
2285 if (ExplodedNode *N = C.generateErrorNode()) {
2286 if (!BT_DoubleFree[*CheckKind])
2287 BT_DoubleFree[*CheckKind].reset(new BugType(
2288 CheckNames[*CheckKind], "Double free", categories::MemoryError));
2290 auto R = std::make_unique<PathSensitiveBugReport>(
2291 *BT_DoubleFree[*CheckKind],
2292 (Released ? "Attempt to free released memory"
2293 : "Attempt to free non-owned memory"),
2296 R->markInteresting(Sym);
2298 R->markInteresting(PrevSym);
2299 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2300 C.emitReport(std::move(R));
2304 void MallocChecker::ReportDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2306 if (!ChecksEnabled[CK_NewDeleteChecker])
2309 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2310 if (!CheckKind.hasValue())
2313 if (ExplodedNode *N = C.generateErrorNode()) {
2314 if (!BT_DoubleDelete)
2315 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2317 categories::MemoryError));
2319 auto R = std::make_unique<PathSensitiveBugReport>(
2320 *BT_DoubleDelete, "Attempt to delete released memory", N);
2322 R->markInteresting(Sym);
2323 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2324 C.emitReport(std::move(R));
2328 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2330 SymbolRef Sym) const {
2332 if (!ChecksEnabled[CK_MallocChecker] &&
2333 !ChecksEnabled[CK_NewDeleteChecker])
2336 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2338 if (!CheckKind.hasValue())
2341 if (ExplodedNode *N = C.generateErrorNode()) {
2342 if (!BT_UseZerroAllocated[*CheckKind])
2343 BT_UseZerroAllocated[*CheckKind].reset(
2344 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2345 categories::MemoryError));
2347 auto R = std::make_unique<PathSensitiveBugReport>(
2348 *BT_UseZerroAllocated[*CheckKind], "Use of zero-allocated memory", N);
2352 R->markInteresting(Sym);
2353 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2355 C.emitReport(std::move(R));
2359 void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2361 const Expr *FreeExpr) const {
2362 if (!ChecksEnabled[CK_MallocChecker])
2365 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, FreeExpr);
2366 if (!CheckKind.hasValue())
2369 if (ExplodedNode *N = C.generateErrorNode()) {
2370 if (!BT_BadFree[*CheckKind])
2371 BT_BadFree[*CheckKind].reset(new BugType(
2372 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2374 SmallString<100> Buf;
2375 llvm::raw_svector_ostream Os(Buf);
2377 const MemRegion *MR = ArgVal.getAsRegion();
2378 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2379 MR = ER->getSuperRegion();
2381 Os << "Argument to ";
2382 if (!printAllocDeallocName(Os, C, FreeExpr))
2383 Os << "deallocator";
2385 Os << " is a function pointer";
2387 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2389 R->markInteresting(MR);
2391 C.emitReport(std::move(R));
2395 ProgramStateRef MallocChecker::ReallocMemAux(CheckerContext &C,
2397 bool ShouldFreeOnFail,
2398 ProgramStateRef State,
2399 bool SuffixWithN) const {
2403 if (SuffixWithN && CE->getNumArgs() < 3)
2405 else if (CE->getNumArgs() < 2)
2408 const Expr *arg0Expr = CE->getArg(0);
2409 SVal Arg0Val = C.getSVal(arg0Expr);
2410 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2412 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2414 SValBuilder &svalBuilder = C.getSValBuilder();
2416 DefinedOrUnknownSVal PtrEQ =
2417 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2419 // Get the size argument.
2420 const Expr *Arg1 = CE->getArg(1);
2422 // Get the value of the size argument.
2423 SVal TotalSize = C.getSVal(Arg1);
2425 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2426 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2429 // Compare the size argument to 0.
2430 DefinedOrUnknownSVal SizeZero =
2431 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2432 svalBuilder.makeIntValWithPtrWidth(0, false));
2434 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2435 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2436 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2437 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2438 // We only assume exceptional states if they are definitely true; if the
2439 // state is under-constrained, assume regular realloc behavior.
2440 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2441 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2443 // If the ptr is NULL and the size is not 0, the call is equivalent to
2445 if (PrtIsNull && !SizeIsZero) {
2446 ProgramStateRef stateMalloc = MallocMemAux(C, CE, TotalSize,
2447 UndefinedVal(), StatePtrIsNull);
2451 if (PrtIsNull && SizeIsZero)
2454 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2456 SymbolRef FromPtr = arg0Val.getAsSymbol();
2457 SVal RetVal = C.getSVal(CE);
2458 SymbolRef ToPtr = RetVal.getAsSymbol();
2459 if (!FromPtr || !ToPtr)
2462 bool IsKnownToBeAllocated = false;
2464 // If the size is 0, free the memory.
2466 // The semantics of the return value are:
2467 // If size was equal to 0, either NULL or a pointer suitable to be passed
2468 // to free() is returned. We just free the input pointer and do not add
2469 // any constrains on the output pointer.
2470 if (ProgramStateRef stateFree =
2471 FreeMemAux(C, CE, StateSizeIsZero, 0, false, IsKnownToBeAllocated))
2474 // Default behavior.
2475 if (ProgramStateRef stateFree =
2476 FreeMemAux(C, CE, State, 0, false, IsKnownToBeAllocated)) {
2478 ProgramStateRef stateRealloc = MallocMemAux(C, CE, TotalSize,
2479 UnknownVal(), stateFree);
2483 OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure;
2484 if (ShouldFreeOnFail)
2485 Kind = OAR_FreeOnFailure;
2486 else if (!IsKnownToBeAllocated)
2487 Kind = OAR_DoNotTrackAfterFailure;
2489 // Record the info about the reallocated symbol so that we could properly
2490 // process failed reallocation.
2491 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2492 ReallocPair(FromPtr, Kind));
2493 // The reallocated symbol should stay alive for as long as the new symbol.
2494 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2495 return stateRealloc;
2500 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C, const CallExpr *CE,
2501 ProgramStateRef State) {
2505 if (CE->getNumArgs() < 2)
2508 SValBuilder &svalBuilder = C.getSValBuilder();
2509 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2510 SVal TotalSize = evalMulForBufferSize(C, CE->getArg(0), CE->getArg(1));
2512 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2515 MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N,
2517 CheckerContext &C) {
2518 const LocationContext *LeakContext = N->getLocationContext();
2519 // Walk the ExplodedGraph backwards and find the first node that referred to
2520 // the tracked symbol.
2521 const ExplodedNode *AllocNode = N;
2522 const MemRegion *ReferenceRegion = nullptr;
2525 ProgramStateRef State = N->getState();
2526 if (!State->get<RegionState>(Sym))
2529 // Find the most recent expression bound to the symbol in the current
2531 if (!ReferenceRegion) {
2532 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2533 SVal Val = State->getSVal(MR);
2534 if (Val.getAsLocSymbol() == Sym) {
2535 const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
2536 // Do not show local variables belonging to a function other than
2537 // where the error is reported.
2538 if (!VR || (VR->getStackFrame() == LeakContext->getStackFrame()))
2539 ReferenceRegion = MR;
2544 // Allocation node, is the last node in the current or parent context in
2545 // which the symbol was tracked.
2546 const LocationContext *NContext = N->getLocationContext();
2547 if (NContext == LeakContext ||
2548 NContext->isParentOf(LeakContext))
2550 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2553 return LeakInfo(AllocNode, ReferenceRegion);
2556 void MallocChecker::reportLeak(SymbolRef Sym, ExplodedNode *N,
2557 CheckerContext &C) const {
2559 if (!ChecksEnabled[CK_MallocChecker] &&
2560 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2563 const RefState *RS = C.getState()->get<RegionState>(Sym);
2564 assert(RS && "cannot leak an untracked symbol");
2565 AllocationFamily Family = RS->getAllocationFamily();
2567 if (Family == AF_Alloca)
2570 Optional<MallocChecker::CheckKind>
2571 CheckKind = getCheckIfTracked(Family, true);
2573 if (!CheckKind.hasValue())
2577 if (!BT_Leak[*CheckKind]) {
2578 // Leaks should not be reported if they are post-dominated by a sink:
2579 // (1) Sinks are higher importance bugs.
2580 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2581 // with __noreturn functions such as assert() or exit(). We choose not
2582 // to report leaks on such paths.
2583 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2584 categories::MemoryError,
2585 /*SuppressOnSink=*/true));
2588 // Most bug reports are cached at the location where they occurred.
2589 // With leaks, we want to unique them by the location where they were
2590 // allocated, and only report a single path.
2591 PathDiagnosticLocation LocUsedForUniqueing;
2592 const ExplodedNode *AllocNode = nullptr;
2593 const MemRegion *Region = nullptr;
2594 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2596 const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
2598 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2599 C.getSourceManager(),
2600 AllocNode->getLocationContext());
2602 SmallString<200> buf;
2603 llvm::raw_svector_ostream os(buf);
2604 if (Region && Region->canPrintPretty()) {
2605 os << "Potential leak of memory pointed to by ";
2606 Region->printPretty(os);
2608 os << "Potential memory leak";
2611 auto R = std::make_unique<PathSensitiveBugReport>(
2612 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2613 AllocNode->getLocationContext()->getDecl());
2614 R->markInteresting(Sym);
2615 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym, true));
2616 C.emitReport(std::move(R));
2619 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2620 CheckerContext &C) const
2622 ProgramStateRef state = C.getState();
2623 RegionStateTy OldRS = state->get<RegionState>();
2624 RegionStateTy::Factory &F = state->get_context<RegionState>();
2626 RegionStateTy RS = OldRS;
2627 SmallVector<SymbolRef, 2> Errors;
2628 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2629 if (SymReaper.isDead(I->first)) {
2630 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2631 Errors.push_back(I->first);
2632 // Remove the dead symbol from the map.
2633 RS = F.remove(RS, I->first);
2638 // We shouldn't have touched other maps yet.
2639 assert(state->get<ReallocPairs>() ==
2640 C.getState()->get<ReallocPairs>());
2641 assert(state->get<FreeReturnValue>() ==
2642 C.getState()->get<FreeReturnValue>());
2646 // Cleanup the Realloc Pairs Map.
2647 ReallocPairsTy RP = state->get<ReallocPairs>();
2648 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2649 if (SymReaper.isDead(I->first) ||
2650 SymReaper.isDead(I->second.ReallocatedSym)) {
2651 state = state->remove<ReallocPairs>(I->first);
2655 // Cleanup the FreeReturnValue Map.
2656 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2657 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2658 if (SymReaper.isDead(I->first) ||
2659 SymReaper.isDead(I->second)) {
2660 state = state->remove<FreeReturnValue>(I->first);
2664 // Generate leak node.
2665 ExplodedNode *N = C.getPredecessor();
2666 if (!Errors.empty()) {
2667 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2668 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2670 for (SmallVectorImpl<SymbolRef>::iterator
2671 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2672 reportLeak(*I, N, C);
2677 C.addTransition(state->set<RegionState>(RS), N);
2680 void MallocChecker::checkPreCall(const CallEvent &Call,
2681 CheckerContext &C) const {
2683 if (const CXXDestructorCall *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2684 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2685 if (!Sym || checkDoubleDelete(Sym, C))
2689 // We will check for double free in the post visit.
2690 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2691 const FunctionDecl *FD = FC->getDecl();
2695 ASTContext &Ctx = C.getASTContext();
2696 if (ChecksEnabled[CK_MallocChecker] &&
2697 (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_Malloc,
2698 MemoryOperationKind::MOK_Free) ||
2699 MemFunctionInfo.isCMemFunction(FD, Ctx, AF_IfNameIndex,
2700 MemoryOperationKind::MOK_Free)))
2704 // Check if the callee of a method is deleted.
2705 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2706 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2707 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2711 // Check arguments for being used after free.
2712 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2713 SVal ArgSVal = Call.getArgSVal(I);
2714 if (ArgSVal.getAs<Loc>()) {
2715 SymbolRef Sym = ArgSVal.getAsSymbol();
2718 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2724 void MallocChecker::checkPreStmt(const ReturnStmt *S,
2725 CheckerContext &C) const {
2726 checkEscapeOnReturn(S, C);
2729 // In the CFG, automatic destructors come after the return statement.
2730 // This callback checks for returning memory that is freed by automatic
2731 // destructors, as those cannot be reached in checkPreStmt().
2732 void MallocChecker::checkEndFunction(const ReturnStmt *S,
2733 CheckerContext &C) const {
2734 checkEscapeOnReturn(S, C);
2737 void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
2738 CheckerContext &C) const {
2742 const Expr *E = S->getRetValue();
2746 // Check if we are returning a symbol.
2747 ProgramStateRef State = C.getState();
2748 SVal RetVal = C.getSVal(E);
2749 SymbolRef Sym = RetVal.getAsSymbol();
2751 // If we are returning a field of the allocated struct or an array element,
2752 // the callee could still free the memory.
2753 // TODO: This logic should be a part of generic symbol escape callback.
2754 if (const MemRegion *MR = RetVal.getAsRegion())
2755 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2756 if (const SymbolicRegion *BMR =
2757 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2758 Sym = BMR->getSymbol();
2760 // Check if we are returning freed memory.
2762 checkUseAfterFree(Sym, C, E);
2765 // TODO: Blocks should be either inlined or should call invalidate regions
2766 // upon invocation. After that's in place, special casing here will not be
2768 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2769 CheckerContext &C) const {
2771 // Scan the BlockDecRefExprs for any object the retain count checker
2773 if (!BE->getBlockDecl()->hasCaptures())
2776 ProgramStateRef state = C.getState();
2777 const BlockDataRegion *R =
2778 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2780 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2781 E = R->referenced_vars_end();
2786 SmallVector<const MemRegion*, 10> Regions;
2787 const LocationContext *LC = C.getLocationContext();
2788 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2790 for ( ; I != E; ++I) {
2791 const VarRegion *VR = I.getCapturedRegion();
2792 if (VR->getSuperRegion() == R) {
2793 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2795 Regions.push_back(VR);
2799 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
2800 C.addTransition(state);
2803 static bool isReleased(SymbolRef Sym, CheckerContext &C) {
2805 const RefState *RS = C.getState()->get<RegionState>(Sym);
2806 return (RS && RS->isReleased());
2809 bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
2810 const CallExpr *CE, CheckerContext &C) const {
2811 if (CE->getNumArgs() == 0)
2814 StringRef FunctionStr = "";
2815 if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
2816 if (const Stmt *Body = FD->getBody())
2817 if (Body->getBeginLoc().isValid())
2819 Lexer::getSourceText(CharSourceRange::getTokenRange(
2820 {FD->getBeginLoc(), Body->getBeginLoc()}),
2821 C.getSourceManager(), C.getLangOpts());
2823 // We do not model the Integer Set Library's retain-count based allocation.
2824 if (!FunctionStr.contains("__isl_"))
2827 ProgramStateRef State = C.getState();
2829 for (const Expr *Arg : CE->arguments())
2830 if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
2831 if (const RefState *RS = State->get<RegionState>(Sym))
2832 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
2834 C.addTransition(State);
2838 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2839 const Stmt *S) const {
2841 if (isReleased(Sym, C)) {
2842 ReportUseAfterFree(C, S->getSourceRange(), Sym);
2849 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2850 const Stmt *S) const {
2853 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2854 if (RS->isAllocatedOfSizeZero())
2855 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2857 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2858 ReportUseZeroAllocated(C, S->getSourceRange(), Sym);
2862 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2864 if (isReleased(Sym, C)) {
2865 ReportDoubleDelete(C, Sym);
2871 // Check if the location is a freed symbolic region.
2872 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2873 CheckerContext &C) const {
2874 SymbolRef Sym = l.getLocSymbolInBase();
2876 checkUseAfterFree(Sym, C, S);
2877 checkUseZeroAllocated(Sym, C, S);
2881 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2882 // it - assuming that allocation failed on this path.
2883 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2885 bool Assumption) const {
2886 RegionStateTy RS = state->get<RegionState>();
2887 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2888 // If the symbol is assumed to be NULL, remove it from consideration.
2889 ConstraintManager &CMgr = state->getConstraintManager();
2890 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2891 if (AllocFailed.isConstrainedTrue())
2892 state = state->remove<RegionState>(I.getKey());
2895 // Realloc returns 0 when reallocation fails, which means that we should
2896 // restore the state of the pointer being reallocated.
2897 ReallocPairsTy RP = state->get<ReallocPairs>();
2898 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2899 // If the symbol is assumed to be NULL, remove it from consideration.
2900 ConstraintManager &CMgr = state->getConstraintManager();
2901 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2902 if (!AllocFailed.isConstrainedTrue())
2905 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2906 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2907 if (RS->isReleased()) {
2908 switch (I.getData().Kind) {
2909 case OAR_ToBeFreedAfterFailure:
2910 state = state->set<RegionState>(ReallocSym,
2911 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2913 case OAR_DoNotTrackAfterFailure:
2914 state = state->remove<RegionState>(ReallocSym);
2917 assert(I.getData().Kind == OAR_FreeOnFailure);
2921 state = state->remove<ReallocPairs>(I.getKey());
2927 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2928 const CallEvent *Call,
2929 ProgramStateRef State,
2930 SymbolRef &EscapingSymbol) const {
2932 EscapingSymbol = nullptr;
2934 // For now, assume that any C++ or block call can free memory.
2935 // TODO: If we want to be more optimistic here, we'll need to make sure that
2936 // regions escape to C++ containers. They seem to do that even now, but for
2937 // mysterious reasons.
2938 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2941 // Check Objective-C messages by selector name.
2942 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2943 // If it's not a framework call, or if it takes a callback, assume it
2945 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2948 // If it's a method we know about, handle it explicitly post-call.
2949 // This should happen before the "freeWhenDone" check below.
2950 if (isKnownDeallocObjCMethodName(*Msg))
2953 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2954 // about, we can't be sure that the object will use free() to deallocate the
2955 // memory, so we can't model it explicitly. The best we can do is use it to
2956 // decide whether the pointer escapes.
2957 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
2958 return *FreeWhenDone;
2960 // If the first selector piece ends with "NoCopy", and there is no
2961 // "freeWhenDone" parameter set to zero, we know ownership is being
2962 // transferred. Again, though, we can't be sure that the object will use
2963 // free() to deallocate the memory, so we can't model it explicitly.
2964 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2965 if (FirstSlot.endswith("NoCopy"))
2968 // If the first selector starts with addPointer, insertPointer,
2969 // or replacePointer, assume we are dealing with NSPointerArray or similar.
2970 // This is similar to C++ containers (vector); we still might want to check
2971 // that the pointers get freed by following the container itself.
2972 if (FirstSlot.startswith("addPointer") ||
2973 FirstSlot.startswith("insertPointer") ||
2974 FirstSlot.startswith("replacePointer") ||
2975 FirstSlot.equals("valueWithPointer")) {
2979 // We should escape receiver on call to 'init'. This is especially relevant
2980 // to the receiver, as the corresponding symbol is usually not referenced
2982 if (Msg->getMethodFamily() == OMF_init) {
2983 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2987 // Otherwise, assume that the method does not free memory.
2988 // Most framework methods do not free memory.
2992 // At this point the only thing left to handle is straight function calls.
2993 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2997 ASTContext &ASTC = State->getStateManager().getContext();
2999 // If it's one of the allocation functions we can reason about, we model
3000 // its behavior explicitly.
3001 if (MemFunctionInfo.isMemFunction(FD, ASTC))
3004 // If it's not a system call, assume it frees memory.
3005 if (!Call->isInSystemHeader())
3008 // White list the system functions whose arguments escape.
3009 const IdentifierInfo *II = FD->getIdentifier();
3012 StringRef FName = II->getName();
3014 // White list the 'XXXNoCopy' CoreFoundation functions.
3015 // We specifically check these before
3016 if (FName.endswith("NoCopy")) {
3017 // Look for the deallocator argument. We know that the memory ownership
3018 // is not transferred only if the deallocator argument is
3019 // 'kCFAllocatorNull'.
3020 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
3021 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3022 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3023 StringRef DeallocatorName = DE->getFoundDecl()->getName();
3024 if (DeallocatorName == "kCFAllocatorNull")
3031 // Associating streams with malloced buffers. The pointer can escape if
3032 // 'closefn' is specified (and if that function does free memory),
3033 // but it will not if closefn is not specified.
3034 // Currently, we do not inspect the 'closefn' function (PR12101).
3035 if (FName == "funopen")
3036 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
3039 // Do not warn on pointers passed to 'setbuf' when used with std streams,
3040 // these leaks might be intentional when setting the buffer for stdio.
3041 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
3042 if (FName == "setbuf" || FName =="setbuffer" ||
3043 FName == "setlinebuf" || FName == "setvbuf") {
3044 if (Call->getNumArgs() >= 1) {
3045 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3046 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3047 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3048 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
3053 // A bunch of other functions which either take ownership of a pointer or
3054 // wrap the result up in a struct or object, meaning it can be freed later.
3055 // (See RetainCountChecker.) Not all the parameters here are invalidated,
3056 // but the Malloc checker cannot differentiate between them. The right way
3057 // of doing this would be to implement a pointer escapes callback.
3058 if (FName == "CGBitmapContextCreate" ||
3059 FName == "CGBitmapContextCreateWithData" ||
3060 FName == "CVPixelBufferCreateWithBytes" ||
3061 FName == "CVPixelBufferCreateWithPlanarBytes" ||
3062 FName == "OSAtomicEnqueue") {
3066 if (FName == "postEvent" &&
3067 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3071 if (FName == "postEvent" &&
3072 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3076 if (FName == "connectImpl" &&
3077 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
3081 // Handle cases where we know a buffer's /address/ can escape.
3082 // Note that the above checks handle some special cases where we know that
3083 // even though the address escapes, it's still our responsibility to free the
3085 if (Call->argumentsMayEscape())
3088 // Otherwise, assume that the function does not free memory.
3089 // Most system calls do not free the memory.
3093 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
3094 const InvalidatedSymbols &Escaped,
3095 const CallEvent *Call,
3096 PointerEscapeKind Kind) const {
3097 return checkPointerEscapeAux(State, Escaped, Call, Kind,
3098 /*IsConstPointerEscape*/ false);
3101 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
3102 const InvalidatedSymbols &Escaped,
3103 const CallEvent *Call,
3104 PointerEscapeKind Kind) const {
3105 // If a const pointer escapes, it may not be freed(), but it could be deleted.
3106 return checkPointerEscapeAux(State, Escaped, Call, Kind,
3107 /*IsConstPointerEscape*/ true);
3110 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
3111 return (RS->getAllocationFamily() == AF_CXXNewArray ||
3112 RS->getAllocationFamily() == AF_CXXNew);
3115 ProgramStateRef MallocChecker::checkPointerEscapeAux(
3116 ProgramStateRef State, const InvalidatedSymbols &Escaped,
3117 const CallEvent *Call, PointerEscapeKind Kind,
3118 bool IsConstPointerEscape) const {
3119 // If we know that the call does not free memory, or we want to process the
3120 // call later, keep tracking the top level arguments.
3121 SymbolRef EscapingSymbol = nullptr;
3122 if (Kind == PSK_DirectEscapeOnCall &&
3123 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
3129 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
3134 if (EscapingSymbol && EscapingSymbol != sym)
3137 if (const RefState *RS = State->get<RegionState>(sym))
3138 if (RS->isAllocated() || RS->isAllocatedOfSizeZero())
3139 if (!IsConstPointerEscape || checkIfNewOrNewArrayFamily(RS))
3140 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3145 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
3146 ProgramStateRef prevState) {
3147 ReallocPairsTy currMap = currState->get<ReallocPairs>();
3148 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3150 for (const ReallocPairsTy::value_type &Pair : prevMap) {
3151 SymbolRef sym = Pair.first;
3152 if (!currMap.lookup(sym))
3159 static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
3160 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
3161 StringRef N = II->getName();
3162 if (N.contains_lower("ptr") || N.contains_lower("pointer")) {
3163 if (N.contains_lower("ref") || N.contains_lower("cnt") ||
3164 N.contains_lower("intrusive") || N.contains_lower("shared")) {
3172 PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N,
3173 BugReporterContext &BRC,
3174 PathSensitiveBugReport &BR) {
3175 ProgramStateRef state = N->getState();
3176 ProgramStateRef statePrev = N->getFirstPred()->getState();
3178 const RefState *RSCurr = state->get<RegionState>(Sym);
3179 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3181 const Stmt *S = N->getStmtForDiagnostics();
3182 // When dealing with containers, we sometimes want to give a note
3183 // even if the statement is missing.
3184 if (!S && (!RSCurr || RSCurr->getAllocationFamily() != AF_InnerBuffer))
3187 const LocationContext *CurrentLC = N->getLocationContext();
3189 // If we find an atomic fetch_add or fetch_sub within the destructor in which
3190 // the pointer was released (before the release), this is likely a destructor
3191 // of a shared pointer.
3192 // Because we don't model atomics, and also because we don't know that the
3193 // original reference count is positive, we should not report use-after-frees
3194 // on objects deleted in such destructors. This can probably be improved
3195 // through better shared pointer modeling.
3196 if (ReleaseDestructorLC) {
3197 if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
3198 AtomicExpr::AtomicOp Op = AE->getOp();
3199 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
3200 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
3201 if (ReleaseDestructorLC == CurrentLC ||
3202 ReleaseDestructorLC->isParentOf(CurrentLC)) {
3203 BR.markInvalid(getTag(), S);
3209 // FIXME: We will eventually need to handle non-statement-based events
3210 // (__attribute__((cleanup))).
3212 // Find out if this is an interesting point and what is the kind.
3214 std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr;
3215 SmallString<256> Buf;
3216 llvm::raw_svector_ostream OS(Buf);
3218 if (Mode == Normal) {
3219 if (isAllocated(RSCurr, RSPrev, S)) {
3220 Msg = "Memory is allocated";
3221 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3222 Sym, "Returned allocated memory");
3223 } else if (isReleased(RSCurr, RSPrev, S)) {
3224 const auto Family = RSCurr->getAllocationFamily();
3229 case AF_CXXNewArray:
3230 case AF_IfNameIndex:
3231 Msg = "Memory is released";
3232 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3233 Sym, "Returning; memory was released");
3235 case AF_InnerBuffer: {
3236 const MemRegion *ObjRegion =
3237 allocation_state::getContainerObjRegion(statePrev, Sym);
3238 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
3239 QualType ObjTy = TypedRegion->getValueType();
3240 OS << "Inner buffer of '" << ObjTy.getAsString() << "' ";
3242 if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
3243 OS << "deallocated by call to destructor";
3244 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3245 Sym, "Returning; inner buffer was deallocated");
3247 OS << "reallocated by call to '";
3248 const Stmt *S = RSCurr->getStmt();
3249 if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
3250 OS << MemCallE->getMethodDecl()->getNameAsString();
3251 } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
3252 OS << OpCallE->getDirectCallee()->getNameAsString();
3253 } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
3254 auto &CEMgr = BRC.getStateManager().getCallEventManager();
3255 CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
3256 const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl());
3257 OS << (D ? D->getNameAsString() : "unknown");
3260 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3261 Sym, "Returning; inner buffer was reallocated");
3267 llvm_unreachable("Unhandled allocation family!");
3270 // See if we're releasing memory while inlining a destructor
3271 // (or one of its callees). This turns on various common
3272 // false positive suppressions.
3273 bool FoundAnyDestructor = false;
3274 for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
3275 if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3276 if (isReferenceCountingPointerDestructor(DD)) {
3277 // This immediately looks like a reference-counting destructor.
3278 // We're bad at guessing the original reference count of the object,
3279 // so suppress the report for now.
3280 BR.markInvalid(getTag(), DD);
3281 } else if (!FoundAnyDestructor) {
3282 assert(!ReleaseDestructorLC &&
3283 "There can be only one release point!");
3284 // Suspect that it's a reference counting pointer destructor.
3285 // On one of the next nodes might find out that it has atomic
3286 // reference counting operations within it (see the code above),
3287 // and if so, we'd conclude that it likely is a reference counting
3288 // pointer destructor.
3289 ReleaseDestructorLC = LC->getStackFrame();
3290 // It is unlikely that releasing memory is delegated to a destructor
3291 // inside a destructor of a shared pointer, because it's fairly hard
3292 // to pass the information that the pointer indeed needs to be
3293 // released into it. So we're only interested in the innermost
3295 FoundAnyDestructor = true;
3299 } else if (isRelinquished(RSCurr, RSPrev, S)) {
3300 Msg = "Memory ownership is transferred";
3301 StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, "");
3302 } else if (hasReallocFailed(RSCurr, RSPrev, S)) {
3303 Mode = ReallocationFailed;
3304 Msg = "Reallocation failed";
3305 StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
3306 Sym, "Reallocation failed");
3308 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3309 // Is it possible to fail two reallocs WITHOUT testing in between?
3310 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3311 "We only support one failed realloc at a time.");
3312 BR.markInteresting(sym);
3313 FailedReallocSymbol = sym;
3317 // We are in a special mode if a reallocation failed later in the path.
3318 } else if (Mode == ReallocationFailed) {
3319 assert(FailedReallocSymbol && "No symbol to look for.");
3321 // Is this is the first appearance of the reallocated symbol?
3322 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3323 // We're at the reallocation point.
3324 Msg = "Attempt to reallocate memory";
3325 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3326 Sym, "Returned reallocated memory");
3327 FailedReallocSymbol = nullptr;
3339 // Generate the extra diagnostic.
3340 PathDiagnosticLocation Pos;
3342 assert(RSCurr->getAllocationFamily() == AF_InnerBuffer);
3343 auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3346 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3347 BRC.getSourceManager());
3349 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3350 N->getLocationContext());
3353 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
3354 BR.addCallStackHint(P, std::move(StackHint));
3358 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3359 const char *NL, const char *Sep) const {
3361 RegionStateTy RS = State->get<RegionState>();
3363 if (!RS.isEmpty()) {
3364 Out << Sep << "MallocChecker :" << NL;
3365 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3366 const RefState *RefS = State->get<RegionState>(I.getKey());
3367 AllocationFamily Family = RefS->getAllocationFamily();
3368 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
3369 if (!CheckKind.hasValue())
3370 CheckKind = getCheckIfTracked(Family, true);
3372 I.getKey()->dumpToStream(Out);
3374 I.getData().dump(Out);
3375 if (CheckKind.hasValue())
3376 Out << " (" << CheckNames[*CheckKind].getName() << ")";
3384 namespace allocation_state {
3387 markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3388 AllocationFamily Family = AF_InnerBuffer;
3389 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3392 } // end namespace allocation_state
3393 } // end namespace ento
3394 } // end namespace clang
3396 // Intended to be used in InnerPointerChecker to register the part of
3397 // MallocChecker connected to it.
3398 void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) {
3399 MallocChecker *checker = mgr.getChecker<MallocChecker>();
3400 checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3401 checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3402 mgr.getCurrentCheckerName();
3405 void ento::registerDynamicMemoryModeling(CheckerManager &mgr) {
3406 auto *checker = mgr.registerChecker<MallocChecker>();
3407 checker->MemFunctionInfo.ShouldIncludeOwnershipAnnotatedFunctions =
3408 mgr.getAnalyzerOptions().getCheckerBooleanOption(checker, "Optimistic");
3411 bool ento::shouldRegisterDynamicMemoryModeling(const LangOptions &LO) {
3415 #define REGISTER_CHECKER(name) \
3416 void ento::register##name(CheckerManager &mgr) { \
3417 MallocChecker *checker = mgr.getChecker<MallocChecker>(); \
3418 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
3419 checker->CheckNames[MallocChecker::CK_##name] = \
3420 mgr.getCurrentCheckerName(); \
3423 bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
3425 REGISTER_CHECKER(MallocChecker)
3426 REGISTER_CHECKER(NewDeleteChecker)
3427 REGISTER_CHECKER(NewDeleteLeaksChecker)
3428 REGISTER_CHECKER(MismatchedDeallocatorChecker)