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 "AllocationState.h"
48 #include "InterCheckerAPI.h"
49 #include "clang/AST/Attr.h"
50 #include "clang/AST/DeclCXX.h"
51 #include "clang/AST/Expr.h"
52 #include "clang/AST/ExprCXX.h"
53 #include "clang/AST/ParentMap.h"
54 #include "clang/Basic/LLVM.h"
55 #include "clang/Basic/SourceManager.h"
56 #include "clang/Basic/TargetInfo.h"
57 #include "clang/Lex/Lexer.h"
58 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
59 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
60 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
61 #include "clang/StaticAnalyzer/Core/Checker.h"
62 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
63 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
64 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
65 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
66 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicSize.h"
67 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
68 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
69 #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState_Fwd.h"
70 #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
71 #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallString.h"
74 #include "llvm/ADT/StringExtras.h"
75 #include "llvm/Support/Compiler.h"
76 #include "llvm/Support/ErrorHandling.h"
81 using namespace clang;
83 using namespace std::placeholders;
85 //===----------------------------------------------------------------------===//
86 // The types of allocation we're modeling. This is used to check whether a
87 // dynamically allocated object is deallocated with the correct function, like
88 // not using operator delete on an object created by malloc(), or alloca regions
89 // aren't ever deallocated manually.
90 //===----------------------------------------------------------------------===//
94 // Used to check correspondence between allocators and deallocators.
95 enum AllocationFamily {
105 } // end of anonymous namespace
107 /// Print names of allocators and deallocators.
109 /// \returns true on success.
110 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E);
112 /// Print expected name of an allocator based on the deallocator's family
113 /// derived from the DeallocExpr.
114 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family);
116 /// Print expected name of a deallocator based on the allocator's
118 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family);
120 //===----------------------------------------------------------------------===//
121 // The state of a symbol, in terms of memory management.
122 //===----------------------------------------------------------------------===//
128 // Reference to allocated memory.
130 // Reference to zero-allocated memory.
132 // Reference to released/freed memory.
134 // The responsibility for freeing resources has transferred from
135 // this reference. A relinquished symbol should not be freed.
137 // We are no longer guaranteed to have observed all manipulations
138 // of this pointer/memory. For example, it could have been
139 // passed as a parameter to an opaque function.
146 AllocationFamily Family;
148 RefState(Kind k, const Stmt *s, AllocationFamily family)
149 : S(s), K(k), Family(family) {
150 assert(family != AF_None);
154 bool isAllocated() const { return K == Allocated; }
155 bool isAllocatedOfSizeZero() const { return K == AllocatedOfSizeZero; }
156 bool isReleased() const { return K == Released; }
157 bool isRelinquished() const { return K == Relinquished; }
158 bool isEscaped() const { return K == Escaped; }
159 AllocationFamily getAllocationFamily() const { return Family; }
160 const Stmt *getStmt() const { return S; }
162 bool operator==(const RefState &X) const {
163 return K == X.K && S == X.S && Family == X.Family;
166 static RefState getAllocated(AllocationFamily family, const Stmt *s) {
167 return RefState(Allocated, s, family);
169 static RefState getAllocatedOfSizeZero(const RefState *RS) {
170 return RefState(AllocatedOfSizeZero, RS->getStmt(),
171 RS->getAllocationFamily());
173 static RefState getReleased(AllocationFamily family, const Stmt *s) {
174 return RefState(Released, s, family);
176 static RefState getRelinquished(AllocationFamily family, const Stmt *s) {
177 return RefState(Relinquished, s, family);
179 static RefState getEscaped(const RefState *RS) {
180 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
183 void Profile(llvm::FoldingSetNodeID &ID) const {
186 ID.AddInteger(Family);
189 LLVM_DUMP_METHOD void dump(raw_ostream &OS) const {
191 #define CASE(ID) case ID: OS << #ID; break;
193 CASE(AllocatedOfSizeZero)
200 LLVM_DUMP_METHOD void dump() const { dump(llvm::errs()); }
203 } // end of anonymous namespace
205 REGISTER_MAP_WITH_PROGRAMSTATE(RegionState, SymbolRef, RefState)
207 /// Check if the memory associated with this symbol was released.
208 static bool isReleased(SymbolRef Sym, CheckerContext &C);
210 /// Update the RefState to reflect the new memory allocation.
211 /// The optional \p RetVal parameter specifies the newly allocated pointer
212 /// value; if unspecified, the value of expression \p E is used.
213 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
214 ProgramStateRef State,
215 AllocationFamily Family,
216 Optional<SVal> RetVal = None);
218 //===----------------------------------------------------------------------===//
219 // The modeling of memory reallocation.
221 // The terminology 'toPtr' and 'fromPtr' will be used:
222 // toPtr = realloc(fromPtr, 20);
223 //===----------------------------------------------------------------------===//
225 REGISTER_SET_WITH_PROGRAMSTATE(ReallocSizeZeroSymbols, SymbolRef)
229 /// The state of 'fromPtr' after reallocation is known to have failed.
230 enum OwnershipAfterReallocKind {
231 // The symbol needs to be freed (e.g.: realloc)
232 OAR_ToBeFreedAfterFailure,
233 // The symbol has been freed (e.g.: reallocf)
235 // The symbol doesn't have to freed (e.g.: we aren't sure if, how and where
236 // 'fromPtr' was allocated:
237 // void Haha(int *ptr) {
238 // ptr = realloc(ptr, 67);
242 OAR_DoNotTrackAfterFailure
245 /// Stores information about the 'fromPtr' symbol after reallocation.
247 /// This is important because realloc may fail, and that needs special modeling.
248 /// Whether reallocation failed or not will not be known until later, so we'll
249 /// store whether upon failure 'fromPtr' will be freed, or needs to be freed
254 SymbolRef ReallocatedSym;
255 OwnershipAfterReallocKind Kind;
257 ReallocPair(SymbolRef S, OwnershipAfterReallocKind K)
258 : ReallocatedSym(S), Kind(K) {}
259 void Profile(llvm::FoldingSetNodeID &ID) const {
261 ID.AddPointer(ReallocatedSym);
263 bool operator==(const ReallocPair &X) const {
264 return ReallocatedSym == X.ReallocatedSym &&
269 } // end of anonymous namespace
271 REGISTER_MAP_WITH_PROGRAMSTATE(ReallocPairs, SymbolRef, ReallocPair)
273 /// Tells if the callee is one of the builtin new/delete operators, including
274 /// placement operators and other standard overloads.
275 static bool isStandardNewDelete(const FunctionDecl *FD);
276 static bool isStandardNewDelete(const CallEvent &Call) {
277 if (!Call.getDecl() || !isa<FunctionDecl>(Call.getDecl()))
279 return isStandardNewDelete(cast<FunctionDecl>(Call.getDecl()));
282 //===----------------------------------------------------------------------===//
283 // Definition of the MallocChecker class.
284 //===----------------------------------------------------------------------===//
289 : public Checker<check::DeadSymbols, check::PointerEscape,
290 check::ConstPointerEscape, check::PreStmt<ReturnStmt>,
291 check::EndFunction, check::PreCall, check::PostCall,
292 check::NewAllocator, check::PostStmt<BlockExpr>,
293 check::PostObjCMessage, check::Location, eval::Assume> {
295 /// In pessimistic mode, the checker assumes that it does not know which
296 /// functions might free the memory.
297 /// In optimistic mode, the checker assumes that all user-defined functions
298 /// which might free a pointer are annotated.
299 DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
301 /// Many checkers are essentially built into this one, so enabling them will
302 /// make MallocChecker perform additional modeling and reporting.
304 /// When a subchecker is enabled but MallocChecker isn't, model memory
305 /// management but do not emit warnings emitted with MallocChecker only
309 CK_NewDeleteLeaksChecker,
310 CK_MismatchedDeallocatorChecker,
311 CK_InnerPointerChecker,
315 using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
317 DefaultBool ChecksEnabled[CK_NumCheckKinds];
318 CheckerNameRef CheckNames[CK_NumCheckKinds];
320 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
321 void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
322 void checkNewAllocator(const CXXAllocatorCall &Call, CheckerContext &C) const;
323 void checkPostObjCMessage(const ObjCMethodCall &Call, CheckerContext &C) const;
324 void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
325 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
326 void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
327 void checkEndFunction(const ReturnStmt *S, CheckerContext &C) const;
328 ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
329 bool Assumption) const;
330 void checkLocation(SVal l, bool isLoad, const Stmt *S,
331 CheckerContext &C) const;
333 ProgramStateRef checkPointerEscape(ProgramStateRef State,
334 const InvalidatedSymbols &Escaped,
335 const CallEvent *Call,
336 PointerEscapeKind Kind) const;
337 ProgramStateRef checkConstPointerEscape(ProgramStateRef State,
338 const InvalidatedSymbols &Escaped,
339 const CallEvent *Call,
340 PointerEscapeKind Kind) const;
342 void printState(raw_ostream &Out, ProgramStateRef State,
343 const char *NL, const char *Sep) const override;
346 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
347 mutable std::unique_ptr<BugType> BT_DoubleDelete;
348 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
349 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
350 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
351 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
352 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
353 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
354 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
356 #define CHECK_FN(NAME) \
357 void NAME(const CallEvent &Call, CheckerContext &C) const;
360 CHECK_FN(checkIfNameIndex)
361 CHECK_FN(checkBasicAlloc)
362 CHECK_FN(checkKernelMalloc)
363 CHECK_FN(checkCalloc)
364 CHECK_FN(checkAlloca)
365 CHECK_FN(checkStrdup)
366 CHECK_FN(checkIfFreeNameIndex)
367 CHECK_FN(checkCXXNewOrCXXDelete)
368 CHECK_FN(checkGMalloc0)
369 CHECK_FN(checkGMemdup)
370 CHECK_FN(checkGMallocN)
371 CHECK_FN(checkGMallocN0)
372 CHECK_FN(checkReallocN)
373 CHECK_FN(checkOwnershipAttr)
375 void checkRealloc(const CallEvent &Call, CheckerContext &C,
376 bool ShouldFreeOnFail) const;
378 using CheckFn = std::function<void(const MallocChecker *,
379 const CallEvent &Call, CheckerContext &C)>;
381 const CallDescriptionMap<CheckFn> FreeingMemFnMap{
382 {{"free", 1}, &MallocChecker::checkFree},
383 {{"if_freenameindex", 1}, &MallocChecker::checkIfFreeNameIndex},
384 {{"kfree", 1}, &MallocChecker::checkFree},
385 {{"g_free", 1}, &MallocChecker::checkFree},
388 bool isFreeingCall(const CallEvent &Call) const;
390 CallDescriptionMap<CheckFn> AllocatingMemFnMap{
391 {{"alloca", 1}, &MallocChecker::checkAlloca},
392 {{"_alloca", 1}, &MallocChecker::checkAlloca},
393 {{"malloc", 1}, &MallocChecker::checkBasicAlloc},
394 {{"malloc", 3}, &MallocChecker::checkKernelMalloc},
395 {{"calloc", 2}, &MallocChecker::checkCalloc},
396 {{"valloc", 1}, &MallocChecker::checkBasicAlloc},
397 {{CDF_MaybeBuiltin, "strndup", 2}, &MallocChecker::checkStrdup},
398 {{CDF_MaybeBuiltin, "strdup", 1}, &MallocChecker::checkStrdup},
399 {{"_strdup", 1}, &MallocChecker::checkStrdup},
400 {{"kmalloc", 2}, &MallocChecker::checkKernelMalloc},
401 {{"if_nameindex", 1}, &MallocChecker::checkIfNameIndex},
402 {{CDF_MaybeBuiltin, "wcsdup", 1}, &MallocChecker::checkStrdup},
403 {{CDF_MaybeBuiltin, "_wcsdup", 1}, &MallocChecker::checkStrdup},
404 {{"g_malloc", 1}, &MallocChecker::checkBasicAlloc},
405 {{"g_malloc0", 1}, &MallocChecker::checkGMalloc0},
406 {{"g_try_malloc", 1}, &MallocChecker::checkBasicAlloc},
407 {{"g_try_malloc0", 1}, &MallocChecker::checkGMalloc0},
408 {{"g_memdup", 2}, &MallocChecker::checkGMemdup},
409 {{"g_malloc_n", 2}, &MallocChecker::checkGMallocN},
410 {{"g_malloc0_n", 2}, &MallocChecker::checkGMallocN0},
411 {{"g_try_malloc_n", 2}, &MallocChecker::checkGMallocN},
412 {{"g_try_malloc0_n", 2}, &MallocChecker::checkGMallocN0},
415 CallDescriptionMap<CheckFn> ReallocatingMemFnMap{
417 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
419 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, true)},
421 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
422 {{"g_try_realloc", 2},
423 std::bind(&MallocChecker::checkRealloc, _1, _2, _3, false)},
424 {{"g_realloc_n", 3}, &MallocChecker::checkReallocN},
425 {{"g_try_realloc_n", 3}, &MallocChecker::checkReallocN},
428 bool isMemCall(const CallEvent &Call) const;
430 // TODO: Remove mutable by moving the initializtaion to the registry function.
431 mutable Optional<uint64_t> KernelZeroFlagVal;
433 using KernelZeroSizePtrValueTy = Optional<int>;
434 /// Store the value of macro called `ZERO_SIZE_PTR`.
435 /// The value is initialized at first use, before first use the outer
436 /// Optional is empty, afterwards it contains another Optional that indicates
437 /// if the macro value could be determined, and if yes the value itself.
438 mutable Optional<KernelZeroSizePtrValueTy> KernelZeroSizePtrValue;
440 /// Process C++ operator new()'s allocation, which is the part of C++
441 /// new-expression that goes before the constructor.
443 ProgramStateRef processNewAllocation(const CXXAllocatorCall &Call,
445 AllocationFamily Family) const;
447 /// Perform a zero-allocation check.
449 /// \param [in] Call The expression that allocates memory.
450 /// \param [in] IndexOfSizeArg Index of the argument that specifies the size
451 /// of the memory that needs to be allocated. E.g. for malloc, this would be
453 /// \param [in] RetVal Specifies the newly allocated pointer value;
454 /// if unspecified, the value of expression \p E is used.
456 static ProgramStateRef ProcessZeroAllocCheck(const CallEvent &Call,
457 const unsigned IndexOfSizeArg,
458 ProgramStateRef State,
459 Optional<SVal> RetVal = None);
461 /// Model functions with the ownership_returns attribute.
463 /// User-defined function may have the ownership_returns attribute, which
464 /// annotates that the function returns with an object that was allocated on
465 /// the heap, and passes the ownertship to the callee.
467 /// void __attribute((ownership_returns(malloc, 1))) *my_malloc(size_t);
469 /// It has two parameters:
470 /// - first: name of the resource (e.g. 'malloc')
471 /// - (OPTIONAL) second: size of the allocated region
473 /// \param [in] Call The expression that allocates memory.
474 /// \param [in] Att The ownership_returns attribute.
475 /// \param [in] State The \c ProgramState right before allocation.
476 /// \returns The ProgramState right after allocation.
478 ProgramStateRef MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
479 const OwnershipAttr *Att,
480 ProgramStateRef State) const;
482 /// Models memory allocation.
484 /// \param [in] Call The expression that allocates memory.
485 /// \param [in] SizeEx Size of the memory that needs to be allocated.
486 /// \param [in] Init The value the allocated memory needs to be initialized.
487 /// with. For example, \c calloc initializes the allocated memory to 0,
488 /// malloc leaves it undefined.
489 /// \param [in] State The \c ProgramState right before allocation.
490 /// \returns The ProgramState right after allocation.
492 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallEvent &Call,
493 const Expr *SizeEx, SVal Init,
494 ProgramStateRef State,
495 AllocationFamily Family);
497 /// Models memory allocation.
499 /// \param [in] Call The expression that allocates memory.
500 /// \param [in] Size Size of the memory that needs to be allocated.
501 /// \param [in] Init The value the allocated memory needs to be initialized.
502 /// with. For example, \c calloc initializes the allocated memory to 0,
503 /// malloc leaves it undefined.
504 /// \param [in] State The \c ProgramState right before allocation.
505 /// \returns The ProgramState right after allocation.
507 static ProgramStateRef MallocMemAux(CheckerContext &C, const CallEvent &Call,
508 SVal Size, SVal Init,
509 ProgramStateRef State,
510 AllocationFamily Family);
513 static ProgramStateRef addExtentSize(CheckerContext &C, const CXXNewExpr *NE,
514 ProgramStateRef State, SVal Target);
516 // Check if this malloc() for special flags. At present that means M_ZERO or
517 // __GFP_ZERO (in which case, treat it like calloc).
519 llvm::Optional<ProgramStateRef>
520 performKernelMalloc(const CallEvent &Call, CheckerContext &C,
521 const ProgramStateRef &State) const;
523 /// Model functions with the ownership_takes and ownership_holds attributes.
525 /// User-defined function may have the ownership_takes and/or ownership_holds
526 /// attributes, which annotates that the function frees the memory passed as a
529 /// void __attribute((ownership_takes(malloc, 1))) my_free(void *);
530 /// void __attribute((ownership_holds(malloc, 1))) my_hold(void *);
532 /// They have two parameters:
533 /// - first: name of the resource (e.g. 'malloc')
534 /// - second: index of the parameter the attribute applies to
536 /// \param [in] Call The expression that frees memory.
537 /// \param [in] Att The ownership_takes or ownership_holds attribute.
538 /// \param [in] State The \c ProgramState right before allocation.
539 /// \returns The ProgramState right after deallocation.
541 ProgramStateRef FreeMemAttr(CheckerContext &C, const CallEvent &Call,
542 const OwnershipAttr *Att,
543 ProgramStateRef State) const;
545 /// Models memory deallocation.
547 /// \param [in] Call The expression that frees memory.
548 /// \param [in] State The \c ProgramState right before allocation.
549 /// \param [in] Num Index of the argument that needs to be freed. This is
550 /// normally 0, but for custom free functions it may be different.
551 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
553 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
554 /// to have been allocated, or in other words, the symbol to be freed was
555 /// registered as allocated by this checker. In the following case, \c ptr
556 /// isn't known to be allocated.
557 /// void Haha(int *ptr) {
558 /// ptr = realloc(ptr, 67);
561 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
562 /// we're modeling returns with Null on failure.
563 /// \returns The ProgramState right after deallocation.
565 ProgramStateRef FreeMemAux(CheckerContext &C, const CallEvent &Call,
566 ProgramStateRef State, unsigned Num, bool Hold,
567 bool &IsKnownToBeAllocated,
568 AllocationFamily Family,
569 bool ReturnsNullOnFailure = false) const;
571 /// Models memory deallocation.
573 /// \param [in] ArgExpr The variable who's pointee needs to be freed.
574 /// \param [in] Call The expression that frees the memory.
575 /// \param [in] State The \c ProgramState right before allocation.
576 /// normally 0, but for custom free functions it may be different.
577 /// \param [in] Hold Whether the parameter at \p Index has the ownership_holds
579 /// \param [out] IsKnownToBeAllocated Whether the memory to be freed is known
580 /// to have been allocated, or in other words, the symbol to be freed was
581 /// registered as allocated by this checker. In the following case, \c ptr
582 /// isn't known to be allocated.
583 /// void Haha(int *ptr) {
584 /// ptr = realloc(ptr, 67);
587 /// \param [in] ReturnsNullOnFailure Whether the memory deallocation function
588 /// we're modeling returns with Null on failure.
589 /// \returns The ProgramState right after deallocation.
591 ProgramStateRef FreeMemAux(CheckerContext &C, const Expr *ArgExpr,
592 const CallEvent &Call, ProgramStateRef State,
593 bool Hold, bool &IsKnownToBeAllocated,
594 AllocationFamily Family,
595 bool ReturnsNullOnFailure = false) const;
597 // TODO: Needs some refactoring, as all other deallocation modeling
598 // functions are suffering from out parameters and messy code due to how
599 // realloc is handled.
601 /// Models memory reallocation.
603 /// \param [in] Call The expression that reallocated memory
604 /// \param [in] ShouldFreeOnFail Whether if reallocation fails, the supplied
605 /// memory should be freed.
606 /// \param [in] State The \c ProgramState right before reallocation.
607 /// \param [in] SuffixWithN Whether the reallocation function we're modeling
608 /// has an '_n' suffix, such as g_realloc_n.
609 /// \returns The ProgramState right after reallocation.
611 ProgramStateRef ReallocMemAux(CheckerContext &C, const CallEvent &Call,
612 bool ShouldFreeOnFail, ProgramStateRef State,
613 AllocationFamily Family,
614 bool SuffixWithN = false) const;
616 /// Evaluates the buffer size that needs to be allocated.
618 /// \param [in] Blocks The amount of blocks that needs to be allocated.
619 /// \param [in] BlockBytes The size of a block.
620 /// \returns The symbolic value of \p Blocks * \p BlockBytes.
622 static SVal evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
623 const Expr *BlockBytes);
625 /// Models zero initialized array allocation.
627 /// \param [in] Call The expression that reallocated memory
628 /// \param [in] State The \c ProgramState right before reallocation.
629 /// \returns The ProgramState right after allocation.
631 static ProgramStateRef CallocMem(CheckerContext &C, const CallEvent &Call,
632 ProgramStateRef State);
634 /// See if deallocation happens in a suspicious context. If so, escape the
635 /// pointers that otherwise would have been deallocated and return true.
636 bool suppressDeallocationsInSuspiciousContexts(const CallEvent &Call,
637 CheckerContext &C) const;
639 /// If in \p S \p Sym is used, check whether \p Sym was already freed.
640 bool checkUseAfterFree(SymbolRef Sym, CheckerContext &C, const Stmt *S) const;
642 /// If in \p S \p Sym is used, check whether \p Sym was allocated as a zero
643 /// sized memory region.
644 void checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
645 const Stmt *S) const;
647 /// If in \p S \p Sym is being freed, check whether \p Sym was already freed.
648 bool checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const;
650 /// Check if the function is known to free memory, or if it is
651 /// "interesting" and should be modeled explicitly.
653 /// \param [out] EscapingSymbol A function might not free memory in general,
654 /// but could be known to free a particular symbol. In this case, false is
655 /// returned and the single escaping symbol is returned through the out
658 /// We assume that pointers do not escape through calls to system functions
659 /// not handled by this checker.
660 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(const CallEvent *Call,
661 ProgramStateRef State,
662 SymbolRef &EscapingSymbol) const;
664 /// Implementation of the checkPointerEscape callbacks.
666 ProgramStateRef checkPointerEscapeAux(ProgramStateRef State,
667 const InvalidatedSymbols &Escaped,
668 const CallEvent *Call,
669 PointerEscapeKind Kind,
670 bool IsConstPointerEscape) const;
672 // Implementation of the checkPreStmt and checkEndFunction callbacks.
673 void checkEscapeOnReturn(const ReturnStmt *S, CheckerContext &C) const;
676 /// Tells if a given family/call/symbol is tracked by the current checker.
677 /// Sets CheckKind to the kind of the checker responsible for this
678 /// family/call/symbol.
679 Optional<CheckKind> getCheckIfTracked(AllocationFamily Family,
680 bool IsALeakCheck = false) const;
682 Optional<CheckKind> getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
683 bool IsALeakCheck = false) const;
685 static bool SummarizeValue(raw_ostream &os, SVal V);
686 static bool SummarizeRegion(raw_ostream &os, const MemRegion *MR);
688 void HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal, SourceRange Range,
689 const Expr *DeallocExpr,
690 AllocationFamily Family) const;
692 void HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
693 SourceRange Range) const;
695 void HandleMismatchedDealloc(CheckerContext &C, SourceRange Range,
696 const Expr *DeallocExpr, const RefState *RS,
697 SymbolRef Sym, bool OwnershipTransferred) const;
699 void HandleOffsetFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
700 const Expr *DeallocExpr, AllocationFamily Family,
701 const Expr *AllocExpr = nullptr) const;
703 void HandleUseAfterFree(CheckerContext &C, SourceRange Range,
704 SymbolRef Sym) const;
706 void HandleDoubleFree(CheckerContext &C, SourceRange Range, bool Released,
707 SymbolRef Sym, SymbolRef PrevSym) const;
709 void HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const;
711 void HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
712 SymbolRef Sym) const;
714 void HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal, SourceRange Range,
715 const Expr *FreeExpr,
716 AllocationFamily Family) const;
718 /// Find the location of the allocation for Sym on the path leading to the
720 static LeakInfo getAllocationSite(const ExplodedNode *N, SymbolRef Sym,
723 void HandleLeak(SymbolRef Sym, ExplodedNode *N, CheckerContext &C) const;
725 /// Test if value in ArgVal equals to value in macro `ZERO_SIZE_PTR`.
726 bool isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
730 //===----------------------------------------------------------------------===//
731 // Definition of MallocBugVisitor.
732 //===----------------------------------------------------------------------===//
734 /// The bug visitor which allows us to print extra diagnostics along the
735 /// BugReport path. For example, showing the allocation site of the leaked
737 class MallocBugVisitor final : public BugReporterVisitor {
739 enum NotificationMode { Normal, ReallocationFailed };
741 // The allocated region symbol tracked by the main analysis.
744 // The mode we are in, i.e. what kind of diagnostics will be emitted.
745 NotificationMode Mode;
747 // A symbol from when the primary region should have been reallocated.
748 SymbolRef FailedReallocSymbol;
750 // A C++ destructor stack frame in which memory was released. Used for
751 // miscellaneous false positive suppression.
752 const StackFrameContext *ReleaseDestructorLC;
757 MallocBugVisitor(SymbolRef S, bool isLeak = false)
758 : Sym(S), Mode(Normal), FailedReallocSymbol(nullptr),
759 ReleaseDestructorLC(nullptr), IsLeak(isLeak) {}
761 static void *getTag() {
766 void Profile(llvm::FoldingSetNodeID &ID) const override {
767 ID.AddPointer(getTag());
771 /// Did not track -> allocated. Other state (released) -> allocated.
772 static inline bool isAllocated(const RefState *RSCurr, const RefState *RSPrev,
774 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
776 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
778 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
781 /// Did not track -> released. Other state (allocated) -> released.
782 /// The statement associated with the release might be missing.
783 static inline bool isReleased(const RefState *RSCurr, const RefState *RSPrev,
786 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
787 assert(!IsReleased ||
788 (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
789 (!Stmt && RSCurr->getAllocationFamily() == AF_InnerBuffer));
793 /// Did not track -> relinquished. Other state (allocated) -> relinquished.
794 static inline bool isRelinquished(const RefState *RSCurr,
795 const RefState *RSPrev, const Stmt *Stmt) {
797 (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
798 isa<ObjCPropertyRefExpr>(Stmt)) &&
799 (RSCurr && RSCurr->isRelinquished()) &&
800 (!RSPrev || !RSPrev->isRelinquished()));
803 /// If the expression is not a call, and the state change is
804 /// released -> allocated, it must be the realloc return value
805 /// check. If we have to handle more cases here, it might be cleaner just
806 /// to track this extra bit in the state itself.
807 static inline bool hasReallocFailed(const RefState *RSCurr,
808 const RefState *RSPrev,
810 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
812 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
814 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
817 PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
818 BugReporterContext &BRC,
819 PathSensitiveBugReport &BR) override;
821 PathDiagnosticPieceRef getEndPath(BugReporterContext &BRC,
822 const ExplodedNode *EndPathNode,
823 PathSensitiveBugReport &BR) override {
827 PathDiagnosticLocation L = BR.getLocation();
828 // Do not add the statement itself as a range in case of leak.
829 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
834 class StackHintGeneratorForReallocationFailed
835 : public StackHintGeneratorForSymbol {
837 StackHintGeneratorForReallocationFailed(SymbolRef S, StringRef M)
838 : StackHintGeneratorForSymbol(S, M) {}
840 std::string getMessageForArg(const Expr *ArgE, unsigned ArgIndex) override {
841 // Printed parameters start at 1, not 0.
844 SmallString<200> buf;
845 llvm::raw_svector_ostream os(buf);
847 os << "Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
848 << " parameter failed";
850 return std::string(os.str());
853 std::string getMessageForReturn(const CallExpr *CallExpr) override {
854 return "Reallocation of returned value failed";
859 } // end anonymous namespace
861 // A map from the freed symbol to the symbol representing the return value of
862 // the free function.
863 REGISTER_MAP_WITH_PROGRAMSTATE(FreeReturnValue, SymbolRef, SymbolRef)
866 class StopTrackingCallback final : public SymbolVisitor {
867 ProgramStateRef state;
870 StopTrackingCallback(ProgramStateRef st) : state(std::move(st)) {}
871 ProgramStateRef getState() const { return state; }
873 bool VisitSymbol(SymbolRef sym) override {
874 state = state->remove<RegionState>(sym);
878 } // end anonymous namespace
880 static bool isStandardNewDelete(const FunctionDecl *FD) {
884 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
885 if (Kind != OO_New && Kind != OO_Array_New && Kind != OO_Delete &&
886 Kind != OO_Array_Delete)
889 // This is standard if and only if it's not defined in a user file.
890 SourceLocation L = FD->getLocation();
891 // If the header for operator delete is not included, it's still defined
892 // in an invalid source location. Check to make sure we don't crash.
893 return !L.isValid() ||
894 FD->getASTContext().getSourceManager().isInSystemHeader(L);
897 //===----------------------------------------------------------------------===//
898 // Methods of MallocChecker and MallocBugVisitor.
899 //===----------------------------------------------------------------------===//
901 bool MallocChecker::isFreeingCall(const CallEvent &Call) const {
902 if (FreeingMemFnMap.lookup(Call) || ReallocatingMemFnMap.lookup(Call))
905 const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl());
906 if (Func && Func->hasAttrs()) {
907 for (const auto *I : Func->specific_attrs<OwnershipAttr>()) {
908 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
909 if (OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds)
916 bool MallocChecker::isMemCall(const CallEvent &Call) const {
917 if (FreeingMemFnMap.lookup(Call) || AllocatingMemFnMap.lookup(Call) ||
918 ReallocatingMemFnMap.lookup(Call))
921 if (!ShouldIncludeOwnershipAnnotatedFunctions)
924 const auto *Func = dyn_cast<FunctionDecl>(Call.getDecl());
925 return Func && Func->hasAttr<OwnershipAttr>();
928 llvm::Optional<ProgramStateRef>
929 MallocChecker::performKernelMalloc(const CallEvent &Call, CheckerContext &C,
930 const ProgramStateRef &State) const {
931 // 3-argument malloc(), as commonly used in {Free,Net,Open}BSD Kernels:
933 // void *malloc(unsigned long size, struct malloc_type *mtp, int flags);
935 // One of the possible flags is M_ZERO, which means 'give me back an
936 // allocation which is already zeroed', like calloc.
938 // 2-argument kmalloc(), as used in the Linux kernel:
940 // void *kmalloc(size_t size, gfp_t flags);
942 // Has the similar flag value __GFP_ZERO.
944 // This logic is largely cloned from O_CREAT in UnixAPIChecker, maybe some
945 // code could be shared.
947 ASTContext &Ctx = C.getASTContext();
948 llvm::Triple::OSType OS = Ctx.getTargetInfo().getTriple().getOS();
950 if (!KernelZeroFlagVal.hasValue()) {
951 if (OS == llvm::Triple::FreeBSD)
952 KernelZeroFlagVal = 0x0100;
953 else if (OS == llvm::Triple::NetBSD)
954 KernelZeroFlagVal = 0x0002;
955 else if (OS == llvm::Triple::OpenBSD)
956 KernelZeroFlagVal = 0x0008;
957 else if (OS == llvm::Triple::Linux)
959 KernelZeroFlagVal = 0x8000;
961 // FIXME: We need a more general way of getting the M_ZERO value.
962 // See also: O_CREAT in UnixAPIChecker.cpp.
964 // Fall back to normal malloc behavior on platforms where we don't
969 // We treat the last argument as the flags argument, and callers fall-back to
970 // normal malloc on a None return. This works for the FreeBSD kernel malloc
971 // as well as Linux kmalloc.
972 if (Call.getNumArgs() < 2)
975 const Expr *FlagsEx = Call.getArgExpr(Call.getNumArgs() - 1);
976 const SVal V = C.getSVal(FlagsEx);
977 if (!V.getAs<NonLoc>()) {
978 // The case where 'V' can be a location can only be due to a bad header,
979 // so in this case bail out.
983 NonLoc Flags = V.castAs<NonLoc>();
984 NonLoc ZeroFlag = C.getSValBuilder()
985 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->getType())
987 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
990 if (MaskedFlagsUC.isUnknownOrUndef())
992 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
994 // Check if maskedFlags is non-zero.
995 ProgramStateRef TrueState, FalseState;
996 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
998 // If M_ZERO is set, treat this like calloc (initialized).
999 if (TrueState && !FalseState) {
1000 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.CharTy);
1001 return MallocMemAux(C, Call, Call.getArgExpr(0), ZeroVal, TrueState,
1008 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C, const Expr *Blocks,
1009 const Expr *BlockBytes) {
1010 SValBuilder &SB = C.getSValBuilder();
1011 SVal BlocksVal = C.getSVal(Blocks);
1012 SVal BlockBytesVal = C.getSVal(BlockBytes);
1013 ProgramStateRef State = C.getState();
1014 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1015 SB.getContext().getSizeType());
1019 void MallocChecker::checkBasicAlloc(const CallEvent &Call,
1020 CheckerContext &C) const {
1021 ProgramStateRef State = C.getState();
1022 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1024 State = ProcessZeroAllocCheck(Call, 0, State);
1025 C.addTransition(State);
1028 void MallocChecker::checkKernelMalloc(const CallEvent &Call,
1029 CheckerContext &C) const {
1030 ProgramStateRef State = C.getState();
1031 llvm::Optional<ProgramStateRef> MaybeState =
1032 performKernelMalloc(Call, C, State);
1033 if (MaybeState.hasValue())
1034 State = MaybeState.getValue();
1036 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1038 C.addTransition(State);
1041 static bool isStandardRealloc(const CallEvent &Call) {
1042 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1044 ASTContext &AC = FD->getASTContext();
1046 if (isa<CXXMethodDecl>(FD))
1049 return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy &&
1050 FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy &&
1051 FD->getParamDecl(1)->getType().getDesugaredType(AC) ==
1055 static bool isGRealloc(const CallEvent &Call) {
1056 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Call.getDecl());
1058 ASTContext &AC = FD->getASTContext();
1060 if (isa<CXXMethodDecl>(FD))
1063 return FD->getDeclaredReturnType().getDesugaredType(AC) == AC.VoidPtrTy &&
1064 FD->getParamDecl(0)->getType().getDesugaredType(AC) == AC.VoidPtrTy &&
1065 FD->getParamDecl(1)->getType().getDesugaredType(AC) ==
1069 void MallocChecker::checkRealloc(const CallEvent &Call, CheckerContext &C,
1070 bool ShouldFreeOnFail) const {
1071 // HACK: CallDescription currently recognizes non-standard realloc functions
1072 // as standard because it doesn't check the type, or wether its a non-method
1073 // function. This should be solved by making CallDescription smarter.
1074 // Mind that this came from a bug report, and all other functions suffer from
1076 // https://bugs.llvm.org/show_bug.cgi?id=46253
1077 if (!isStandardRealloc(Call) && !isGRealloc(Call))
1079 ProgramStateRef State = C.getState();
1080 State = ReallocMemAux(C, Call, ShouldFreeOnFail, State, AF_Malloc);
1081 State = ProcessZeroAllocCheck(Call, 1, State);
1082 C.addTransition(State);
1085 void MallocChecker::checkCalloc(const CallEvent &Call,
1086 CheckerContext &C) const {
1087 ProgramStateRef State = C.getState();
1088 State = CallocMem(C, Call, State);
1089 State = ProcessZeroAllocCheck(Call, 0, State);
1090 State = ProcessZeroAllocCheck(Call, 1, State);
1091 C.addTransition(State);
1094 void MallocChecker::checkFree(const CallEvent &Call, CheckerContext &C) const {
1095 ProgramStateRef State = C.getState();
1096 bool IsKnownToBeAllocatedMemory = false;
1097 if (suppressDeallocationsInSuspiciousContexts(Call, C))
1099 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1101 C.addTransition(State);
1104 void MallocChecker::checkAlloca(const CallEvent &Call,
1105 CheckerContext &C) const {
1106 ProgramStateRef State = C.getState();
1107 State = MallocMemAux(C, Call, Call.getArgExpr(0), UndefinedVal(), State,
1109 State = ProcessZeroAllocCheck(Call, 0, State);
1110 C.addTransition(State);
1113 void MallocChecker::checkStrdup(const CallEvent &Call,
1114 CheckerContext &C) const {
1115 ProgramStateRef State = C.getState();
1116 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1119 State = MallocUpdateRefState(C, CE, State, AF_Malloc);
1121 C.addTransition(State);
1124 void MallocChecker::checkIfNameIndex(const CallEvent &Call,
1125 CheckerContext &C) const {
1126 ProgramStateRef State = C.getState();
1127 // Should we model this differently? We can allocate a fixed number of
1128 // elements with zeros in the last one.
1130 MallocMemAux(C, Call, UnknownVal(), UnknownVal(), State, AF_IfNameIndex);
1132 C.addTransition(State);
1135 void MallocChecker::checkIfFreeNameIndex(const CallEvent &Call,
1136 CheckerContext &C) const {
1137 ProgramStateRef State = C.getState();
1138 bool IsKnownToBeAllocatedMemory = false;
1139 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1141 C.addTransition(State);
1144 void MallocChecker::checkCXXNewOrCXXDelete(const CallEvent &Call,
1145 CheckerContext &C) const {
1146 ProgramStateRef State = C.getState();
1147 bool IsKnownToBeAllocatedMemory = false;
1148 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1152 assert(isStandardNewDelete(Call));
1154 // Process direct calls to operator new/new[]/delete/delete[] functions
1155 // as distinct from new/new[]/delete/delete[] expressions that are
1156 // processed by the checkPostStmt callbacks for CXXNewExpr and
1158 const FunctionDecl *FD = C.getCalleeDecl(CE);
1159 switch (FD->getOverloadedOperator()) {
1162 MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State, AF_CXXNew);
1163 State = ProcessZeroAllocCheck(Call, 0, State);
1166 State = MallocMemAux(C, Call, CE->getArg(0), UndefinedVal(), State,
1168 State = ProcessZeroAllocCheck(Call, 0, State);
1171 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1174 case OO_Array_Delete:
1175 State = FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocatedMemory,
1179 llvm_unreachable("not a new/delete operator");
1182 C.addTransition(State);
1185 void MallocChecker::checkGMalloc0(const CallEvent &Call,
1186 CheckerContext &C) const {
1187 ProgramStateRef State = C.getState();
1188 SValBuilder &svalBuilder = C.getSValBuilder();
1189 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1190 State = MallocMemAux(C, Call, Call.getArgExpr(0), zeroVal, State, AF_Malloc);
1191 State = ProcessZeroAllocCheck(Call, 0, State);
1192 C.addTransition(State);
1195 void MallocChecker::checkGMemdup(const CallEvent &Call,
1196 CheckerContext &C) const {
1197 ProgramStateRef State = C.getState();
1198 State = MallocMemAux(C, Call, Call.getArgExpr(1), UndefinedVal(), State,
1200 State = ProcessZeroAllocCheck(Call, 1, State);
1201 C.addTransition(State);
1204 void MallocChecker::checkGMallocN(const CallEvent &Call,
1205 CheckerContext &C) const {
1206 ProgramStateRef State = C.getState();
1207 SVal Init = UndefinedVal();
1208 SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1209 State = MallocMemAux(C, Call, TotalSize, Init, State, AF_Malloc);
1210 State = ProcessZeroAllocCheck(Call, 0, State);
1211 State = ProcessZeroAllocCheck(Call, 1, State);
1212 C.addTransition(State);
1215 void MallocChecker::checkGMallocN0(const CallEvent &Call,
1216 CheckerContext &C) const {
1217 ProgramStateRef State = C.getState();
1218 SValBuilder &SB = C.getSValBuilder();
1219 SVal Init = SB.makeZeroVal(SB.getContext().CharTy);
1220 SVal TotalSize = evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
1221 State = MallocMemAux(C, Call, TotalSize, Init, State, AF_Malloc);
1222 State = ProcessZeroAllocCheck(Call, 0, State);
1223 State = ProcessZeroAllocCheck(Call, 1, State);
1224 C.addTransition(State);
1227 void MallocChecker::checkReallocN(const CallEvent &Call,
1228 CheckerContext &C) const {
1229 ProgramStateRef State = C.getState();
1230 State = ReallocMemAux(C, Call, /*ShouldFreeOnFail=*/false, State, AF_Malloc,
1231 /*SuffixWithN=*/true);
1232 State = ProcessZeroAllocCheck(Call, 1, State);
1233 State = ProcessZeroAllocCheck(Call, 2, State);
1234 C.addTransition(State);
1237 void MallocChecker::checkOwnershipAttr(const CallEvent &Call,
1238 CheckerContext &C) const {
1239 ProgramStateRef State = C.getState();
1240 const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
1243 const FunctionDecl *FD = C.getCalleeDecl(CE);
1246 if (ShouldIncludeOwnershipAnnotatedFunctions ||
1247 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
1248 // Check all the attributes, if there are any.
1249 // There can be multiple of these attributes.
1251 for (const auto *I : FD->specific_attrs<OwnershipAttr>()) {
1252 switch (I->getOwnKind()) {
1253 case OwnershipAttr::Returns:
1254 State = MallocMemReturnsAttr(C, Call, I, State);
1256 case OwnershipAttr::Takes:
1257 case OwnershipAttr::Holds:
1258 State = FreeMemAttr(C, Call, I, State);
1263 C.addTransition(State);
1266 void MallocChecker::checkPostCall(const CallEvent &Call,
1267 CheckerContext &C) const {
1270 if (!Call.getOriginExpr())
1273 ProgramStateRef State = C.getState();
1275 if (const CheckFn *Callback = FreeingMemFnMap.lookup(Call)) {
1276 (*Callback)(this, Call, C);
1280 if (const CheckFn *Callback = AllocatingMemFnMap.lookup(Call)) {
1281 (*Callback)(this, Call, C);
1285 if (const CheckFn *Callback = ReallocatingMemFnMap.lookup(Call)) {
1286 (*Callback)(this, Call, C);
1290 if (isStandardNewDelete(Call)) {
1291 checkCXXNewOrCXXDelete(Call, C);
1295 checkOwnershipAttr(Call, C);
1298 // Performs a 0-sized allocations check.
1299 ProgramStateRef MallocChecker::ProcessZeroAllocCheck(
1300 const CallEvent &Call, const unsigned IndexOfSizeArg, ProgramStateRef State,
1301 Optional<SVal> RetVal) {
1306 RetVal = Call.getReturnValue();
1308 const Expr *Arg = nullptr;
1310 if (const CallExpr *CE = dyn_cast<CallExpr>(Call.getOriginExpr())) {
1311 Arg = CE->getArg(IndexOfSizeArg);
1312 } else if (const CXXNewExpr *NE =
1313 dyn_cast<CXXNewExpr>(Call.getOriginExpr())) {
1314 if (NE->isArray()) {
1315 Arg = *NE->getArraySize();
1320 llvm_unreachable("not a CallExpr or CXXNewExpr");
1325 State->getSVal(Arg, Call.getLocationContext()).getAs<DefinedSVal>();
1330 // Check if the allocation size is 0.
1331 ProgramStateRef TrueState, FalseState;
1332 SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
1334 SvalBuilder.makeZeroVal(Arg->getType()).castAs<DefinedSVal>();
1336 std::tie(TrueState, FalseState) =
1337 State->assume(SvalBuilder.evalEQ(State, *DefArgVal, Zero));
1339 if (TrueState && !FalseState) {
1340 SymbolRef Sym = RetVal->getAsLocSymbol();
1344 const RefState *RS = State->get<RegionState>(Sym);
1346 if (RS->isAllocated())
1347 return TrueState->set<RegionState>(Sym,
1348 RefState::getAllocatedOfSizeZero(RS));
1352 // Case of zero-size realloc. Historically 'realloc(ptr, 0)' is treated as
1353 // 'free(ptr)' and the returned value from 'realloc(ptr, 0)' is not
1354 // tracked. Add zero-reallocated Sym to the state to catch references
1355 // to zero-allocated memory.
1356 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1360 // Assume the value is non-zero going forward.
1365 static QualType getDeepPointeeType(QualType T) {
1366 QualType Result = T, PointeeType = T->getPointeeType();
1367 while (!PointeeType.isNull()) {
1368 Result = PointeeType;
1369 PointeeType = PointeeType->getPointeeType();
1374 /// \returns true if the constructor invoked by \p NE has an argument of a
1375 /// pointer/reference to a record type.
1376 static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE) {
1378 const CXXConstructExpr *ConstructE = NE->getConstructExpr();
1382 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1385 const CXXConstructorDecl *CtorD = ConstructE->getConstructor();
1387 // Iterate over the constructor parameters.
1388 for (const auto *CtorParam : CtorD->parameters()) {
1390 QualType CtorParamPointeeT = CtorParam->getType()->getPointeeType();
1391 if (CtorParamPointeeT.isNull())
1394 CtorParamPointeeT = getDeepPointeeType(CtorParamPointeeT);
1396 if (CtorParamPointeeT->getAsCXXRecordDecl())
1404 MallocChecker::processNewAllocation(const CXXAllocatorCall &Call,
1406 AllocationFamily Family) const {
1407 if (!isStandardNewDelete(Call))
1410 const CXXNewExpr *NE = Call.getOriginExpr();
1411 const ParentMap &PM = C.getLocationContext()->getParentMap();
1412 ProgramStateRef State = C.getState();
1414 // Non-trivial constructors have a chance to escape 'this', but marking all
1415 // invocations of trivial constructors as escaped would cause too great of
1416 // reduction of true positives, so let's just do that for constructors that
1417 // have an argument of a pointer-to-record type.
1418 if (!PM.isConsumedExpr(NE) && hasNonTrivialConstructorCall(NE))
1421 // The return value from operator new is bound to a specified initialization
1422 // value (if any) and we don't want to loose this value. So we call
1423 // MallocUpdateRefState() instead of MallocMemAux() which breaks the
1424 // existing binding.
1425 SVal Target = Call.getObjectUnderConstruction();
1426 State = MallocUpdateRefState(C, NE, State, Family, Target);
1427 State = addExtentSize(C, NE, State, Target);
1428 State = ProcessZeroAllocCheck(Call, 0, State, Target);
1432 void MallocChecker::checkNewAllocator(const CXXAllocatorCall &Call,
1433 CheckerContext &C) const {
1434 if (!C.wasInlined) {
1435 ProgramStateRef State = processNewAllocation(
1437 (Call.getOriginExpr()->isArray() ? AF_CXXNewArray : AF_CXXNew));
1438 C.addTransition(State);
1442 // Sets the extent value of the MemRegion allocated by
1443 // new expression NE to its size in Bytes.
1445 ProgramStateRef MallocChecker::addExtentSize(CheckerContext &C,
1446 const CXXNewExpr *NE,
1447 ProgramStateRef State,
1451 SValBuilder &svalBuilder = C.getSValBuilder();
1453 const SubRegion *Region;
1454 if (NE->isArray()) {
1455 const Expr *SizeExpr = *NE->getArraySize();
1456 ElementCount = C.getSVal(SizeExpr);
1457 // Store the extent size for the (symbolic)region
1458 // containing the elements.
1459 Region = Target.getAsRegion()
1460 ->castAs<SubRegion>()
1462 ->castAs<SubRegion>();
1464 ElementCount = svalBuilder.makeIntVal(1, true);
1465 Region = Target.getAsRegion()->castAs<SubRegion>();
1468 // Set the region's extent equal to the Size in Bytes.
1469 QualType ElementType = NE->getAllocatedType();
1470 ASTContext &AstContext = C.getASTContext();
1471 CharUnits TypeSize = AstContext.getTypeSizeInChars(ElementType);
1473 if (ElementCount.getAs<NonLoc>()) {
1474 DefinedOrUnknownSVal DynSize = getDynamicSize(State, Region, svalBuilder);
1476 // size in Bytes = ElementCount*TypeSize
1477 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1478 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1479 svalBuilder.makeArrayIndex(TypeSize.getQuantity()),
1480 svalBuilder.getArrayIndexType());
1481 DefinedOrUnknownSVal DynSizeMatchesSize = svalBuilder.evalEQ(
1482 State, DynSize, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1483 State = State->assume(DynSizeMatchesSize, true);
1488 static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call) {
1489 // If the first selector piece is one of the names below, assume that the
1490 // object takes ownership of the memory, promising to eventually deallocate it
1492 // Ex: [NSData dataWithBytesNoCopy:bytes length:10];
1493 // (...unless a 'freeWhenDone' parameter is false, but that's checked later.)
1494 StringRef FirstSlot = Call.getSelector().getNameForSlot(0);
1495 return FirstSlot == "dataWithBytesNoCopy" ||
1496 FirstSlot == "initWithBytesNoCopy" ||
1497 FirstSlot == "initWithCharactersNoCopy";
1500 static Optional<bool> getFreeWhenDoneArg(const ObjCMethodCall &Call) {
1501 Selector S = Call.getSelector();
1503 // FIXME: We should not rely on fully-constrained symbols being folded.
1504 for (unsigned i = 1; i < S.getNumArgs(); ++i)
1505 if (S.getNameForSlot(i).equals("freeWhenDone"))
1506 return !Call.getArgSVal(i).isZeroConstant();
1511 void MallocChecker::checkPostObjCMessage(const ObjCMethodCall &Call,
1512 CheckerContext &C) const {
1516 if (!isKnownDeallocObjCMethodName(Call))
1519 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(Call))
1523 if (Call.hasNonZeroCallbackArg())
1526 bool IsKnownToBeAllocatedMemory;
1527 ProgramStateRef State =
1528 FreeMemAux(C, Call.getArgExpr(0), Call, C.getState(),
1529 /*Hold=*/true, IsKnownToBeAllocatedMemory, AF_Malloc,
1530 /*RetNullOnFailure=*/true);
1532 C.addTransition(State);
1536 MallocChecker::MallocMemReturnsAttr(CheckerContext &C, const CallEvent &Call,
1537 const OwnershipAttr *Att,
1538 ProgramStateRef State) const {
1542 if (Att->getModule()->getName() != "malloc")
1545 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1547 return MallocMemAux(C, Call, Call.getArgExpr(I->getASTIndex()),
1548 UndefinedVal(), State, AF_Malloc);
1550 return MallocMemAux(C, Call, UnknownVal(), UndefinedVal(), State, AF_Malloc);
1553 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1554 const CallEvent &Call,
1555 const Expr *SizeEx, SVal Init,
1556 ProgramStateRef State,
1557 AllocationFamily Family) {
1562 return MallocMemAux(C, Call, C.getSVal(SizeEx), Init, State, Family);
1565 ProgramStateRef MallocChecker::MallocMemAux(CheckerContext &C,
1566 const CallEvent &Call, SVal Size,
1567 SVal Init, ProgramStateRef State,
1568 AllocationFamily Family) {
1572 const Expr *CE = Call.getOriginExpr();
1574 // We expect the malloc functions to return a pointer.
1575 if (!Loc::isLocType(CE->getType()))
1578 // Bind the return value to the symbolic value from the heap region.
1579 // TODO: We could rewrite post visit to eval call; 'malloc' does not have
1580 // side effects other than what we model here.
1581 unsigned Count = C.blockCount();
1582 SValBuilder &svalBuilder = C.getSValBuilder();
1583 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1584 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1585 .castAs<DefinedSVal>();
1586 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1588 // Fill the region with the initialization value.
1589 State = State->bindDefaultInitial(RetVal, Init, LCtx);
1591 // Set the region's extent equal to the Size parameter.
1592 const SymbolicRegion *R =
1593 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1596 if (Optional<DefinedOrUnknownSVal> DefinedSize =
1597 Size.getAs<DefinedOrUnknownSVal>()) {
1598 DefinedOrUnknownSVal DynSize = getDynamicSize(State, R, svalBuilder);
1600 DefinedOrUnknownSVal DynSizeMatchesSize =
1601 svalBuilder.evalEQ(State, DynSize, *DefinedSize);
1603 State = State->assume(DynSizeMatchesSize, true);
1607 return MallocUpdateRefState(C, CE, State, Family);
1610 static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E,
1611 ProgramStateRef State,
1612 AllocationFamily Family,
1613 Optional<SVal> RetVal) {
1617 // Get the return value.
1619 RetVal = C.getSVal(E);
1621 // We expect the malloc functions to return a pointer.
1622 if (!RetVal->getAs<Loc>())
1625 SymbolRef Sym = RetVal->getAsLocSymbol();
1626 // This is a return value of a function that was not inlined, such as malloc()
1627 // or new(). We've checked that in the caller. Therefore, it must be a symbol.
1630 // Set the symbol's state to Allocated.
1631 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1634 ProgramStateRef MallocChecker::FreeMemAttr(CheckerContext &C,
1635 const CallEvent &Call,
1636 const OwnershipAttr *Att,
1637 ProgramStateRef State) const {
1641 if (Att->getModule()->getName() != "malloc")
1644 bool IsKnownToBeAllocated = false;
1646 for (const auto &Arg : Att->args()) {
1647 ProgramStateRef StateI =
1648 FreeMemAux(C, Call, State, Arg.getASTIndex(),
1649 Att->getOwnKind() == OwnershipAttr::Holds,
1650 IsKnownToBeAllocated, AF_Malloc);
1657 ProgramStateRef MallocChecker::FreeMemAux(CheckerContext &C,
1658 const CallEvent &Call,
1659 ProgramStateRef State, unsigned Num,
1660 bool Hold, bool &IsKnownToBeAllocated,
1661 AllocationFamily Family,
1662 bool ReturnsNullOnFailure) const {
1666 if (Call.getNumArgs() < (Num + 1))
1669 return FreeMemAux(C, Call.getArgExpr(Num), Call, State, Hold,
1670 IsKnownToBeAllocated, Family, ReturnsNullOnFailure);
1673 /// Checks if the previous call to free on the given symbol failed - if free
1674 /// failed, returns true. Also, returns the corresponding return value symbol.
1675 static bool didPreviousFreeFail(ProgramStateRef State,
1676 SymbolRef Sym, SymbolRef &RetStatusSymbol) {
1677 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1679 assert(*Ret && "We should not store the null return symbol");
1680 ConstraintManager &CMgr = State->getConstraintManager();
1681 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1682 RetStatusSymbol = *Ret;
1683 return FreeFailed.isConstrainedTrue();
1688 static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E) {
1689 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1690 // FIXME: This doesn't handle indirect calls.
1691 const FunctionDecl *FD = CE->getDirectCallee();
1696 if (!FD->isOverloadedOperator())
1701 if (const ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E)) {
1702 if (Msg->isInstanceMessage())
1706 Msg->getSelector().print(os);
1710 if (const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1712 << getOperatorSpelling(NE->getOperatorNew()->getOverloadedOperator())
1717 if (const CXXDeleteExpr *DE = dyn_cast<CXXDeleteExpr>(E)) {
1719 << getOperatorSpelling(DE->getOperatorDelete()->getOverloadedOperator())
1727 static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family) {
1730 case AF_Malloc: os << "malloc()"; return;
1731 case AF_CXXNew: os << "'new'"; return;
1732 case AF_CXXNewArray: os << "'new[]'"; return;
1733 case AF_IfNameIndex: os << "'if_nameindex()'"; return;
1734 case AF_InnerBuffer: os << "container-specific allocator"; return;
1736 case AF_None: llvm_unreachable("not a deallocation expression");
1740 static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family) {
1742 case AF_Malloc: os << "free()"; return;
1743 case AF_CXXNew: os << "'delete'"; return;
1744 case AF_CXXNewArray: os << "'delete[]'"; return;
1745 case AF_IfNameIndex: os << "'if_freenameindex()'"; return;
1746 case AF_InnerBuffer: os << "container-specific deallocator"; return;
1748 case AF_None: llvm_unreachable("suspicious argument");
1752 ProgramStateRef MallocChecker::FreeMemAux(
1753 CheckerContext &C, const Expr *ArgExpr, const CallEvent &Call,
1754 ProgramStateRef State, bool Hold, bool &IsKnownToBeAllocated,
1755 AllocationFamily Family, 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();
1781 const Expr *ParentExpr = Call.getOriginExpr();
1783 // NOTE: We detected a bug, but the checker under whose name we would emit the
1784 // error could be disabled. Generally speaking, the MallocChecker family is an
1785 // integral part of the Static Analyzer, and disabling any part of it should
1786 // only be done under exceptional circumstances, such as frequent false
1787 // positives. If this is the case, we can reasonably believe that there are
1788 // serious faults in our understanding of the source code, and even if we
1789 // don't emit an warning, we should terminate further analysis with a sink
1792 // Nonlocs can't be freed, of course.
1793 // Non-region locations (labels and fixed addresses) also shouldn't be freed.
1796 // If the macro ZERO_SIZE_PTR is defined, this could be a kernel source
1797 // code. In that case, the ZERO_SIZE_PTR defines a special value used for a
1798 // zero-sized memory block which is allowed to be freed, despite not being a
1800 if (Family != AF_Malloc || !isArgZERO_SIZE_PTR(State, C, ArgVal))
1801 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1806 R = R->StripCasts();
1808 // Blocks might show up as heap data, but should not be free()d
1809 if (isa<BlockDataRegion>(R)) {
1810 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1815 const MemSpaceRegion *MS = R->getMemorySpace();
1817 // Parameters, locals, statics, globals, and memory returned by
1818 // __builtin_alloca() shouldn't be freed.
1819 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1820 // FIXME: at the time this code was written, malloc() regions were
1821 // represented by conjured symbols, which are all in UnknownSpaceRegion.
1822 // This means that there isn't actually anything from HeapSpaceRegion
1823 // that should be freed, even though we allow it here.
1824 // Of course, free() can work on memory allocated outside the current
1825 // function, so UnknownSpaceRegion is always a possibility.
1826 // False negatives are better than false positives.
1828 if (isa<AllocaRegion>(R))
1829 HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1831 HandleNonHeapDealloc(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1837 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1838 // Various cases could lead to non-symbol values here.
1839 // For now, ignore them.
1843 SymbolRef SymBase = SrBase->getSymbol();
1844 const RefState *RsBase = State->get<RegionState>(SymBase);
1845 SymbolRef PreviousRetStatusSymbol = nullptr;
1847 IsKnownToBeAllocated =
1848 RsBase && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero());
1852 // Memory returned by alloca() shouldn't be freed.
1853 if (RsBase->getAllocationFamily() == AF_Alloca) {
1854 HandleFreeAlloca(C, ArgVal, ArgExpr->getSourceRange());
1858 // Check for double free first.
1859 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1860 !didPreviousFreeFail(State, SymBase, PreviousRetStatusSymbol)) {
1861 HandleDoubleFree(C, ParentExpr->getSourceRange(), RsBase->isReleased(),
1862 SymBase, PreviousRetStatusSymbol);
1865 // If the pointer is allocated or escaped, but we are now trying to free it,
1866 // check that the call to free is proper.
1867 } else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1868 RsBase->isEscaped()) {
1870 // Check if an expected deallocation function matches the real one.
1871 bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family;
1872 if (!DeallocMatchesAlloc) {
1873 HandleMismatchedDealloc(C, ArgExpr->getSourceRange(), ParentExpr,
1874 RsBase, SymBase, Hold);
1878 // Check if the memory location being freed is the actual location
1879 // allocated, or an offset.
1880 RegionOffset Offset = R->getAsOffset();
1881 if (Offset.isValid() &&
1882 !Offset.hasSymbolicOffset() &&
1883 Offset.getOffset() != 0) {
1884 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1885 HandleOffsetFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1892 if (SymBase->getType()->isFunctionPointerType()) {
1893 HandleFunctionPtrFree(C, ArgVal, ArgExpr->getSourceRange(), ParentExpr,
1898 // Clean out the info on previous call to free return info.
1899 State = State->remove<FreeReturnValue>(SymBase);
1901 // Keep track of the return value. If it is NULL, we will know that free
1903 if (ReturnsNullOnFailure) {
1904 SVal RetVal = C.getSVal(ParentExpr);
1905 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1906 if (RetStatusSymbol) {
1907 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1908 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1912 // If we don't know anything about this symbol, a free on it may be totally
1913 // valid. If this is the case, lets assume that the allocation family of the
1914 // freeing function is the same as the symbols allocation family, and go with
1916 assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family));
1920 return State->set<RegionState>(SymBase,
1921 RefState::getRelinquished(Family,
1924 return State->set<RegionState>(SymBase,
1925 RefState::getReleased(Family, ParentExpr));
1928 Optional<MallocChecker::CheckKind>
1929 MallocChecker::getCheckIfTracked(AllocationFamily Family,
1930 bool IsALeakCheck) const {
1934 case AF_IfNameIndex: {
1935 if (ChecksEnabled[CK_MallocChecker])
1936 return CK_MallocChecker;
1940 case AF_CXXNewArray: {
1942 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1943 return CK_NewDeleteLeaksChecker;
1946 if (ChecksEnabled[CK_NewDeleteChecker])
1947 return CK_NewDeleteChecker;
1951 case AF_InnerBuffer: {
1952 if (ChecksEnabled[CK_InnerPointerChecker])
1953 return CK_InnerPointerChecker;
1957 llvm_unreachable("no family");
1960 llvm_unreachable("unhandled family");
1963 Optional<MallocChecker::CheckKind>
1964 MallocChecker::getCheckIfTracked(CheckerContext &C, SymbolRef Sym,
1965 bool IsALeakCheck) const {
1966 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1967 return CK_MallocChecker;
1969 const RefState *RS = C.getState()->get<RegionState>(Sym);
1971 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1974 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal V) {
1975 if (Optional<nonloc::ConcreteInt> IntVal = V.getAs<nonloc::ConcreteInt>())
1976 os << "an integer (" << IntVal->getValue() << ")";
1977 else if (Optional<loc::ConcreteInt> ConstAddr = V.getAs<loc::ConcreteInt>())
1978 os << "a constant address (" << ConstAddr->getValue() << ")";
1979 else if (Optional<loc::GotoLabel> Label = V.getAs<loc::GotoLabel>())
1980 os << "the address of the label '" << Label->getLabel()->getName() << "'";
1987 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1988 const MemRegion *MR) {
1989 switch (MR->getKind()) {
1990 case MemRegion::FunctionCodeRegionKind: {
1991 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1993 os << "the address of the function '" << *FD << '\'';
1995 os << "the address of a function";
1998 case MemRegion::BlockCodeRegionKind:
2001 case MemRegion::BlockDataRegionKind:
2002 // FIXME: where the block came from?
2006 const MemSpaceRegion *MS = MR->getMemorySpace();
2008 if (isa<StackLocalsSpaceRegion>(MS)) {
2009 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2017 os << "the address of the local variable '" << VD->getName() << "'";
2019 os << "the address of a local stack variable";
2023 if (isa<StackArgumentsSpaceRegion>(MS)) {
2024 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2032 os << "the address of the parameter '" << VD->getName() << "'";
2034 os << "the address of a parameter";
2038 if (isa<GlobalsSpaceRegion>(MS)) {
2039 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2047 if (VD->isStaticLocal())
2048 os << "the address of the static variable '" << VD->getName() << "'";
2050 os << "the address of the global variable '" << VD->getName() << "'";
2052 os << "the address of a global variable";
2061 void MallocChecker::HandleNonHeapDealloc(CheckerContext &C, SVal ArgVal,
2063 const Expr *DeallocExpr,
2064 AllocationFamily Family) const {
2066 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2071 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2072 if (!CheckKind.hasValue())
2075 if (ExplodedNode *N = C.generateErrorNode()) {
2076 if (!BT_BadFree[*CheckKind])
2077 BT_BadFree[*CheckKind].reset(new BugType(
2078 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2080 SmallString<100> buf;
2081 llvm::raw_svector_ostream os(buf);
2083 const MemRegion *MR = ArgVal.getAsRegion();
2084 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2085 MR = ER->getSuperRegion();
2087 os << "Argument to ";
2088 if (!printMemFnName(os, C, DeallocExpr))
2089 os << "deallocator";
2092 bool Summarized = MR ? SummarizeRegion(os, MR)
2093 : SummarizeValue(os, ArgVal);
2095 os << ", which is not memory allocated by ";
2097 os << "not memory allocated by ";
2099 printExpectedAllocName(os, Family);
2101 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2103 R->markInteresting(MR);
2105 C.emitReport(std::move(R));
2109 void MallocChecker::HandleFreeAlloca(CheckerContext &C, SVal ArgVal,
2110 SourceRange Range) const {
2112 Optional<MallocChecker::CheckKind> CheckKind;
2114 if (ChecksEnabled[CK_MallocChecker])
2115 CheckKind = CK_MallocChecker;
2116 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
2117 CheckKind = CK_MismatchedDeallocatorChecker;
2123 if (ExplodedNode *N = C.generateErrorNode()) {
2124 if (!BT_FreeAlloca[*CheckKind])
2125 BT_FreeAlloca[*CheckKind].reset(new BugType(
2126 CheckNames[*CheckKind], "Free alloca()", categories::MemoryError));
2128 auto R = std::make_unique<PathSensitiveBugReport>(
2129 *BT_FreeAlloca[*CheckKind],
2130 "Memory allocated by alloca() should not be deallocated", N);
2131 R->markInteresting(ArgVal.getAsRegion());
2133 C.emitReport(std::move(R));
2137 void MallocChecker::HandleMismatchedDealloc(CheckerContext &C,
2139 const Expr *DeallocExpr,
2140 const RefState *RS, SymbolRef Sym,
2141 bool OwnershipTransferred) const {
2143 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
2148 if (ExplodedNode *N = C.generateErrorNode()) {
2149 if (!BT_MismatchedDealloc)
2150 BT_MismatchedDealloc.reset(
2151 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
2152 "Bad deallocator", categories::MemoryError));
2154 SmallString<100> buf;
2155 llvm::raw_svector_ostream os(buf);
2157 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2158 SmallString<20> AllocBuf;
2159 llvm::raw_svector_ostream AllocOs(AllocBuf);
2160 SmallString<20> DeallocBuf;
2161 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2163 if (OwnershipTransferred) {
2164 if (printMemFnName(DeallocOs, C, DeallocExpr))
2165 os << DeallocOs.str() << " cannot";
2169 os << " take ownership of memory";
2171 if (printMemFnName(AllocOs, C, AllocExpr))
2172 os << " allocated by " << AllocOs.str();
2175 if (printMemFnName(AllocOs, C, AllocExpr))
2176 os << " allocated by " << AllocOs.str();
2178 os << " should be deallocated by ";
2179 printExpectedDeallocName(os, RS->getAllocationFamily());
2181 if (printMemFnName(DeallocOs, C, DeallocExpr))
2182 os << ", not " << DeallocOs.str();
2185 auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc,
2187 R->markInteresting(Sym);
2189 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2190 C.emitReport(std::move(R));
2194 void MallocChecker::HandleOffsetFree(CheckerContext &C, SVal ArgVal,
2195 SourceRange Range, const Expr *DeallocExpr,
2196 AllocationFamily Family,
2197 const Expr *AllocExpr) const {
2199 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2204 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2205 if (!CheckKind.hasValue())
2208 ExplodedNode *N = C.generateErrorNode();
2212 if (!BT_OffsetFree[*CheckKind])
2213 BT_OffsetFree[*CheckKind].reset(new BugType(
2214 CheckNames[*CheckKind], "Offset free", categories::MemoryError));
2216 SmallString<100> buf;
2217 llvm::raw_svector_ostream os(buf);
2218 SmallString<20> AllocNameBuf;
2219 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2221 const MemRegion *MR = ArgVal.getAsRegion();
2222 assert(MR && "Only MemRegion based symbols can have offset free errors");
2224 RegionOffset Offset = MR->getAsOffset();
2225 assert((Offset.isValid() &&
2226 !Offset.hasSymbolicOffset() &&
2227 Offset.getOffset() != 0) &&
2228 "Only symbols with a valid offset can have offset free errors");
2230 int offsetBytes = Offset.getOffset() / C.getASTContext().getCharWidth();
2232 os << "Argument to ";
2233 if (!printMemFnName(os, C, DeallocExpr))
2234 os << "deallocator";
2235 os << " is offset by "
2238 << ((abs(offsetBytes) > 1) ? "bytes" : "byte")
2239 << " from the start of ";
2240 if (AllocExpr && printMemFnName(AllocNameOs, C, AllocExpr))
2241 os << "memory allocated by " << AllocNameOs.str();
2243 os << "allocated memory";
2245 auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind],
2247 R->markInteresting(MR->getBaseRegion());
2249 C.emitReport(std::move(R));
2252 void MallocChecker::HandleUseAfterFree(CheckerContext &C, SourceRange Range,
2253 SymbolRef Sym) const {
2255 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker] &&
2256 !ChecksEnabled[CK_InnerPointerChecker]) {
2261 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2262 if (!CheckKind.hasValue())
2265 if (ExplodedNode *N = C.generateErrorNode()) {
2266 if (!BT_UseFree[*CheckKind])
2267 BT_UseFree[*CheckKind].reset(new BugType(
2268 CheckNames[*CheckKind], "Use-after-free", categories::MemoryError));
2270 AllocationFamily AF =
2271 C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2273 auto R = std::make_unique<PathSensitiveBugReport>(
2274 *BT_UseFree[*CheckKind],
2275 AF == AF_InnerBuffer
2276 ? "Inner pointer of container used after re/deallocation"
2277 : "Use of memory after it is freed",
2280 R->markInteresting(Sym);
2282 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2284 if (AF == AF_InnerBuffer)
2285 R->addVisitor(allocation_state::getInnerPointerBRVisitor(Sym));
2287 C.emitReport(std::move(R));
2291 void MallocChecker::HandleDoubleFree(CheckerContext &C, SourceRange Range,
2292 bool Released, SymbolRef Sym,
2293 SymbolRef PrevSym) const {
2295 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2300 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2301 if (!CheckKind.hasValue())
2304 if (ExplodedNode *N = C.generateErrorNode()) {
2305 if (!BT_DoubleFree[*CheckKind])
2306 BT_DoubleFree[*CheckKind].reset(new BugType(
2307 CheckNames[*CheckKind], "Double free", categories::MemoryError));
2309 auto R = std::make_unique<PathSensitiveBugReport>(
2310 *BT_DoubleFree[*CheckKind],
2311 (Released ? "Attempt to free released memory"
2312 : "Attempt to free non-owned memory"),
2315 R->markInteresting(Sym);
2317 R->markInteresting(PrevSym);
2318 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2319 C.emitReport(std::move(R));
2323 void MallocChecker::HandleDoubleDelete(CheckerContext &C, SymbolRef Sym) const {
2325 if (!ChecksEnabled[CK_NewDeleteChecker]) {
2330 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2331 if (!CheckKind.hasValue())
2334 if (ExplodedNode *N = C.generateErrorNode()) {
2335 if (!BT_DoubleDelete)
2336 BT_DoubleDelete.reset(new BugType(CheckNames[CK_NewDeleteChecker],
2338 categories::MemoryError));
2340 auto R = std::make_unique<PathSensitiveBugReport>(
2341 *BT_DoubleDelete, "Attempt to delete released memory", N);
2343 R->markInteresting(Sym);
2344 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2345 C.emitReport(std::move(R));
2349 void MallocChecker::HandleUseZeroAlloc(CheckerContext &C, SourceRange Range,
2350 SymbolRef Sym) const {
2352 if (!ChecksEnabled[CK_MallocChecker] && !ChecksEnabled[CK_NewDeleteChecker]) {
2357 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(C, Sym);
2359 if (!CheckKind.hasValue())
2362 if (ExplodedNode *N = C.generateErrorNode()) {
2363 if (!BT_UseZerroAllocated[*CheckKind])
2364 BT_UseZerroAllocated[*CheckKind].reset(
2365 new BugType(CheckNames[*CheckKind], "Use of zero allocated",
2366 categories::MemoryError));
2368 auto R = std::make_unique<PathSensitiveBugReport>(
2369 *BT_UseZerroAllocated[*CheckKind], "Use of zero-allocated memory", N);
2373 R->markInteresting(Sym);
2374 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2376 C.emitReport(std::move(R));
2380 void MallocChecker::HandleFunctionPtrFree(CheckerContext &C, SVal ArgVal,
2382 const Expr *FreeExpr,
2383 AllocationFamily Family) const {
2384 if (!ChecksEnabled[CK_MallocChecker]) {
2389 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
2390 if (!CheckKind.hasValue())
2393 if (ExplodedNode *N = C.generateErrorNode()) {
2394 if (!BT_BadFree[*CheckKind])
2395 BT_BadFree[*CheckKind].reset(new BugType(
2396 CheckNames[*CheckKind], "Bad free", categories::MemoryError));
2398 SmallString<100> Buf;
2399 llvm::raw_svector_ostream Os(Buf);
2401 const MemRegion *MR = ArgVal.getAsRegion();
2402 while (const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2403 MR = ER->getSuperRegion();
2405 Os << "Argument to ";
2406 if (!printMemFnName(Os, C, FreeExpr))
2407 Os << "deallocator";
2409 Os << " is a function pointer";
2411 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2413 R->markInteresting(MR);
2415 C.emitReport(std::move(R));
2420 MallocChecker::ReallocMemAux(CheckerContext &C, const CallEvent &Call,
2421 bool ShouldFreeOnFail, ProgramStateRef State,
2422 AllocationFamily Family, bool SuffixWithN) const {
2426 const CallExpr *CE = cast<CallExpr>(Call.getOriginExpr());
2428 if (SuffixWithN && CE->getNumArgs() < 3)
2430 else if (CE->getNumArgs() < 2)
2433 const Expr *arg0Expr = CE->getArg(0);
2434 SVal Arg0Val = C.getSVal(arg0Expr);
2435 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2437 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2439 SValBuilder &svalBuilder = C.getSValBuilder();
2441 DefinedOrUnknownSVal PtrEQ =
2442 svalBuilder.evalEQ(State, arg0Val, svalBuilder.makeNull());
2444 // Get the size argument.
2445 const Expr *Arg1 = CE->getArg(1);
2447 // Get the value of the size argument.
2448 SVal TotalSize = C.getSVal(Arg1);
2450 TotalSize = evalMulForBufferSize(C, Arg1, CE->getArg(2));
2451 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2454 // Compare the size argument to 0.
2455 DefinedOrUnknownSVal SizeZero =
2456 svalBuilder.evalEQ(State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2457 svalBuilder.makeIntValWithPtrWidth(0, false));
2459 ProgramStateRef StatePtrIsNull, StatePtrNotNull;
2460 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2461 ProgramStateRef StateSizeIsZero, StateSizeNotZero;
2462 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2463 // We only assume exceptional states if they are definitely true; if the
2464 // state is under-constrained, assume regular realloc behavior.
2465 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2466 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2468 // If the ptr is NULL and the size is not 0, the call is equivalent to
2470 if (PrtIsNull && !SizeIsZero) {
2471 ProgramStateRef stateMalloc = MallocMemAux(
2472 C, Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family);
2476 if (PrtIsNull && SizeIsZero)
2481 bool IsKnownToBeAllocated = false;
2483 // If the size is 0, free the memory.
2485 // The semantics of the return value are:
2486 // If size was equal to 0, either NULL or a pointer suitable to be passed
2487 // to free() is returned. We just free the input pointer and do not add
2488 // any constrains on the output pointer.
2489 if (ProgramStateRef stateFree = FreeMemAux(
2490 C, Call, StateSizeIsZero, 0, false, IsKnownToBeAllocated, Family))
2493 // Default behavior.
2494 if (ProgramStateRef stateFree =
2495 FreeMemAux(C, Call, State, 0, false, IsKnownToBeAllocated, Family)) {
2497 ProgramStateRef stateRealloc =
2498 MallocMemAux(C, Call, TotalSize, UnknownVal(), stateFree, Family);
2502 OwnershipAfterReallocKind Kind = OAR_ToBeFreedAfterFailure;
2503 if (ShouldFreeOnFail)
2504 Kind = OAR_FreeOnFailure;
2505 else if (!IsKnownToBeAllocated)
2506 Kind = OAR_DoNotTrackAfterFailure;
2508 // Get the from and to pointer symbols as in toPtr = realloc(fromPtr, size).
2509 SymbolRef FromPtr = arg0Val.getLocSymbolInBase();
2510 SVal RetVal = C.getSVal(CE);
2511 SymbolRef ToPtr = RetVal.getAsSymbol();
2512 assert(FromPtr && ToPtr &&
2513 "By this point, FreeMemAux and MallocMemAux should have checked "
2514 "whether the argument or the return value is symbolic!");
2516 // Record the info about the reallocated symbol so that we could properly
2517 // process failed reallocation.
2518 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2519 ReallocPair(FromPtr, Kind));
2520 // The reallocated symbol should stay alive for as long as the new symbol.
2521 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2522 return stateRealloc;
2527 ProgramStateRef MallocChecker::CallocMem(CheckerContext &C,
2528 const CallEvent &Call,
2529 ProgramStateRef State) {
2533 if (Call.getNumArgs() < 2)
2536 SValBuilder &svalBuilder = C.getSValBuilder();
2537 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2539 evalMulForBufferSize(C, Call.getArgExpr(0), Call.getArgExpr(1));
2541 return MallocMemAux(C, Call, TotalSize, zeroVal, State, AF_Malloc);
2544 MallocChecker::LeakInfo MallocChecker::getAllocationSite(const ExplodedNode *N,
2546 CheckerContext &C) {
2547 const LocationContext *LeakContext = N->getLocationContext();
2548 // Walk the ExplodedGraph backwards and find the first node that referred to
2549 // the tracked symbol.
2550 const ExplodedNode *AllocNode = N;
2551 const MemRegion *ReferenceRegion = nullptr;
2554 ProgramStateRef State = N->getState();
2555 if (!State->get<RegionState>(Sym))
2558 // Find the most recent expression bound to the symbol in the current
2560 if (!ReferenceRegion) {
2561 if (const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2562 SVal Val = State->getSVal(MR);
2563 if (Val.getAsLocSymbol() == Sym) {
2564 const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
2565 // Do not show local variables belonging to a function other than
2566 // where the error is reported.
2567 if (!VR || (VR->getStackFrame() == LeakContext->getStackFrame()))
2568 ReferenceRegion = MR;
2573 // Allocation node, is the last node in the current or parent context in
2574 // which the symbol was tracked.
2575 const LocationContext *NContext = N->getLocationContext();
2576 if (NContext == LeakContext ||
2577 NContext->isParentOf(LeakContext))
2579 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2582 return LeakInfo(AllocNode, ReferenceRegion);
2585 void MallocChecker::HandleLeak(SymbolRef Sym, ExplodedNode *N,
2586 CheckerContext &C) const {
2588 if (!ChecksEnabled[CK_MallocChecker] &&
2589 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2592 const RefState *RS = C.getState()->get<RegionState>(Sym);
2593 assert(RS && "cannot leak an untracked symbol");
2594 AllocationFamily Family = RS->getAllocationFamily();
2596 if (Family == AF_Alloca)
2599 Optional<MallocChecker::CheckKind>
2600 CheckKind = getCheckIfTracked(Family, true);
2602 if (!CheckKind.hasValue())
2606 if (!BT_Leak[*CheckKind]) {
2607 // Leaks should not be reported if they are post-dominated by a sink:
2608 // (1) Sinks are higher importance bugs.
2609 // (2) NoReturnFunctionChecker uses sink nodes to represent paths ending
2610 // with __noreturn functions such as assert() or exit(). We choose not
2611 // to report leaks on such paths.
2612 BT_Leak[*CheckKind].reset(new BugType(CheckNames[*CheckKind], "Memory leak",
2613 categories::MemoryError,
2614 /*SuppressOnSink=*/true));
2617 // Most bug reports are cached at the location where they occurred.
2618 // With leaks, we want to unique them by the location where they were
2619 // allocated, and only report a single path.
2620 PathDiagnosticLocation LocUsedForUniqueing;
2621 const ExplodedNode *AllocNode = nullptr;
2622 const MemRegion *Region = nullptr;
2623 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2625 const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
2627 LocUsedForUniqueing = PathDiagnosticLocation::createBegin(AllocationStmt,
2628 C.getSourceManager(),
2629 AllocNode->getLocationContext());
2631 SmallString<200> buf;
2632 llvm::raw_svector_ostream os(buf);
2633 if (Region && Region->canPrintPretty()) {
2634 os << "Potential leak of memory pointed to by ";
2635 Region->printPretty(os);
2637 os << "Potential memory leak";
2640 auto R = std::make_unique<PathSensitiveBugReport>(
2641 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2642 AllocNode->getLocationContext()->getDecl());
2643 R->markInteresting(Sym);
2644 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym, true));
2645 C.emitReport(std::move(R));
2648 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2649 CheckerContext &C) const
2651 ProgramStateRef state = C.getState();
2652 RegionStateTy OldRS = state->get<RegionState>();
2653 RegionStateTy::Factory &F = state->get_context<RegionState>();
2655 RegionStateTy RS = OldRS;
2656 SmallVector<SymbolRef, 2> Errors;
2657 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2658 if (SymReaper.isDead(I->first)) {
2659 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2660 Errors.push_back(I->first);
2661 // Remove the dead symbol from the map.
2662 RS = F.remove(RS, I->first);
2667 // We shouldn't have touched other maps yet.
2668 assert(state->get<ReallocPairs>() ==
2669 C.getState()->get<ReallocPairs>());
2670 assert(state->get<FreeReturnValue>() ==
2671 C.getState()->get<FreeReturnValue>());
2675 // Cleanup the Realloc Pairs Map.
2676 ReallocPairsTy RP = state->get<ReallocPairs>();
2677 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2678 if (SymReaper.isDead(I->first) ||
2679 SymReaper.isDead(I->second.ReallocatedSym)) {
2680 state = state->remove<ReallocPairs>(I->first);
2684 // Cleanup the FreeReturnValue Map.
2685 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2686 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2687 if (SymReaper.isDead(I->first) ||
2688 SymReaper.isDead(I->second)) {
2689 state = state->remove<FreeReturnValue>(I->first);
2693 // Generate leak node.
2694 ExplodedNode *N = C.getPredecessor();
2695 if (!Errors.empty()) {
2696 static CheckerProgramPointTag Tag("MallocChecker", "DeadSymbolsLeak");
2697 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2699 for (SmallVectorImpl<SymbolRef>::iterator
2700 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2701 HandleLeak(*I, N, C);
2706 C.addTransition(state->set<RegionState>(RS), N);
2709 void MallocChecker::checkPreCall(const CallEvent &Call,
2710 CheckerContext &C) const {
2712 if (const auto *DC = dyn_cast<CXXDeallocatorCall>(&Call)) {
2713 const CXXDeleteExpr *DE = DC->getOriginExpr();
2715 if (!ChecksEnabled[CK_NewDeleteChecker])
2716 if (SymbolRef Sym = C.getSVal(DE->getArgument()).getAsSymbol())
2717 checkUseAfterFree(Sym, C, DE->getArgument());
2719 if (!isStandardNewDelete(DC->getDecl()))
2722 ProgramStateRef State = C.getState();
2723 bool IsKnownToBeAllocated;
2724 State = FreeMemAux(C, DE->getArgument(), Call, State,
2725 /*Hold*/ false, IsKnownToBeAllocated,
2726 (DE->isArrayForm() ? AF_CXXNewArray : AF_CXXNew));
2728 C.addTransition(State);
2732 if (const auto *DC = dyn_cast<CXXDestructorCall>(&Call)) {
2733 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2734 if (!Sym || checkDoubleDelete(Sym, C))
2738 // We will check for double free in the post visit.
2739 if (const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&Call)) {
2740 const FunctionDecl *FD = FC->getDecl();
2744 if (ChecksEnabled[CK_MallocChecker] && isFreeingCall(Call))
2748 // Check if the callee of a method is deleted.
2749 if (const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&Call)) {
2750 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2751 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2755 // Check arguments for being used after free.
2756 for (unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2757 SVal ArgSVal = Call.getArgSVal(I);
2758 if (ArgSVal.getAs<Loc>()) {
2759 SymbolRef Sym = ArgSVal.getAsSymbol();
2762 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2768 void MallocChecker::checkPreStmt(const ReturnStmt *S,
2769 CheckerContext &C) const {
2770 checkEscapeOnReturn(S, C);
2773 // In the CFG, automatic destructors come after the return statement.
2774 // This callback checks for returning memory that is freed by automatic
2775 // destructors, as those cannot be reached in checkPreStmt().
2776 void MallocChecker::checkEndFunction(const ReturnStmt *S,
2777 CheckerContext &C) const {
2778 checkEscapeOnReturn(S, C);
2781 void MallocChecker::checkEscapeOnReturn(const ReturnStmt *S,
2782 CheckerContext &C) const {
2786 const Expr *E = S->getRetValue();
2790 // Check if we are returning a symbol.
2791 ProgramStateRef State = C.getState();
2792 SVal RetVal = C.getSVal(E);
2793 SymbolRef Sym = RetVal.getAsSymbol();
2795 // If we are returning a field of the allocated struct or an array element,
2796 // the callee could still free the memory.
2797 // TODO: This logic should be a part of generic symbol escape callback.
2798 if (const MemRegion *MR = RetVal.getAsRegion())
2799 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2800 if (const SymbolicRegion *BMR =
2801 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2802 Sym = BMR->getSymbol();
2804 // Check if we are returning freed memory.
2806 checkUseAfterFree(Sym, C, E);
2809 // TODO: Blocks should be either inlined or should call invalidate regions
2810 // upon invocation. After that's in place, special casing here will not be
2812 void MallocChecker::checkPostStmt(const BlockExpr *BE,
2813 CheckerContext &C) const {
2815 // Scan the BlockDecRefExprs for any object the retain count checker
2817 if (!BE->getBlockDecl()->hasCaptures())
2820 ProgramStateRef state = C.getState();
2821 const BlockDataRegion *R =
2822 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2824 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2825 E = R->referenced_vars_end();
2830 SmallVector<const MemRegion*, 10> Regions;
2831 const LocationContext *LC = C.getLocationContext();
2832 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2834 for ( ; I != E; ++I) {
2835 const VarRegion *VR = I.getCapturedRegion();
2836 if (VR->getSuperRegion() == R) {
2837 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2839 Regions.push_back(VR);
2843 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
2844 C.addTransition(state);
2847 static bool isReleased(SymbolRef Sym, CheckerContext &C) {
2849 const RefState *RS = C.getState()->get<RegionState>(Sym);
2850 return (RS && RS->isReleased());
2853 bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
2854 const CallEvent &Call, CheckerContext &C) const {
2855 if (Call.getNumArgs() == 0)
2858 StringRef FunctionStr = "";
2859 if (const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
2860 if (const Stmt *Body = FD->getBody())
2861 if (Body->getBeginLoc().isValid())
2863 Lexer::getSourceText(CharSourceRange::getTokenRange(
2864 {FD->getBeginLoc(), Body->getBeginLoc()}),
2865 C.getSourceManager(), C.getLangOpts());
2867 // We do not model the Integer Set Library's retain-count based allocation.
2868 if (!FunctionStr.contains("__isl_"))
2871 ProgramStateRef State = C.getState();
2873 for (const Expr *Arg : cast<CallExpr>(Call.getOriginExpr())->arguments())
2874 if (SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
2875 if (const RefState *RS = State->get<RegionState>(Sym))
2876 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
2878 C.addTransition(State);
2882 bool MallocChecker::checkUseAfterFree(SymbolRef Sym, CheckerContext &C,
2883 const Stmt *S) const {
2885 if (isReleased(Sym, C)) {
2886 HandleUseAfterFree(C, S->getSourceRange(), Sym);
2893 void MallocChecker::checkUseZeroAllocated(SymbolRef Sym, CheckerContext &C,
2894 const Stmt *S) const {
2897 if (const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2898 if (RS->isAllocatedOfSizeZero())
2899 HandleUseZeroAlloc(C, RS->getStmt()->getSourceRange(), Sym);
2901 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2902 HandleUseZeroAlloc(C, S->getSourceRange(), Sym);
2906 bool MallocChecker::checkDoubleDelete(SymbolRef Sym, CheckerContext &C) const {
2908 if (isReleased(Sym, C)) {
2909 HandleDoubleDelete(C, Sym);
2915 // Check if the location is a freed symbolic region.
2916 void MallocChecker::checkLocation(SVal l, bool isLoad, const Stmt *S,
2917 CheckerContext &C) const {
2918 SymbolRef Sym = l.getLocSymbolInBase();
2920 checkUseAfterFree(Sym, C, S);
2921 checkUseZeroAllocated(Sym, C, S);
2925 // If a symbolic region is assumed to NULL (or another constant), stop tracking
2926 // it - assuming that allocation failed on this path.
2927 ProgramStateRef MallocChecker::evalAssume(ProgramStateRef state,
2929 bool Assumption) const {
2930 RegionStateTy RS = state->get<RegionState>();
2931 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2932 // If the symbol is assumed to be NULL, remove it from consideration.
2933 ConstraintManager &CMgr = state->getConstraintManager();
2934 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2935 if (AllocFailed.isConstrainedTrue())
2936 state = state->remove<RegionState>(I.getKey());
2939 // Realloc returns 0 when reallocation fails, which means that we should
2940 // restore the state of the pointer being reallocated.
2941 ReallocPairsTy RP = state->get<ReallocPairs>();
2942 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2943 // If the symbol is assumed to be NULL, remove it from consideration.
2944 ConstraintManager &CMgr = state->getConstraintManager();
2945 ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
2946 if (!AllocFailed.isConstrainedTrue())
2949 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2950 if (const RefState *RS = state->get<RegionState>(ReallocSym)) {
2951 if (RS->isReleased()) {
2952 switch (I.getData().Kind) {
2953 case OAR_ToBeFreedAfterFailure:
2954 state = state->set<RegionState>(ReallocSym,
2955 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2957 case OAR_DoNotTrackAfterFailure:
2958 state = state->remove<RegionState>(ReallocSym);
2961 assert(I.getData().Kind == OAR_FreeOnFailure);
2965 state = state->remove<ReallocPairs>(I.getKey());
2971 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2972 const CallEvent *Call,
2973 ProgramStateRef State,
2974 SymbolRef &EscapingSymbol) const {
2976 EscapingSymbol = nullptr;
2978 // For now, assume that any C++ or block call can free memory.
2979 // TODO: If we want to be more optimistic here, we'll need to make sure that
2980 // regions escape to C++ containers. They seem to do that even now, but for
2981 // mysterious reasons.
2982 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2985 // Check Objective-C messages by selector name.
2986 if (const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2987 // If it's not a framework call, or if it takes a callback, assume it
2989 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2992 // If it's a method we know about, handle it explicitly post-call.
2993 // This should happen before the "freeWhenDone" check below.
2994 if (isKnownDeallocObjCMethodName(*Msg))
2997 // If there's a "freeWhenDone" parameter, but the method isn't one we know
2998 // about, we can't be sure that the object will use free() to deallocate the
2999 // memory, so we can't model it explicitly. The best we can do is use it to
3000 // decide whether the pointer escapes.
3001 if (Optional<bool> FreeWhenDone = getFreeWhenDoneArg(*Msg))
3002 return *FreeWhenDone;
3004 // If the first selector piece ends with "NoCopy", and there is no
3005 // "freeWhenDone" parameter set to zero, we know ownership is being
3006 // transferred. Again, though, we can't be sure that the object will use
3007 // free() to deallocate the memory, so we can't model it explicitly.
3008 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
3009 if (FirstSlot.endswith("NoCopy"))
3012 // If the first selector starts with addPointer, insertPointer,
3013 // or replacePointer, assume we are dealing with NSPointerArray or similar.
3014 // This is similar to C++ containers (vector); we still might want to check
3015 // that the pointers get freed by following the container itself.
3016 if (FirstSlot.startswith("addPointer") ||
3017 FirstSlot.startswith("insertPointer") ||
3018 FirstSlot.startswith("replacePointer") ||
3019 FirstSlot.equals("valueWithPointer")) {
3023 // We should escape receiver on call to 'init'. This is especially relevant
3024 // to the receiver, as the corresponding symbol is usually not referenced
3026 if (Msg->getMethodFamily() == OMF_init) {
3027 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
3031 // Otherwise, assume that the method does not free memory.
3032 // Most framework methods do not free memory.
3036 // At this point the only thing left to handle is straight function calls.
3037 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
3041 // If it's one of the allocation functions we can reason about, we model
3042 // its behavior explicitly.
3043 if (isMemCall(*Call))
3046 // If it's not a system call, assume it frees memory.
3047 if (!Call->isInSystemHeader())
3050 // White list the system functions whose arguments escape.
3051 const IdentifierInfo *II = FD->getIdentifier();
3054 StringRef FName = II->getName();
3056 // White list the 'XXXNoCopy' CoreFoundation functions.
3057 // We specifically check these before
3058 if (FName.endswith("NoCopy")) {
3059 // Look for the deallocator argument. We know that the memory ownership
3060 // is not transferred only if the deallocator argument is
3061 // 'kCFAllocatorNull'.
3062 for (unsigned i = 1; i < Call->getNumArgs(); ++i) {
3063 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3064 if (const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3065 StringRef DeallocatorName = DE->getFoundDecl()->getName();
3066 if (DeallocatorName == "kCFAllocatorNull")
3073 // Associating streams with malloced buffers. The pointer can escape if
3074 // 'closefn' is specified (and if that function does free memory),
3075 // but it will not if closefn is not specified.
3076 // Currently, we do not inspect the 'closefn' function (PR12101).
3077 if (FName == "funopen")
3078 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
3081 // Do not warn on pointers passed to 'setbuf' when used with std streams,
3082 // these leaks might be intentional when setting the buffer for stdio.
3083 // http://stackoverflow.com/questions/2671151/who-frees-setvbuf-buffer
3084 if (FName == "setbuf" || FName =="setbuffer" ||
3085 FName == "setlinebuf" || FName == "setvbuf") {
3086 if (Call->getNumArgs() >= 1) {
3087 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3088 if (const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3089 if (const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3090 if (D->getCanonicalDecl()->getName().find("std") != StringRef::npos)
3095 // A bunch of other functions which either take ownership of a pointer or
3096 // wrap the result up in a struct or object, meaning it can be freed later.
3097 // (See RetainCountChecker.) Not all the parameters here are invalidated,
3098 // but the Malloc checker cannot differentiate between them. The right way
3099 // of doing this would be to implement a pointer escapes callback.
3100 if (FName == "CGBitmapContextCreate" ||
3101 FName == "CGBitmapContextCreateWithData" ||
3102 FName == "CVPixelBufferCreateWithBytes" ||
3103 FName == "CVPixelBufferCreateWithPlanarBytes" ||
3104 FName == "OSAtomicEnqueue") {
3108 if (FName == "postEvent" &&
3109 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3113 if (FName == "postEvent" &&
3114 FD->getQualifiedNameAsString() == "QCoreApplication::postEvent") {
3118 if (FName == "connectImpl" &&
3119 FD->getQualifiedNameAsString() == "QObject::connectImpl") {
3123 // Handle cases where we know a buffer's /address/ can escape.
3124 // Note that the above checks handle some special cases where we know that
3125 // even though the address escapes, it's still our responsibility to free the
3127 if (Call->argumentsMayEscape())
3130 // Otherwise, assume that the function does not free memory.
3131 // Most system calls do not free the memory.
3135 ProgramStateRef MallocChecker::checkPointerEscape(ProgramStateRef State,
3136 const InvalidatedSymbols &Escaped,
3137 const CallEvent *Call,
3138 PointerEscapeKind Kind) const {
3139 return checkPointerEscapeAux(State, Escaped, Call, Kind,
3140 /*IsConstPointerEscape*/ false);
3143 ProgramStateRef MallocChecker::checkConstPointerEscape(ProgramStateRef State,
3144 const InvalidatedSymbols &Escaped,
3145 const CallEvent *Call,
3146 PointerEscapeKind Kind) const {
3147 // If a const pointer escapes, it may not be freed(), but it could be deleted.
3148 return checkPointerEscapeAux(State, Escaped, Call, Kind,
3149 /*IsConstPointerEscape*/ true);
3152 static bool checkIfNewOrNewArrayFamily(const RefState *RS) {
3153 return (RS->getAllocationFamily() == AF_CXXNewArray ||
3154 RS->getAllocationFamily() == AF_CXXNew);
3157 ProgramStateRef MallocChecker::checkPointerEscapeAux(
3158 ProgramStateRef State, const InvalidatedSymbols &Escaped,
3159 const CallEvent *Call, PointerEscapeKind Kind,
3160 bool IsConstPointerEscape) const {
3161 // If we know that the call does not free memory, or we want to process the
3162 // call later, keep tracking the top level arguments.
3163 SymbolRef EscapingSymbol = nullptr;
3164 if (Kind == PSK_DirectEscapeOnCall &&
3165 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call, State,
3171 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
3176 if (EscapingSymbol && EscapingSymbol != sym)
3179 if (const RefState *RS = State->get<RegionState>(sym))
3180 if (RS->isAllocated() || RS->isAllocatedOfSizeZero())
3181 if (!IsConstPointerEscape || checkIfNewOrNewArrayFamily(RS))
3182 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3187 bool MallocChecker::isArgZERO_SIZE_PTR(ProgramStateRef State, CheckerContext &C,
3188 SVal ArgVal) const {
3189 if (!KernelZeroSizePtrValue)
3190 KernelZeroSizePtrValue =
3191 tryExpandAsInteger("ZERO_SIZE_PTR", C.getPreprocessor());
3193 const llvm::APSInt *ArgValKnown =
3194 C.getSValBuilder().getKnownValue(State, ArgVal);
3195 return ArgValKnown && *KernelZeroSizePtrValue &&
3196 ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue;
3199 static SymbolRef findFailedReallocSymbol(ProgramStateRef currState,
3200 ProgramStateRef prevState) {
3201 ReallocPairsTy currMap = currState->get<ReallocPairs>();
3202 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3204 for (const ReallocPairsTy::value_type &Pair : prevMap) {
3205 SymbolRef sym = Pair.first;
3206 if (!currMap.lookup(sym))
3213 static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD) {
3214 if (const IdentifierInfo *II = DD->getParent()->getIdentifier()) {
3215 StringRef N = II->getName();
3216 if (N.contains_lower("ptr") || N.contains_lower("pointer")) {
3217 if (N.contains_lower("ref") || N.contains_lower("cnt") ||
3218 N.contains_lower("intrusive") || N.contains_lower("shared")) {
3226 PathDiagnosticPieceRef MallocBugVisitor::VisitNode(const ExplodedNode *N,
3227 BugReporterContext &BRC,
3228 PathSensitiveBugReport &BR) {
3229 ProgramStateRef state = N->getState();
3230 ProgramStateRef statePrev = N->getFirstPred()->getState();
3232 const RefState *RSCurr = state->get<RegionState>(Sym);
3233 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3235 const Stmt *S = N->getStmtForDiagnostics();
3236 // When dealing with containers, we sometimes want to give a note
3237 // even if the statement is missing.
3238 if (!S && (!RSCurr || RSCurr->getAllocationFamily() != AF_InnerBuffer))
3241 const LocationContext *CurrentLC = N->getLocationContext();
3243 // If we find an atomic fetch_add or fetch_sub within the destructor in which
3244 // the pointer was released (before the release), this is likely a destructor
3245 // of a shared pointer.
3246 // Because we don't model atomics, and also because we don't know that the
3247 // original reference count is positive, we should not report use-after-frees
3248 // on objects deleted in such destructors. This can probably be improved
3249 // through better shared pointer modeling.
3250 if (ReleaseDestructorLC) {
3251 if (const auto *AE = dyn_cast<AtomicExpr>(S)) {
3252 AtomicExpr::AtomicOp Op = AE->getOp();
3253 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
3254 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
3255 if (ReleaseDestructorLC == CurrentLC ||
3256 ReleaseDestructorLC->isParentOf(CurrentLC)) {
3257 BR.markInvalid(getTag(), S);
3263 // FIXME: We will eventually need to handle non-statement-based events
3264 // (__attribute__((cleanup))).
3266 // Find out if this is an interesting point and what is the kind.
3268 std::unique_ptr<StackHintGeneratorForSymbol> StackHint = nullptr;
3269 SmallString<256> Buf;
3270 llvm::raw_svector_ostream OS(Buf);
3272 if (Mode == Normal) {
3273 if (isAllocated(RSCurr, RSPrev, S)) {
3274 Msg = "Memory is allocated";
3275 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3276 Sym, "Returned allocated memory");
3277 } else if (isReleased(RSCurr, RSPrev, S)) {
3278 const auto Family = RSCurr->getAllocationFamily();
3283 case AF_CXXNewArray:
3284 case AF_IfNameIndex:
3285 Msg = "Memory is released";
3286 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3287 Sym, "Returning; memory was released");
3289 case AF_InnerBuffer: {
3290 const MemRegion *ObjRegion =
3291 allocation_state::getContainerObjRegion(statePrev, Sym);
3292 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
3293 QualType ObjTy = TypedRegion->getValueType();
3294 OS << "Inner buffer of '" << ObjTy.getAsString() << "' ";
3296 if (N->getLocation().getKind() == ProgramPoint::PostImplicitCallKind) {
3297 OS << "deallocated by call to destructor";
3298 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3299 Sym, "Returning; inner buffer was deallocated");
3301 OS << "reallocated by call to '";
3302 const Stmt *S = RSCurr->getStmt();
3303 if (const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
3304 OS << MemCallE->getMethodDecl()->getNameAsString();
3305 } else if (const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
3306 OS << OpCallE->getDirectCallee()->getNameAsString();
3307 } else if (const auto *CallE = dyn_cast<CallExpr>(S)) {
3308 auto &CEMgr = BRC.getStateManager().getCallEventManager();
3309 CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
3310 const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl());
3311 OS << (D ? D->getNameAsString() : "unknown");
3314 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3315 Sym, "Returning; inner buffer was reallocated");
3321 llvm_unreachable("Unhandled allocation family!");
3324 // See if we're releasing memory while inlining a destructor
3325 // (or one of its callees). This turns on various common
3326 // false positive suppressions.
3327 bool FoundAnyDestructor = false;
3328 for (const LocationContext *LC = CurrentLC; LC; LC = LC->getParent()) {
3329 if (const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3330 if (isReferenceCountingPointerDestructor(DD)) {
3331 // This immediately looks like a reference-counting destructor.
3332 // We're bad at guessing the original reference count of the object,
3333 // so suppress the report for now.
3334 BR.markInvalid(getTag(), DD);
3335 } else if (!FoundAnyDestructor) {
3336 assert(!ReleaseDestructorLC &&
3337 "There can be only one release point!");
3338 // Suspect that it's a reference counting pointer destructor.
3339 // On one of the next nodes might find out that it has atomic
3340 // reference counting operations within it (see the code above),
3341 // and if so, we'd conclude that it likely is a reference counting
3342 // pointer destructor.
3343 ReleaseDestructorLC = LC->getStackFrame();
3344 // It is unlikely that releasing memory is delegated to a destructor
3345 // inside a destructor of a shared pointer, because it's fairly hard
3346 // to pass the information that the pointer indeed needs to be
3347 // released into it. So we're only interested in the innermost
3349 FoundAnyDestructor = true;
3353 } else if (isRelinquished(RSCurr, RSPrev, S)) {
3354 Msg = "Memory ownership is transferred";
3355 StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym, "");
3356 } else if (hasReallocFailed(RSCurr, RSPrev, S)) {
3357 Mode = ReallocationFailed;
3358 Msg = "Reallocation failed";
3359 StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
3360 Sym, "Reallocation failed");
3362 if (SymbolRef sym = findFailedReallocSymbol(state, statePrev)) {
3363 // Is it possible to fail two reallocs WITHOUT testing in between?
3364 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3365 "We only support one failed realloc at a time.");
3366 BR.markInteresting(sym);
3367 FailedReallocSymbol = sym;
3371 // We are in a special mode if a reallocation failed later in the path.
3372 } else if (Mode == ReallocationFailed) {
3373 assert(FailedReallocSymbol && "No symbol to look for.");
3375 // Is this is the first appearance of the reallocated symbol?
3376 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3377 // We're at the reallocation point.
3378 Msg = "Attempt to reallocate memory";
3379 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3380 Sym, "Returned reallocated memory");
3381 FailedReallocSymbol = nullptr;
3393 // Generate the extra diagnostic.
3394 PathDiagnosticLocation Pos;
3396 assert(RSCurr->getAllocationFamily() == AF_InnerBuffer);
3397 auto PostImplCall = N->getLocation().getAs<PostImplicitCall>();
3400 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3401 BRC.getSourceManager());
3403 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3404 N->getLocationContext());
3407 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg, true);
3408 BR.addCallStackHint(P, std::move(StackHint));
3412 void MallocChecker::printState(raw_ostream &Out, ProgramStateRef State,
3413 const char *NL, const char *Sep) const {
3415 RegionStateTy RS = State->get<RegionState>();
3417 if (!RS.isEmpty()) {
3418 Out << Sep << "MallocChecker :" << NL;
3419 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3420 const RefState *RefS = State->get<RegionState>(I.getKey());
3421 AllocationFamily Family = RefS->getAllocationFamily();
3422 Optional<MallocChecker::CheckKind> CheckKind = getCheckIfTracked(Family);
3423 if (!CheckKind.hasValue())
3424 CheckKind = getCheckIfTracked(Family, true);
3426 I.getKey()->dumpToStream(Out);
3428 I.getData().dump(Out);
3429 if (CheckKind.hasValue())
3430 Out << " (" << CheckNames[*CheckKind].getName() << ")";
3438 namespace allocation_state {
3441 markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin) {
3442 AllocationFamily Family = AF_InnerBuffer;
3443 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3446 } // end namespace allocation_state
3447 } // end namespace ento
3448 } // end namespace clang
3450 // Intended to be used in InnerPointerChecker to register the part of
3451 // MallocChecker connected to it.
3452 void ento::registerInnerPointerCheckerAux(CheckerManager &mgr) {
3453 MallocChecker *checker = mgr.getChecker<MallocChecker>();
3454 checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] = true;
3455 checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3456 mgr.getCurrentCheckerName();
3459 void ento::registerDynamicMemoryModeling(CheckerManager &mgr) {
3460 auto *checker = mgr.registerChecker<MallocChecker>();
3461 checker->ShouldIncludeOwnershipAnnotatedFunctions =
3462 mgr.getAnalyzerOptions().getCheckerBooleanOption(checker, "Optimistic");
3465 bool ento::shouldRegisterDynamicMemoryModeling(const CheckerManager &mgr) {
3469 #define REGISTER_CHECKER(name) \
3470 void ento::register##name(CheckerManager &mgr) { \
3471 MallocChecker *checker = mgr.getChecker<MallocChecker>(); \
3472 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \
3473 checker->CheckNames[MallocChecker::CK_##name] = \
3474 mgr.getCurrentCheckerName(); \
3477 bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
3479 REGISTER_CHECKER(MallocChecker)
3480 REGISTER_CHECKER(NewDeleteChecker)
3481 REGISTER_CHECKER(NewDeleteLeaksChecker)
3482 REGISTER_CHECKER(MismatchedDeallocatorChecker)