30 #include "llvm/ADT/STLExtras.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/StringExtras.h" 37 using namespace clang;
74 RefState(
Kind k,
const Stmt *s,
unsigned family)
75 : S(s), K(k), Family(family) {
76 assert(family != AF_None);
79 bool isAllocated()
const {
return K == Allocated; }
80 bool isAllocatedOfSizeZero()
const {
return K == AllocatedOfSizeZero; }
81 bool isReleased()
const {
return K == Released; }
82 bool isRelinquished()
const {
return K == Relinquished; }
83 bool isEscaped()
const {
return K == Escaped; }
87 const Stmt *getStmt()
const {
return S; }
90 return K == X.K && S == X.S && Family == X.Family;
93 static RefState getAllocated(
unsigned family,
const Stmt *s) {
94 return RefState(Allocated, s, family);
96 static RefState getAllocatedOfSizeZero(
const RefState *RS) {
97 return RefState(AllocatedOfSizeZero, RS->getStmt(),
98 RS->getAllocationFamily());
100 static RefState getReleased(
unsigned family,
const Stmt *s) {
101 return RefState(Released, s, family);
103 static RefState getRelinquished(
unsigned family,
const Stmt *s) {
104 return RefState(Relinquished, s, family);
106 static RefState getEscaped(
const RefState *RS) {
107 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
110 void Profile(llvm::FoldingSetNodeID &
ID)
const {
113 ID.AddInteger(Family);
116 void dump(raw_ostream &
OS)
const {
117 switch (static_cast<Kind>(K)) {
118 #define CASE(ID) case ID: OS << #ID; break; 120 CASE(AllocatedOfSizeZero)
127 LLVM_DUMP_METHOD
void dump()
const {
dump(llvm::errs()); }
131 RPToBeFreedAfterFailure,
135 RPDoNotTrackAfterFailure
147 ReallocatedSym(S),
Kind(K) {}
148 void Profile(llvm::FoldingSetNodeID &
ID)
const {
150 ID.AddPointer(ReallocatedSym);
153 return ReallocatedSym == X.ReallocatedSym &&
158 typedef std::pair<const ExplodedNode*, const MemRegion*> LeakInfo;
160 class MallocChecker :
public Checker<check::DeadSymbols,
161 check::PointerEscape,
162 check::ConstPointerEscape,
163 check::PreStmt<ReturnStmt>,
166 check::PostStmt<CallExpr>,
167 check::PostStmt<CXXNewExpr>,
169 check::PreStmt<CXXDeleteExpr>,
170 check::PostStmt<BlockExpr>,
171 check::PostObjCMessage,
177 : II_alloca(
nullptr), II_win_alloca(
nullptr), II_malloc(
nullptr),
178 II_free(
nullptr), II_realloc(
nullptr), II_calloc(
nullptr),
179 II_valloc(
nullptr), II_reallocf(
nullptr), II_strndup(
nullptr),
180 II_strdup(
nullptr), II_win_strdup(
nullptr), II_kmalloc(
nullptr),
181 II_kfree(
nullptr), II_if_nameindex(
nullptr),
182 II_if_freenameindex(
nullptr), II_wcsdup(
nullptr),
183 II_win_wcsdup(
nullptr), II_g_malloc(
nullptr), II_g_malloc0(
nullptr),
184 II_g_realloc(
nullptr), II_g_try_malloc(
nullptr),
185 II_g_try_malloc0(
nullptr), II_g_try_realloc(
nullptr),
186 II_g_free(
nullptr), II_g_memdup(
nullptr), II_g_malloc_n(
nullptr),
187 II_g_malloc0_n(
nullptr), II_g_realloc_n(
nullptr),
188 II_g_try_malloc_n(
nullptr), II_g_try_malloc0_n(
nullptr),
189 II_g_try_realloc_n(
nullptr) {}
196 CK_NewDeleteLeaksChecker,
197 CK_MismatchedDeallocatorChecker,
198 CK_InnerPointerChecker,
202 enum class MemoryOperationKind {
208 DefaultBool IsOptimistic;
210 DefaultBool ChecksEnabled[CK_NumCheckKinds];
211 CheckName CheckNames[CK_NumCheckKinds];
213 void checkPreCall(
const CallEvent &Call, CheckerContext &C)
const;
214 void checkPostStmt(
const CallExpr *CE, CheckerContext &C)
const;
215 void checkPostStmt(
const CXXNewExpr *NE, CheckerContext &C)
const;
217 CheckerContext &C)
const;
218 void checkPreStmt(
const CXXDeleteExpr *DE, CheckerContext &C)
const;
219 void checkPostObjCMessage(
const ObjCMethodCall &Call, CheckerContext &C)
const;
220 void checkPostStmt(
const BlockExpr *BE, CheckerContext &C)
const;
221 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C)
const;
222 void checkPreStmt(
const ReturnStmt *S, CheckerContext &C)
const;
223 void checkEndFunction(
const ReturnStmt *S, CheckerContext &C)
const;
225 bool Assumption)
const;
226 void checkLocation(SVal l,
bool isLoad,
const Stmt *S,
227 CheckerContext &C)
const;
239 const char *NL,
const char *Sep)
const override;
242 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
243 mutable std::unique_ptr<BugType> BT_DoubleDelete;
244 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
245 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
246 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
247 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
248 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
249 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
250 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
251 mutable IdentifierInfo *II_alloca, *II_win_alloca, *II_malloc, *II_free,
252 *II_realloc, *II_calloc, *II_valloc, *II_reallocf,
253 *II_strndup, *II_strdup, *II_win_strdup, *II_kmalloc,
254 *II_kfree, *II_if_nameindex, *II_if_freenameindex,
255 *II_wcsdup, *II_win_wcsdup, *II_g_malloc,
256 *II_g_malloc0, *II_g_realloc, *II_g_try_malloc,
257 *II_g_try_malloc0, *II_g_try_realloc, *II_g_free,
258 *II_g_memdup, *II_g_malloc_n, *II_g_malloc0_n,
259 *II_g_realloc_n, *II_g_try_malloc_n,
260 *II_g_try_malloc0_n, *II_g_try_realloc_n;
271 bool printAllocDeallocName(raw_ostream &os, CheckerContext &C,
272 const Expr *E)
const;
276 void printExpectedAllocName(raw_ostream &os, CheckerContext &C,
277 const Expr *DeallocExpr)
const;
280 void printExpectedDeallocName(raw_ostream &os,
AllocationFamily Family)
const;
289 MemoryOperationKind MemKind)
const;
295 void processNewAllocation(
const CXXNewExpr *NE, CheckerContext &C,
302 const unsigned AllocationSizeArg,
308 const OwnershipAttr* Att,
311 const Expr *SizeEx, SVal Init,
315 SVal SizeEx, SVal Init,
325 performKernelMalloc(
const CallExpr *CE, CheckerContext &C,
337 const OwnershipAttr* Att,
342 bool &ReleasedAllocated,
343 bool ReturnsNullOnFailure =
false)
const;
345 const Expr *ParentExpr,
348 bool &ReleasedAllocated,
349 bool ReturnsNullOnFailure =
false)
const;
352 bool FreesMemOnFailure,
354 bool SuffixWithN =
false)
const;
355 static SVal evalMulForBufferSize(CheckerContext &C,
const Expr *Blocks,
356 const Expr *BlockBytes);
361 bool isReleased(
SymbolRef Sym, CheckerContext &C)
const;
365 bool suppressDeallocationsInSuspiciousContexts(
const CallExpr *CE,
366 CheckerContext &C)
const;
368 bool checkUseAfterFree(
SymbolRef Sym, CheckerContext &C,
const Stmt *S)
const;
370 void checkUseZeroAllocated(
SymbolRef Sym, CheckerContext &C,
371 const Stmt *S)
const;
373 bool checkDoubleDelete(
SymbolRef Sym, CheckerContext &C)
const;
385 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
const CallEvent *Call,
394 bool(*CheckRefState)(
const RefState*))
const;
397 void checkEscapeOnReturn(
const ReturnStmt *S, CheckerContext &C)
const;
404 bool IsALeakCheck =
false)
const;
406 const Stmt *AllocDeallocStmt,
407 bool IsALeakCheck =
false)
const;
409 bool IsALeakCheck =
false)
const;
411 static bool SummarizeValue(raw_ostream &os, SVal
V);
412 static bool SummarizeRegion(raw_ostream &os,
const MemRegion *MR);
413 void ReportBadFree(CheckerContext &C, SVal ArgVal,
SourceRange Range,
414 const Expr *DeallocExpr)
const;
415 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
417 void ReportMismatchedDealloc(CheckerContext &C,
SourceRange Range,
418 const Expr *DeallocExpr,
const RefState *RS,
419 SymbolRef Sym,
bool OwnershipTransferred)
const;
420 void ReportOffsetFree(CheckerContext &C, SVal ArgVal,
SourceRange Range,
421 const Expr *DeallocExpr,
422 const Expr *AllocExpr =
nullptr)
const;
423 void ReportUseAfterFree(CheckerContext &C,
SourceRange Range,
425 void ReportDoubleFree(CheckerContext &C,
SourceRange Range,
bool Released,
428 void ReportDoubleDelete(CheckerContext &C,
SymbolRef Sym)
const;
430 void ReportUseZeroAllocated(CheckerContext &C,
SourceRange Range,
433 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
438 LeakInfo getAllocationSite(
const ExplodedNode *N,
SymbolRef Sym,
439 CheckerContext &C)
const;
441 void reportLeak(
SymbolRef Sym, ExplodedNode *N, CheckerContext &C)
const;
448 enum NotificationMode {
457 NotificationMode Mode;
469 MallocBugVisitor(
SymbolRef S,
bool isLeak =
false)
470 : Sym(S), Mode(Normal), FailedReallocSymbol(
nullptr),
471 ReleaseDestructorLC(
nullptr), IsLeak(isLeak) {}
473 static void *getTag() {
478 void Profile(llvm::FoldingSetNodeID &
ID)
const override {
479 ID.AddPointer(getTag());
483 inline bool isAllocated(
const RefState *S,
const RefState *SPrev,
486 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
487 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
488 (!SPrev || !(SPrev->isAllocated() ||
489 SPrev->isAllocatedOfSizeZero())));
492 inline bool isReleased(
const RefState *S,
const RefState *SPrev,
496 bool IsReleased = (S && S->isReleased()) &&
497 (!SPrev || !SPrev->isReleased());
498 assert(!IsReleased ||
499 (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
500 (!Stmt && S->getAllocationFamily() == AF_InnerBuffer));
504 inline bool isRelinquished(
const RefState *S,
const RefState *SPrev,
507 return (Stmt && (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
508 isa<ObjCPropertyRefExpr>(Stmt)) &&
509 (S && S->isRelinquished()) &&
510 (!SPrev || !SPrev->isRelinquished()));
513 inline bool isReallocFailedCheck(
const RefState *S,
const RefState *SPrev,
519 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
520 (S && (S->isAllocated() || S->isAllocatedOfSizeZero())) &&
521 (SPrev && !(SPrev->isAllocated() ||
522 SPrev->isAllocatedOfSizeZero())));
525 std::shared_ptr<PathDiagnosticPiece> VisitNode(
const ExplodedNode *N,
526 BugReporterContext &BRC,
527 BugReport &BR)
override;
529 std::shared_ptr<PathDiagnosticPiece>
530 getEndPath(BugReporterContext &BRC,
const ExplodedNode *EndPathNode,
531 BugReport &BR)
override {
535 PathDiagnosticLocation L =
537 BRC.getSourceManager());
539 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
544 class StackHintGeneratorForReallocationFailed
545 :
public StackHintGeneratorForSymbol {
547 StackHintGeneratorForReallocationFailed(
SymbolRef S, StringRef M)
548 : StackHintGeneratorForSymbol(S, M) {}
550 std::string getMessageForArg(
const Expr *ArgE,
551 unsigned ArgIndex)
override {
556 llvm::raw_svector_ostream os(buf);
558 os <<
"Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
559 <<
" parameter failed";
565 return "Reallocation of returned value failed";
581 class StopTrackingCallback final :
public SymbolVisitor {
587 bool VisitSymbol(
SymbolRef sym)
override {
588 state = state->remove<RegionState>(sym);
594 void MallocChecker::initIdentifierInfo(
ASTContext &Ctx)
const {
601 II_reallocf = &Ctx.
Idents.
get(
"reallocf");
609 II_if_nameindex = &Ctx.
Idents.
get(
"if_nameindex");
610 II_if_freenameindex = &Ctx.
Idents.
get(
"if_freenameindex");
613 II_win_strdup = &Ctx.
Idents.
get(
"_strdup");
614 II_win_wcsdup = &Ctx.
Idents.
get(
"_wcsdup");
615 II_win_alloca = &Ctx.
Idents.
get(
"_alloca");
618 II_g_malloc = &Ctx.
Idents.
get(
"g_malloc");
619 II_g_malloc0 = &Ctx.
Idents.
get(
"g_malloc0");
620 II_g_realloc = &Ctx.
Idents.
get(
"g_realloc");
621 II_g_try_malloc = &Ctx.
Idents.
get(
"g_try_malloc");
622 II_g_try_malloc0 = &Ctx.
Idents.
get(
"g_try_malloc0");
623 II_g_try_realloc = &Ctx.
Idents.
get(
"g_try_realloc");
625 II_g_memdup = &Ctx.
Idents.
get(
"g_memdup");
626 II_g_malloc_n = &Ctx.
Idents.
get(
"g_malloc_n");
627 II_g_malloc0_n = &Ctx.
Idents.
get(
"g_malloc0_n");
628 II_g_realloc_n = &Ctx.
Idents.
get(
"g_realloc_n");
629 II_g_try_malloc_n = &Ctx.
Idents.
get(
"g_try_malloc_n");
630 II_g_try_malloc0_n = &Ctx.
Idents.
get(
"g_try_malloc0_n");
631 II_g_try_realloc_n = &Ctx.
Idents.
get(
"g_try_realloc_n");
635 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
638 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
641 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
644 if (isStandardNewDelete(FD, C))
650 bool MallocChecker::isCMemFunction(
const FunctionDecl *FD,
653 MemoryOperationKind MemKind)
const {
657 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
658 MemKind == MemoryOperationKind::MOK_Free);
659 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
660 MemKind == MemoryOperationKind::MOK_Allocate);
664 initIdentifierInfo(C);
666 if (Family == AF_Malloc && CheckFree) {
667 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
668 FunI == II_g_free || FunI == II_kfree)
672 if (Family == AF_Malloc && CheckAlloc) {
673 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
674 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
675 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
676 FunI == II_win_wcsdup || FunI == II_kmalloc ||
677 FunI == II_g_malloc || FunI == II_g_malloc0 ||
678 FunI == II_g_realloc || FunI == II_g_try_malloc ||
679 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
680 FunI == II_g_memdup || FunI == II_g_malloc_n ||
681 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
682 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
683 FunI == II_g_try_realloc_n)
687 if (Family == AF_IfNameIndex && CheckFree) {
688 if (FunI == II_if_freenameindex)
692 if (Family == AF_IfNameIndex && CheckAlloc) {
693 if (FunI == II_if_nameindex)
697 if (Family == AF_Alloca && CheckAlloc) {
698 if (FunI == II_alloca || FunI == II_win_alloca)
703 if (Family != AF_Malloc)
706 if (IsOptimistic && FD->
hasAttrs()) {
708 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
709 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
712 }
else if (OwnKind == OwnershipAttr::Returns) {
724 bool MallocChecker::isStandardNewDelete(
const FunctionDecl *FD,
730 if (Kind != OO_New && Kind != OO_Array_New &&
731 Kind != OO_Delete && Kind != OO_Array_Delete)
762 if (!KernelZeroFlagVal.hasValue()) {
763 if (OS == llvm::Triple::FreeBSD)
764 KernelZeroFlagVal = 0x0100;
765 else if (OS == llvm::Triple::NetBSD)
766 KernelZeroFlagVal = 0x0002;
767 else if (OS == llvm::Triple::OpenBSD)
768 KernelZeroFlagVal = 0x0008;
769 else if (OS == llvm::Triple::Linux)
771 KernelZeroFlagVal = 0x8000;
788 const SVal
V = C.getSVal(FlagsEx);
789 if (!V.getAs<NonLoc>()) {
795 NonLoc Flags = V.castAs<NonLoc>();
796 NonLoc ZeroFlag = C.getSValBuilder()
797 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->
getType())
799 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
802 if (MaskedFlagsUC.isUnknownOrUndef())
804 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
808 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
811 if (TrueState && !FalseState) {
812 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.
CharTy);
813 return MallocMemAux(C, CE, CE->
getArg(0), ZeroVal, TrueState);
819 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C,
const Expr *Blocks,
820 const Expr *BlockBytes) {
821 SValBuilder &SB = C.getSValBuilder();
822 SVal BlocksVal = C.getSVal(Blocks);
823 SVal BlockBytesVal = C.getSVal(BlockBytes);
825 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
826 SB.getContext().getSizeType());
830 void MallocChecker::checkPostStmt(
const CallExpr *CE, CheckerContext &C)
const {
839 bool ReleasedAllocatedMemory =
false;
842 initIdentifierInfo(C.getASTContext());
845 if (FunI == II_malloc || FunI == II_g_malloc || FunI == II_g_try_malloc) {
849 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
851 State = ProcessZeroAllocation(C, CE, 0, State);
854 performKernelMalloc(CE, C, State);
855 if (MaybeState.hasValue())
856 State = MaybeState.getValue();
858 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
860 }
else if (FunI == II_kmalloc) {
864 performKernelMalloc(CE, C, State);
865 if (MaybeState.hasValue())
866 State = MaybeState.getValue();
868 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
869 }
else if (FunI == II_valloc) {
872 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
873 State = ProcessZeroAllocation(C, CE, 0, State);
874 }
else if (FunI == II_realloc || FunI == II_g_realloc ||
875 FunI == II_g_try_realloc) {
876 State = ReallocMemAux(C, CE,
false, State);
877 State = ProcessZeroAllocation(C, CE, 1, State);
878 }
else if (FunI == II_reallocf) {
879 State = ReallocMemAux(C, CE,
true, State);
880 State = ProcessZeroAllocation(C, CE, 1, State);
881 }
else if (FunI == II_calloc) {
882 State = CallocMem(C, CE, State);
883 State = ProcessZeroAllocation(C, CE, 0, State);
884 State = ProcessZeroAllocation(C, CE, 1, State);
885 }
else if (FunI == II_free || FunI == II_g_free || FunI == II_kfree) {
886 if (suppressDeallocationsInSuspiciousContexts(CE, C))
889 State = FreeMemAux(C, CE, State, 0,
false, ReleasedAllocatedMemory);
890 }
else if (FunI == II_strdup || FunI == II_win_strdup ||
891 FunI == II_wcsdup || FunI == II_win_wcsdup) {
892 State = MallocUpdateRefState(C, CE, State);
893 }
else if (FunI == II_strndup) {
894 State = MallocUpdateRefState(C, CE, State);
895 }
else if (FunI == II_alloca || FunI == II_win_alloca) {
898 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State,
900 State = ProcessZeroAllocation(C, CE, 0, State);
908 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State,
910 State = ProcessZeroAllocation(C, CE, 0, State);
912 else if (K == OO_Array_New) {
913 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State,
915 State = ProcessZeroAllocation(C, CE, 0, State);
917 else if (K == OO_Delete || K == OO_Array_Delete)
918 State = FreeMemAux(C, CE, State, 0,
false, ReleasedAllocatedMemory);
920 llvm_unreachable(
"not a new/delete operator");
921 }
else if (FunI == II_if_nameindex) {
924 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
926 }
else if (FunI == II_if_freenameindex) {
927 State = FreeMemAux(C, CE, State, 0,
false, ReleasedAllocatedMemory);
928 }
else if (FunI == II_g_malloc0 || FunI == II_g_try_malloc0) {
931 SValBuilder &svalBuilder = C.getSValBuilder();
932 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
933 State = MallocMemAux(C, CE, CE->
getArg(0), zeroVal,
State);
934 State = ProcessZeroAllocation(C, CE, 0, State);
935 }
else if (FunI == II_g_memdup) {
938 State = MallocMemAux(C, CE, CE->
getArg(1), UndefinedVal(),
State);
939 State = ProcessZeroAllocation(C, CE, 1, State);
940 }
else if (FunI == II_g_malloc_n || FunI == II_g_try_malloc_n ||
941 FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
944 SVal Init = UndefinedVal();
945 if (FunI == II_g_malloc0_n || FunI == II_g_try_malloc0_n) {
946 SValBuilder &SB = C.getSValBuilder();
947 Init = SB.makeZeroVal(SB.getContext().CharTy);
949 SVal TotalSize = evalMulForBufferSize(C, CE->
getArg(0), CE->
getArg(1));
950 State = MallocMemAux(C, CE, TotalSize, Init, State);
951 State = ProcessZeroAllocation(C, CE, 0, State);
952 State = ProcessZeroAllocation(C, CE, 1, State);
953 }
else if (FunI == II_g_realloc_n || FunI == II_g_try_realloc_n) {
956 State = ReallocMemAux(C, CE,
false, State,
true);
957 State = ProcessZeroAllocation(C, CE, 1, State);
958 State = ProcessZeroAllocation(C, CE, 2, State);
962 if (IsOptimistic || ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
967 switch (I->getOwnKind()) {
968 case OwnershipAttr::Returns:
969 State = MallocMemReturnsAttr(C, CE, I, State);
971 case OwnershipAttr::Takes:
972 case OwnershipAttr::Holds:
973 State = FreeMemAttr(C, CE, I, State);
978 C.addTransition(State);
983 CheckerContext &C,
const Expr *E,
const unsigned AllocationSizeArg,
989 RetVal = C.getSVal(E);
991 const Expr *Arg =
nullptr;
993 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
994 Arg = CE->
getArg(AllocationSizeArg);
996 else if (
const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
998 Arg = *NE->getArraySize();
1003 llvm_unreachable(
"not a CallExpr or CXXNewExpr");
1014 SValBuilder &SvalBuilder = C.getSValBuilder();
1016 SvalBuilder.makeZeroVal(Arg->
getType()).castAs<DefinedSVal>();
1018 std::tie(TrueState, FalseState) =
1019 State->assume(SvalBuilder.evalEQ(
State, *DefArgVal, Zero));
1021 if (TrueState && !FalseState) {
1022 SymbolRef Sym = RetVal->getAsLocSymbol();
1026 const RefState *RS =
State->get<RegionState>(Sym);
1028 if (RS->isAllocated())
1029 return TrueState->set<RegionState>(Sym,
1030 RefState::getAllocatedOfSizeZero(RS));
1038 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1049 while (!PointeeType.isNull()) {
1050 Result = PointeeType;
1068 for (
const auto *CtorParam : CtorD->
parameters()) {
1071 if (CtorParamPointeeT.
isNull())
1083 void MallocChecker::processNewAllocation(
const CXXNewExpr *NE,
1086 if (!isStandardNewDelete(NE->
getOperatorNew(), C.getASTContext()))
1089 ParentMap &PM = C.getLocationContext()->getParentMap();
1098 State = MallocUpdateRefState(C, NE, State, NE->
isArray() ? AF_CXXNewArray
1099 : AF_CXXNew, Target);
1100 State = addExtentSize(C, NE, State, Target);
1101 State = ProcessZeroAllocation(C, NE, 0, State, Target);
1102 C.addTransition(State);
1105 void MallocChecker::checkPostStmt(
const CXXNewExpr *NE,
1106 CheckerContext &C)
const {
1107 if (!C.getAnalysisManager().getAnalyzerOptions().MayInlineCXXAllocator)
1108 processNewAllocation(NE, C, C.getSVal(NE));
1112 CheckerContext &C)
const {
1114 processNewAllocation(NE, C,
Target);
1126 SValBuilder &svalBuilder = C.getSValBuilder();
1128 const SubRegion *Region;
1131 ElementCount = C.getSVal(SizeExpr);
1134 Region = Target.getAsRegion()
1135 ->getAs<SubRegion>()
1137 ->getAs<SubRegion>();
1139 ElementCount = svalBuilder.makeIntVal(1,
true);
1140 Region = Target.getAsRegion()->getAs<SubRegion>();
1149 if (ElementCount.getAs<NonLoc>()) {
1150 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1152 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1153 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1154 svalBuilder.makeArrayIndex(TypeSize.
getQuantity()),
1155 svalBuilder.getArrayIndexType());
1156 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1157 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1158 State =
State->assume(extentMatchesSize,
true);
1164 CheckerContext &C)
const {
1166 if (!ChecksEnabled[CK_NewDeleteChecker])
1174 bool ReleasedAllocated;
1176 false, ReleasedAllocated);
1178 C.addTransition(State);
1188 return FirstSlot ==
"dataWithBytesNoCopy" ||
1189 FirstSlot ==
"initWithBytesNoCopy" ||
1190 FirstSlot ==
"initWithCharactersNoCopy";
1199 return !Call.getArgSVal(
i).isZeroConstant();
1204 void MallocChecker::checkPostObjCMessage(
const ObjCMethodCall &Call,
1205 CheckerContext &C)
const {
1216 bool ReleasedAllocatedMemory;
1219 true, ReleasedAllocatedMemory,
1222 C.addTransition(State);
1226 MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
const CallExpr *CE,
1227 const OwnershipAttr *Att,
1232 if (Att->getModule() != II_malloc)
1235 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1237 return MallocMemAux(C, CE, CE->
getArg(I->getASTIndex()), UndefinedVal(),
1240 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1245 const Expr *SizeEx, SVal Init,
1251 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init,
State, Family);
1256 SVal Size, SVal Init,
1269 unsigned Count = C.blockCount();
1270 SValBuilder &svalBuilder = C.getSValBuilder();
1271 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1272 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1273 .castAs<DefinedSVal>();
1274 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1277 State = State->bindDefaultInitial(RetVal, Init, LCtx);
1280 const SymbolicRegion *R =
1281 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1285 Size.getAs<DefinedOrUnknownSVal>()) {
1286 SValBuilder &svalBuilder = C.getSValBuilder();
1287 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1288 DefinedOrUnknownSVal extentMatchesSize =
1289 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1291 State = State->assume(extentMatchesSize,
true);
1295 return MallocUpdateRefState(C, CE, State, Family);
1298 ProgramStateRef MallocChecker::MallocUpdateRefState(CheckerContext &C,
1308 RetVal = C.getSVal(E);
1311 if (!RetVal->getAs<Loc>())
1314 SymbolRef Sym = RetVal->getAsLocSymbol();
1320 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1325 const OwnershipAttr *Att,
1330 if (Att->getModule() != II_malloc)
1333 bool ReleasedAllocated =
false;
1335 for (
const auto &Arg : Att->args()) {
1337 C, CE, State, Arg.getASTIndex(),
1338 Att->getOwnKind() == OwnershipAttr::Holds, ReleasedAllocated);
1350 bool &ReleasedAllocated,
1351 bool ReturnsNullOnFailure)
const {
1358 return FreeMemAux(C, CE->
getArg(Num), CE,
State, Hold,
1359 ReleasedAllocated, ReturnsNullOnFailure);
1366 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
1368 assert(*Ret &&
"We should not store the null return symbol");
1369 ConstraintManager &CMgr = State->getConstraintManager();
1370 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1371 RetStatusSymbol = *Ret;
1372 return FreeFailed.isConstrainedTrue();
1378 const Stmt *S)
const {
1382 if (
const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1390 if (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Any))
1393 if (isStandardNewDelete(FD, Ctx)) {
1395 if (Kind == OO_New || Kind == OO_Delete)
1397 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1398 return AF_CXXNewArray;
1401 if (isCMemFunction(FD, Ctx, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
1402 return AF_IfNameIndex;
1404 if (isCMemFunction(FD, Ctx, AF_Alloca, MemoryOperationKind::MOK_Any))
1410 if (
const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1411 return NE->
isArray() ? AF_CXXNewArray : AF_CXXNew;
1414 return DE->
isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1416 if (isa<ObjCMessageExpr>(S))
1422 bool MallocChecker::printAllocDeallocName(raw_ostream &os, CheckerContext &C,
1423 const Expr *E)
const {
1424 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1431 if (!FD->isOverloadedOperator())
1437 if (Msg->isInstanceMessage())
1441 Msg->getSelector().
print(os);
1445 if (
const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1462 void MallocChecker::printExpectedAllocName(raw_ostream &os, CheckerContext &C,
1463 const Expr *E)
const {
1467 case AF_Malloc: os <<
"malloc()";
return;
1468 case AF_CXXNew: os <<
"'new'";
return;
1469 case AF_CXXNewArray: os <<
"'new[]'";
return;
1470 case AF_IfNameIndex: os <<
"'if_nameindex()'";
return;
1471 case AF_InnerBuffer: os <<
"container-specific allocator";
return;
1473 case AF_None: llvm_unreachable(
"not a deallocation expression");
1477 void MallocChecker::printExpectedDeallocName(raw_ostream &os,
1480 case AF_Malloc: os <<
"free()";
return;
1481 case AF_CXXNew: os <<
"'delete'";
return;
1482 case AF_CXXNewArray: os <<
"'delete[]'";
return;
1483 case AF_IfNameIndex: os <<
"'if_freenameindex()'";
return;
1484 case AF_InnerBuffer: os <<
"container-specific deallocator";
return;
1486 case AF_None: llvm_unreachable(
"suspicious argument");
1491 const Expr *ArgExpr,
1492 const Expr *ParentExpr,
1495 bool &ReleasedAllocated,
1496 bool ReturnsNullOnFailure)
const {
1501 SVal ArgVal = C.getSVal(ArgExpr);
1502 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1504 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1507 if (!location.getAs<Loc>())
1512 std::tie(notNullState, nullState) =
State->assume(location);
1513 if (nullState && !notNullState)
1518 if (ArgVal.isUnknownOrUndef())
1521 const MemRegion *R = ArgVal.getAsRegion();
1530 R = R->StripCasts();
1533 if (isa<BlockDataRegion>(R)) {
1538 const MemSpaceRegion *MS = R->getMemorySpace();
1542 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1551 if (isa<AllocaRegion>(R))
1559 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1565 SymbolRef SymBase = SrBase->getSymbol();
1566 const RefState *RsBase =
State->get<RegionState>(SymBase);
1567 SymbolRef PreviousRetStatusSymbol =
nullptr;
1572 if (RsBase->getAllocationFamily() == AF_Alloca) {
1578 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1580 ReportDoubleFree(C, ParentExpr->
getSourceRange(), RsBase->isReleased(),
1581 SymBase, PreviousRetStatusSymbol);
1586 }
else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1587 RsBase->isEscaped()) {
1590 bool DeallocMatchesAlloc =
1591 RsBase->getAllocationFamily() == getAllocationFamily(C, ParentExpr);
1592 if (!DeallocMatchesAlloc) {
1594 ParentExpr, RsBase, SymBase, Hold);
1600 RegionOffset
Offset = R->getAsOffset();
1601 if (Offset.isValid() &&
1602 !Offset.hasSymbolicOffset() &&
1603 Offset.getOffset() != 0) {
1604 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1605 ReportOffsetFree(C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr,
1612 if (SymBase->getType()->isFunctionPointerType()) {
1613 ReportFunctionPointerFree(C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr);
1617 ReleasedAllocated = (RsBase !=
nullptr) && (RsBase->isAllocated() ||
1618 RsBase->isAllocatedOfSizeZero());
1621 State =
State->remove<FreeReturnValue>(SymBase);
1625 if (ReturnsNullOnFailure) {
1626 SVal RetVal = C.getSVal(ParentExpr);
1627 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1628 if (RetStatusSymbol) {
1629 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1630 State =
State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1635 : getAllocationFamily(C, ParentExpr);
1638 return State->set<RegionState>(SymBase,
1639 RefState::getRelinquished(Family,
1642 return State->set<RegionState>(SymBase,
1643 RefState::getReleased(Family, ParentExpr));
1648 bool IsALeakCheck)
const {
1652 case AF_IfNameIndex: {
1653 if (ChecksEnabled[CK_MallocChecker])
1654 return CK_MallocChecker;
1658 case AF_CXXNewArray: {
1660 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1661 return CK_NewDeleteLeaksChecker;
1664 if (ChecksEnabled[CK_NewDeleteChecker])
1665 return CK_NewDeleteChecker;
1669 case AF_InnerBuffer: {
1670 if (ChecksEnabled[CK_InnerPointerChecker])
1671 return CK_InnerPointerChecker;
1675 llvm_unreachable(
"no family");
1678 llvm_unreachable(
"unhandled family");
1682 MallocChecker::getCheckIfTracked(CheckerContext &C,
1683 const Stmt *AllocDeallocStmt,
1684 bool IsALeakCheck)
const {
1685 return getCheckIfTracked(getAllocationFamily(C, AllocDeallocStmt),
1690 MallocChecker::getCheckIfTracked(CheckerContext &C,
SymbolRef Sym,
1691 bool IsALeakCheck)
const {
1692 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1693 return CK_MallocChecker;
1695 const RefState *RS = C.getState()->get<RegionState>(Sym);
1697 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1700 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal
V) {
1702 os <<
"an integer (" << IntVal->getValue() <<
")";
1704 os <<
"a constant address (" << ConstAddr->getValue() <<
")";
1706 os <<
"the address of the label '" <<
Label->getLabel()->getName() <<
"'";
1713 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1714 const MemRegion *MR) {
1715 switch (MR->getKind()) {
1716 case MemRegion::FunctionCodeRegionKind: {
1717 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1719 os <<
"the address of the function '" << *FD <<
'\'';
1721 os <<
"the address of a function";
1724 case MemRegion::BlockCodeRegionKind:
1727 case MemRegion::BlockDataRegionKind:
1732 const MemSpaceRegion *MS = MR->getMemorySpace();
1734 if (isa<StackLocalsSpaceRegion>(MS)) {
1735 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1743 os <<
"the address of the local variable '" << VD->
getName() <<
"'";
1745 os <<
"the address of a local stack variable";
1749 if (isa<StackArgumentsSpaceRegion>(MS)) {
1750 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1758 os <<
"the address of the parameter '" << VD->
getName() <<
"'";
1760 os <<
"the address of a parameter";
1764 if (isa<GlobalsSpaceRegion>(MS)) {
1765 const VarRegion *VR = dyn_cast<VarRegion>(MR);
1773 if (VD->isStaticLocal())
1774 os <<
"the address of the static variable '" << VD->
getName() <<
"'";
1776 os <<
"the address of the global variable '" << VD->getName() <<
"'";
1778 os <<
"the address of a global variable";
1787 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
1789 const Expr *DeallocExpr)
const {
1791 if (!ChecksEnabled[CK_MallocChecker] &&
1792 !ChecksEnabled[CK_NewDeleteChecker])
1796 getCheckIfTracked(C, DeallocExpr);
1797 if (!CheckKind.hasValue())
1800 if (ExplodedNode *N = C.generateErrorNode()) {
1801 if (!BT_BadFree[*CheckKind])
1802 BT_BadFree[*CheckKind].reset(
new BugType(
1806 llvm::raw_svector_ostream os(buf);
1808 const MemRegion *MR = ArgVal.getAsRegion();
1809 while (
const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
1810 MR = ER->getSuperRegion();
1812 os <<
"Argument to ";
1813 if (!printAllocDeallocName(os, C, DeallocExpr))
1814 os <<
"deallocator";
1817 bool Summarized = MR ? SummarizeRegion(os, MR)
1818 : SummarizeValue(os, ArgVal);
1820 os <<
", which is not memory allocated by ";
1822 os <<
"not memory allocated by ";
1824 printExpectedAllocName(os, C, DeallocExpr);
1826 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], os.str(), N);
1827 R->markInteresting(MR);
1829 C.emitReport(std::move(R));
1833 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
1838 if (ChecksEnabled[CK_MallocChecker])
1839 CheckKind = CK_MallocChecker;
1840 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
1841 CheckKind = CK_MismatchedDeallocatorChecker;
1845 if (ExplodedNode *N = C.generateErrorNode()) {
1846 if (!BT_FreeAlloca[*CheckKind])
1847 BT_FreeAlloca[*CheckKind].reset(
new BugType(
1850 auto R = llvm::make_unique<BugReport>(
1851 *BT_FreeAlloca[*CheckKind],
1852 "Memory allocated by alloca() should not be deallocated", N);
1853 R->markInteresting(ArgVal.getAsRegion());
1855 C.emitReport(std::move(R));
1859 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
1861 const Expr *DeallocExpr,
1864 bool OwnershipTransferred)
const {
1866 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
1869 if (ExplodedNode *N = C.generateErrorNode()) {
1870 if (!BT_MismatchedDealloc)
1871 BT_MismatchedDealloc.reset(
1872 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
1876 llvm::raw_svector_ostream os(buf);
1878 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
1880 llvm::raw_svector_ostream AllocOs(AllocBuf);
1882 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
1884 if (OwnershipTransferred) {
1885 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1886 os << DeallocOs.str() <<
" cannot";
1890 os <<
" take ownership of memory";
1892 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1893 os <<
" allocated by " << AllocOs.str();
1896 if (printAllocDeallocName(AllocOs, C, AllocExpr))
1897 os <<
" allocated by " << AllocOs.str();
1899 os <<
" should be deallocated by ";
1900 printExpectedDeallocName(os, RS->getAllocationFamily());
1902 if (printAllocDeallocName(DeallocOs, C, DeallocExpr))
1903 os <<
", not " << DeallocOs.str();
1906 auto R = llvm::make_unique<BugReport>(*BT_MismatchedDealloc, os.str(), N);
1907 R->markInteresting(Sym);
1909 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
1910 C.emitReport(std::move(R));
1914 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
1916 const Expr *AllocExpr)
const {
1919 if (!ChecksEnabled[CK_MallocChecker] &&
1920 !ChecksEnabled[CK_NewDeleteChecker])
1924 getCheckIfTracked(C, AllocExpr);
1925 if (!CheckKind.hasValue())
1928 ExplodedNode *N = C.generateErrorNode();
1932 if (!BT_OffsetFree[*CheckKind])
1933 BT_OffsetFree[*CheckKind].reset(
new BugType(
1937 llvm::raw_svector_ostream os(buf);
1939 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
1941 const MemRegion *MR = ArgVal.getAsRegion();
1942 assert(MR &&
"Only MemRegion based symbols can have offset free errors");
1944 RegionOffset
Offset = MR->getAsOffset();
1945 assert((Offset.isValid() &&
1946 !Offset.hasSymbolicOffset() &&
1947 Offset.getOffset() != 0) &&
1948 "Only symbols with a valid offset can have offset free errors");
1950 int offsetBytes = Offset.getOffset() / C.getASTContext().
getCharWidth();
1952 os <<
"Argument to ";
1953 if (!printAllocDeallocName(os, C, DeallocExpr))
1954 os <<
"deallocator";
1955 os <<
" is offset by " 1958 << ((
abs(offsetBytes) > 1) ?
"bytes" :
"byte")
1959 <<
" from the start of ";
1960 if (AllocExpr && printAllocDeallocName(AllocNameOs, C, AllocExpr))
1961 os <<
"memory allocated by " << AllocNameOs.str();
1963 os <<
"allocated memory";
1965 auto R = llvm::make_unique<BugReport>(*BT_OffsetFree[*CheckKind], os.str(), N);
1966 R->markInteresting(MR->getBaseRegion());
1968 C.emitReport(std::move(R));
1971 void MallocChecker::ReportUseAfterFree(CheckerContext &C,
SourceRange Range,
1974 if (!ChecksEnabled[CK_MallocChecker] &&
1975 !ChecksEnabled[CK_NewDeleteChecker] &&
1976 !ChecksEnabled[CK_InnerPointerChecker])
1980 if (!CheckKind.hasValue())
1983 if (ExplodedNode *N = C.generateErrorNode()) {
1984 if (!BT_UseFree[*CheckKind])
1985 BT_UseFree[*CheckKind].reset(
new BugType(
1989 C.getState()->get<RegionState>(Sym)->getAllocationFamily();
1991 auto R = llvm::make_unique<BugReport>(*BT_UseFree[*CheckKind],
1992 AF == AF_InnerBuffer
1993 ?
"Inner pointer of container used after re/deallocation" 1994 :
"Use of memory after it is freed",
1997 R->markInteresting(Sym);
1999 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2001 if (AF == AF_InnerBuffer)
2004 C.emitReport(std::move(R));
2008 void MallocChecker::ReportDoubleFree(CheckerContext &C,
SourceRange Range,
2012 if (!ChecksEnabled[CK_MallocChecker] &&
2013 !ChecksEnabled[CK_NewDeleteChecker])
2017 if (!CheckKind.hasValue())
2020 if (ExplodedNode *N = C.generateErrorNode()) {
2021 if (!BT_DoubleFree[*CheckKind])
2022 BT_DoubleFree[*CheckKind].reset(
new BugType(
2025 auto R = llvm::make_unique<BugReport>(
2026 *BT_DoubleFree[*CheckKind],
2027 (Released ?
"Attempt to free released memory" 2028 :
"Attempt to free non-owned memory"),
2031 R->markInteresting(Sym);
2033 R->markInteresting(PrevSym);
2034 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2035 C.emitReport(std::move(R));
2039 void MallocChecker::ReportDoubleDelete(CheckerContext &C,
SymbolRef Sym)
const {
2041 if (!ChecksEnabled[CK_NewDeleteChecker])
2045 if (!CheckKind.hasValue())
2048 if (ExplodedNode *N = C.generateErrorNode()) {
2049 if (!BT_DoubleDelete)
2050 BT_DoubleDelete.reset(
new BugType(CheckNames[CK_NewDeleteChecker],
2054 auto R = llvm::make_unique<BugReport>(
2055 *BT_DoubleDelete,
"Attempt to delete released memory", N);
2057 R->markInteresting(Sym);
2058 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2059 C.emitReport(std::move(R));
2063 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2067 if (!ChecksEnabled[CK_MallocChecker] &&
2068 !ChecksEnabled[CK_NewDeleteChecker])
2073 if (!CheckKind.hasValue())
2076 if (ExplodedNode *N = C.generateErrorNode()) {
2077 if (!BT_UseZerroAllocated[*CheckKind])
2078 BT_UseZerroAllocated[*CheckKind].reset(
2079 new BugType(CheckNames[*CheckKind],
"Use of zero allocated",
2082 auto R = llvm::make_unique<BugReport>(*BT_UseZerroAllocated[*CheckKind],
2083 "Use of zero-allocated memory", N);
2087 R->markInteresting(Sym);
2088 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym));
2090 C.emitReport(std::move(R));
2094 void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2096 const Expr *FreeExpr)
const {
2097 if (!ChecksEnabled[CK_MallocChecker])
2101 if (!CheckKind.hasValue())
2104 if (ExplodedNode *N = C.generateErrorNode()) {
2105 if (!BT_BadFree[*CheckKind])
2106 BT_BadFree[*CheckKind].reset(
new BugType(
2110 llvm::raw_svector_ostream Os(Buf);
2112 const MemRegion *MR = ArgVal.getAsRegion();
2113 while (
const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2114 MR = ER->getSuperRegion();
2116 Os <<
"Argument to ";
2117 if (!printAllocDeallocName(Os, C, FreeExpr))
2118 Os <<
"deallocator";
2120 Os <<
" is a function pointer";
2122 auto R = llvm::make_unique<BugReport>(*BT_BadFree[*CheckKind], Os.str(), N);
2123 R->markInteresting(MR);
2125 C.emitReport(std::move(R));
2133 bool SuffixWithN)
const {
2143 SVal Arg0Val = C.getSVal(arg0Expr);
2144 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2146 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2148 SValBuilder &svalBuilder = C.getSValBuilder();
2150 DefinedOrUnknownSVal PtrEQ =
2151 svalBuilder.evalEQ(
State, arg0Val, svalBuilder.makeNull());
2157 SVal TotalSize = C.getSVal(Arg1);
2159 TotalSize = evalMulForBufferSize(C, Arg1, CE->
getArg(2));
2160 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2164 DefinedOrUnknownSVal SizeZero =
2165 svalBuilder.evalEQ(
State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2166 svalBuilder.makeIntValWithPtrWidth(0,
false));
2169 std::tie(StatePtrIsNull, StatePtrNotNull) =
State->assume(PtrEQ);
2171 std::tie(StateSizeIsZero, StateSizeNotZero) =
State->assume(SizeZero);
2174 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2175 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2179 if (PrtIsNull && !SizeIsZero) {
2181 UndefinedVal(), StatePtrIsNull);
2185 if (PrtIsNull && SizeIsZero)
2190 SymbolRef FromPtr = arg0Val.getAsSymbol();
2191 SVal RetVal = C.getSVal(CE);
2193 if (!FromPtr || !ToPtr)
2196 bool ReleasedAllocated =
false;
2201 false, ReleasedAllocated)){
2211 FreeMemAux(C, CE,
State, 0,
false, ReleasedAllocated)) {
2214 UnknownVal(), stateFree);
2220 Kind = RPIsFreeOnFailure;
2221 else if (!ReleasedAllocated)
2222 Kind = RPDoNotTrackAfterFailure;
2226 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2227 ReallocPair(FromPtr, Kind));
2229 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2230 return stateRealloc;
2243 SValBuilder &svalBuilder = C.getSValBuilder();
2244 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2245 SVal TotalSize = evalMulForBufferSize(C, CE->
getArg(0), CE->
getArg(1));
2247 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2251 MallocChecker::getAllocationSite(
const ExplodedNode *N,
SymbolRef Sym,
2252 CheckerContext &C)
const {
2256 const ExplodedNode *AllocNode = N;
2257 const MemRegion *ReferenceRegion =
nullptr;
2261 if (!State->get<RegionState>(Sym))
2266 if (!ReferenceRegion) {
2267 if (
const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2268 SVal Val = State->getSVal(MR);
2269 if (Val.getAsLocSymbol() == Sym) {
2270 const VarRegion* VR = MR->getBaseRegion()->getAs<VarRegion>();
2275 ReferenceRegion = MR;
2283 if (NContext == LeakContext ||
2286 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2289 return LeakInfo(AllocNode, ReferenceRegion);
2292 void MallocChecker::reportLeak(
SymbolRef Sym, ExplodedNode *N,
2293 CheckerContext &C)
const {
2295 if (!ChecksEnabled[CK_MallocChecker] &&
2296 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2299 const RefState *RS = C.getState()->get<RegionState>(Sym);
2300 assert(RS &&
"cannot leak an untracked symbol");
2303 if (Family == AF_Alloca)
2307 CheckKind = getCheckIfTracked(Family,
true);
2309 if (!CheckKind.hasValue())
2313 if (!BT_Leak[*CheckKind]) {
2319 BT_Leak[*CheckKind].reset(
new BugType(CheckNames[*CheckKind],
"Memory leak",
2327 PathDiagnosticLocation LocUsedForUniqueing;
2328 const ExplodedNode *AllocNode =
nullptr;
2329 const MemRegion *Region =
nullptr;
2330 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2335 C.getSourceManager(),
2336 AllocNode->getLocationContext());
2339 llvm::raw_svector_ostream os(buf);
2340 if (Region && Region->canPrintPretty()) {
2341 os <<
"Potential leak of memory pointed to by ";
2342 Region->printPretty(os);
2344 os <<
"Potential memory leak";
2347 auto R = llvm::make_unique<BugReport>(
2348 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2349 AllocNode->getLocationContext()->getDecl());
2350 R->markInteresting(Sym);
2351 R->addVisitor(llvm::make_unique<MallocBugVisitor>(Sym,
true));
2352 C.emitReport(std::move(R));
2355 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2356 CheckerContext &C)
const 2359 RegionStateTy OldRS = state->get<RegionState>();
2360 RegionStateTy::Factory &F = state->get_context<RegionState>();
2362 RegionStateTy RS = OldRS;
2364 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2365 if (SymReaper.isDead(I->first)) {
2366 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2367 Errors.push_back(I->first);
2369 RS = F.remove(RS, I->first);
2375 assert(state->get<ReallocPairs>() ==
2376 C.getState()->get<ReallocPairs>());
2377 assert(state->get<FreeReturnValue>() ==
2378 C.getState()->get<FreeReturnValue>());
2383 ReallocPairsTy RP = state->get<ReallocPairs>();
2384 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2385 if (SymReaper.isDead(I->first) ||
2386 SymReaper.isDead(I->second.ReallocatedSym)) {
2387 state = state->remove<ReallocPairs>(I->first);
2392 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2393 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2394 if (SymReaper.isDead(I->first) ||
2395 SymReaper.isDead(I->second)) {
2396 state = state->remove<FreeReturnValue>(I->first);
2401 ExplodedNode *N = C.getPredecessor();
2402 if (!Errors.empty()) {
2403 static CheckerProgramPointTag Tag(
"MallocChecker",
"DeadSymbolsLeak");
2404 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2407 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2408 reportLeak(*I, N, C);
2413 C.addTransition(state->set<RegionState>(RS), N);
2416 void MallocChecker::checkPreCall(
const CallEvent &Call,
2417 CheckerContext &C)
const {
2420 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2421 if (!Sym || checkDoubleDelete(Sym, C))
2432 if (ChecksEnabled[CK_MallocChecker] &&
2433 (isCMemFunction(FD, Ctx, AF_Malloc, MemoryOperationKind::MOK_Free) ||
2434 isCMemFunction(FD, Ctx, AF_IfNameIndex,
2435 MemoryOperationKind::MOK_Free)))
2441 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2442 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2447 for (
unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2448 SVal ArgSVal = Call.getArgSVal(I);
2449 if (ArgSVal.getAs<Loc>()) {
2453 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2459 void MallocChecker::checkPreStmt(
const ReturnStmt *S,
2460 CheckerContext &C)
const {
2461 checkEscapeOnReturn(S, C);
2467 void MallocChecker::checkEndFunction(
const ReturnStmt *S,
2468 CheckerContext &C)
const {
2469 checkEscapeOnReturn(S, C);
2472 void MallocChecker::checkEscapeOnReturn(
const ReturnStmt *S,
2473 CheckerContext &C)
const {
2483 SVal RetVal = C.getSVal(E);
2489 if (
const MemRegion *MR = RetVal.getAsRegion())
2490 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2491 if (
const SymbolicRegion *BMR =
2492 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2493 Sym = BMR->getSymbol();
2497 checkUseAfterFree(Sym, C, E);
2503 void MallocChecker::checkPostStmt(
const BlockExpr *BE,
2504 CheckerContext &C)
const {
2512 const BlockDataRegion *R =
2513 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2515 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2516 E = R->referenced_vars_end();
2523 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2525 for ( ; I != E; ++I) {
2526 const VarRegion *VR = I.getCapturedRegion();
2527 if (VR->getSuperRegion() == R) {
2528 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2530 Regions.push_back(VR);
2534 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
2535 C.addTransition(state);
2538 bool MallocChecker::isReleased(
SymbolRef Sym, CheckerContext &C)
const {
2540 const RefState *RS = C.getState()->get<RegionState>(Sym);
2541 return (RS && RS->isReleased());
2544 bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
2545 const CallExpr *CE, CheckerContext &C)
const {
2549 StringRef FunctionStr =
"";
2550 if (
const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
2552 if (Body->getBeginLoc().isValid())
2556 C.getSourceManager(), C.getLangOpts());
2559 if (!FunctionStr.contains(
"__isl_"))
2565 if (
SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
2566 if (
const RefState *RS = State->get<RegionState>(Sym))
2567 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
2569 C.addTransition(State);
2573 bool MallocChecker::checkUseAfterFree(
SymbolRef Sym, CheckerContext &C,
2574 const Stmt *S)
const {
2576 if (isReleased(Sym, C)) {
2584 void MallocChecker::checkUseZeroAllocated(
SymbolRef Sym, CheckerContext &C,
2585 const Stmt *S)
const {
2588 if (
const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2589 if (RS->isAllocatedOfSizeZero())
2590 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2592 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2597 bool MallocChecker::checkDoubleDelete(
SymbolRef Sym, CheckerContext &C)
const {
2599 if (isReleased(Sym, C)) {
2600 ReportDoubleDelete(C, Sym);
2607 void MallocChecker::checkLocation(SVal l,
bool isLoad,
const Stmt *S,
2608 CheckerContext &C)
const {
2611 checkUseAfterFree(Sym, C, S);
2612 checkUseZeroAllocated(Sym, C, S);
2620 bool Assumption)
const {
2621 RegionStateTy RS =
state->get<RegionState>();
2622 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2624 ConstraintManager &CMgr =
state->getConstraintManager();
2625 ConditionTruthVal AllocFailed = CMgr.isNull(
state, I.getKey());
2626 if (AllocFailed.isConstrainedTrue())
2627 state =
state->remove<RegionState>(I.getKey());
2632 ReallocPairsTy RP =
state->get<ReallocPairs>();
2633 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2635 ConstraintManager &CMgr =
state->getConstraintManager();
2636 ConditionTruthVal AllocFailed = CMgr.isNull(
state, I.getKey());
2637 if (!AllocFailed.isConstrainedTrue())
2640 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2641 if (
const RefState *RS =
state->get<RegionState>(ReallocSym)) {
2642 if (RS->isReleased()) {
2643 if (I.getData().Kind == RPToBeFreedAfterFailure)
2645 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2646 else if (I.getData().Kind == RPDoNotTrackAfterFailure)
2647 state =
state->remove<RegionState>(ReallocSym);
2649 assert(I.getData().Kind == RPIsFreeOnFailure);
2652 state = state->remove<ReallocPairs>(I.getKey());
2658 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2663 EscapingSymbol =
nullptr;
2669 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2673 if (
const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2676 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2689 return *FreeWhenDone;
2695 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2696 if (FirstSlot.endswith(
"NoCopy"))
2703 if (FirstSlot.startswith(
"addPointer") ||
2704 FirstSlot.startswith(
"insertPointer") ||
2705 FirstSlot.startswith(
"replacePointer") ||
2706 FirstSlot.equals(
"valueWithPointer")) {
2713 if (Msg->getMethodFamily() ==
OMF_init) {
2714 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2724 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
2732 if (isMemFunction(FD, ASTC))
2736 if (!Call->isInSystemHeader())
2743 StringRef FName = II->
getName();
2747 if (FName.endswith(
"NoCopy")) {
2751 for (
unsigned i = 1;
i < Call->getNumArgs(); ++
i) {
2752 const Expr *ArgE = Call->getArgExpr(
i)->IgnoreParenCasts();
2753 if (
const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
2754 StringRef DeallocatorName = DE->getFoundDecl()->getName();
2755 if (DeallocatorName ==
"kCFAllocatorNull")
2766 if (FName ==
"funopen")
2767 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
2773 if (FName ==
"setbuf" || FName ==
"setbuffer" ||
2774 FName ==
"setlinebuf" || FName ==
"setvbuf") {
2775 if (Call->getNumArgs() >= 1) {
2776 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
2777 if (
const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
2778 if (
const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
2779 if (D->getCanonicalDecl()->getName().find(
"std") != StringRef::npos)
2789 if (FName ==
"CGBitmapContextCreate" ||
2790 FName ==
"CGBitmapContextCreateWithData" ||
2791 FName ==
"CVPixelBufferCreateWithBytes" ||
2792 FName ==
"CVPixelBufferCreateWithPlanarBytes" ||
2793 FName ==
"OSAtomicEnqueue") {
2797 if (FName ==
"postEvent" &&
2802 if (FName ==
"postEvent" &&
2807 if (FName ==
"connectImpl" &&
2816 if (Call->argumentsMayEscape())
2829 return (RS->getAllocationFamily() == AF_CXXNewArray ||
2830 RS->getAllocationFamily() == AF_CXXNew);
2837 return checkPointerEscapeAux(
State, Escaped, Call, Kind, &
retTrue);
2844 return checkPointerEscapeAux(
State, Escaped, Call, Kind,
2852 bool(*CheckRefState)(
const RefState*))
const {
2857 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call,
State,
2863 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
2868 if (EscapingSymbol && EscapingSymbol != sym)
2871 if (
const RefState *RS =
State->get<RegionState>(sym)) {
2872 if ((RS->isAllocated() || RS->isAllocatedOfSizeZero()) &&
2873 CheckRefState(RS)) {
2874 State =
State->set<RegionState>(sym, RefState::getEscaped(RS));
2883 ReallocPairsTy currMap = currState->get<ReallocPairs>();
2884 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
2886 for (ReallocPairsTy::iterator I = prevMap.begin(), E = prevMap.end();
2889 if (!currMap.lookup(sym))
2898 StringRef N = II->getName();
2899 if (N.contains_lower(
"ptr") || N.contains_lower(
"pointer")) {
2900 if (N.contains_lower(
"ref") || N.contains_lower(
"cnt") ||
2901 N.contains_lower(
"intrusive") || N.contains_lower(
"shared")) {
2909 std::shared_ptr<PathDiagnosticPiece> MallocChecker::MallocBugVisitor::VisitNode(
2910 const ExplodedNode *N, BugReporterContext &BRC, BugReport &BR) {
2915 const RefState *RS = state->get<RegionState>(Sym);
2916 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
2921 if (!S && (!RS || RS->getAllocationFamily() != AF_InnerBuffer))
2933 if (ReleaseDestructorLC) {
2934 if (
const auto *AE = dyn_cast<AtomicExpr>(S)) {
2936 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
2937 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
2938 if (ReleaseDestructorLC == CurrentLC ||
2939 ReleaseDestructorLC->
isParentOf(CurrentLC)) {
2940 BR.markInvalid(getTag(), S);
2951 StackHintGeneratorForSymbol *StackHint =
nullptr;
2953 llvm::raw_svector_ostream
OS(Buf);
2955 if (Mode == Normal) {
2956 if (isAllocated(RS, RSPrev, S)) {
2957 Msg =
"Memory is allocated";
2958 StackHint =
new StackHintGeneratorForSymbol(Sym,
2959 "Returned allocated memory");
2960 }
else if (isReleased(RS, RSPrev, S)) {
2961 const auto Family = RS->getAllocationFamily();
2966 case AF_CXXNewArray:
2967 case AF_IfNameIndex:
2968 Msg =
"Memory is released";
2969 StackHint =
new StackHintGeneratorForSymbol(Sym,
2970 "Returning; memory was released");
2972 case AF_InnerBuffer: {
2973 const MemRegion *ObjRegion =
2975 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
2976 QualType ObjTy = TypedRegion->getValueType();
2977 OS <<
"Inner buffer of '" << ObjTy.getAsString() <<
"' ";
2980 OS <<
"deallocated by call to destructor";
2981 StackHint =
new StackHintGeneratorForSymbol(Sym,
2982 "Returning; inner buffer was deallocated");
2984 OS <<
"reallocated by call to '";
2985 const Stmt *S = RS->getStmt();
2986 if (
const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
2987 OS << MemCallE->getMethodDecl()->getNameAsString();
2988 }
else if (
const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
2989 OS << OpCallE->getDirectCallee()->getNameAsString();
2990 }
else if (
const auto *CallE = dyn_cast<CallExpr>(S)) {
2991 auto &CEMgr = BRC.getStateManager().getCallEventManager();
2992 CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
2993 const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl());
2994 OS << (D ? D->getNameAsString() :
"unknown");
2997 StackHint =
new StackHintGeneratorForSymbol(Sym,
2998 "Returning; inner buffer was reallocated");
3004 llvm_unreachable(
"Unhandled allocation family!");
3010 bool FoundAnyDestructor =
false;
3012 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3017 BR.markInvalid(getTag(), DD);
3018 }
else if (!FoundAnyDestructor) {
3019 assert(!ReleaseDestructorLC &&
3020 "There can be only one release point!");
3026 ReleaseDestructorLC = LC->getStackFrame();
3032 FoundAnyDestructor =
true;
3036 }
else if (isRelinquished(RS, RSPrev, S)) {
3037 Msg =
"Memory ownership is transferred";
3038 StackHint =
new StackHintGeneratorForSymbol(Sym,
"");
3039 }
else if (isReallocFailedCheck(RS, RSPrev, S)) {
3040 Mode = ReallocationFailed;
3041 Msg =
"Reallocation failed";
3042 StackHint =
new StackHintGeneratorForReallocationFailed(Sym,
3043 "Reallocation failed");
3047 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3048 "We only support one failed realloc at a time.");
3049 BR.markInteresting(sym);
3050 FailedReallocSymbol = sym;
3055 }
else if (Mode == ReallocationFailed) {
3056 assert(FailedReallocSymbol &&
"No symbol to look for.");
3059 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3061 Msg =
"Attempt to reallocate memory";
3062 StackHint =
new StackHintGeneratorForSymbol(Sym,
3063 "Returned reallocated memory");
3064 FailedReallocSymbol =
nullptr;
3074 PathDiagnosticLocation Pos;
3076 assert(RS->getAllocationFamily() == AF_InnerBuffer);
3080 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3081 BRC.getSourceManager());
3083 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3084 N->getLocationContext());
3087 return std::make_shared<PathDiagnosticEventPiece>(Pos, Msg,
true, StackHint);
3091 const char *NL,
const char *Sep)
const {
3093 RegionStateTy RS =
State->get<RegionState>();
3095 if (!RS.isEmpty()) {
3096 Out << Sep <<
"MallocChecker :" << NL;
3097 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3098 const RefState *RefS =
State->get<RegionState>(I.getKey());
3101 if (!CheckKind.hasValue())
3102 CheckKind = getCheckIfTracked(Family,
true);
3104 I.getKey()->dumpToStream(Out);
3106 I.getData().dump(Out);
3107 if (CheckKind.hasValue())
3108 Out <<
" (" << CheckNames[*CheckKind].
getName() <<
")";
3116 namespace allocation_state {
3121 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3131 MallocChecker *checker = mgr.
getChecker<MallocChecker>();
3132 checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] =
true;
3133 checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3140 checker,
"Optimistic");
3143 bool ento::shouldRegisterDynamicMemoryModeling(
const LangOptions &LO) {
3147 #define REGISTER_CHECKER(name) \ 3148 void ento::register##name(CheckerManager &mgr) { \ 3149 MallocChecker *checker = mgr.getChecker<MallocChecker>(); \ 3150 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \ 3151 checker->CheckNames[MallocChecker::CK_##name] = mgr.getCurrentCheckName(); \ 3154 bool ento::shouldRegister##name(const LangOptions &LO) { \
const BlockDecl * getBlockDecl() const
Represents a function declaration or definition.
Smart pointer class that efficiently represents Objective-C method names.
A (possibly-)qualified type.
const char *const MemoryError
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
bool operator==(CanQual< T > x, CanQual< U > y)
llvm::DenseSet< SymbolRef > InvalidatedSymbols
const SymExpr * SymbolRef
Stmt - This represents one statement.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Defines the SourceManager interface.
static CharSourceRange getTokenRange(SourceRange R)
void registerInnerPointerCheckerAux(CheckerManager &Mgr)
Register the part of MallocChecker connected to InnerPointerChecker.
__DEVICE__ long long abs(long long __n)
FunctionDecl * getOperatorNew() const
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const MemRegion * getContainerObjRegion(ProgramStateRef State, SymbolRef Sym)
'Sym' represents a pointer to the inner buffer of a container object.
Represents a call to a C++ constructor.
const TargetInfo & getTargetInfo() const
constexpr XRayInstrMask Function
Represents a C++ constructor within a class.
bool isConsumedExpr(Expr *E) const
Represents a variable declaration or definition.
bool isParentOf(const LocationContext *LC) const
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call)
One of these records is kept for each identifier that is lexed.
void print(raw_ostream &Out, unsigned Indentation=0, bool PrintInstantiation=false) const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
const CXXConstructExpr * getConstructExpr() const
Returns the CXXConstructExpr from this new-expression, or null.
std::unique_ptr< BugReporterVisitor > getInnerPointerBRVisitor(SymbolRef Sym)
This function provides an additional visitor that augments the bug report with information relevant t...
SourceLocation getBeginLoc() const LLVM_READONLY
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
ArrayRef< ParmVarDecl * > parameters() const
static bool isLocType(QualType T)
Represents any expression that calls an Objective-C method.
Optional< Expr * > getArraySize()
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
FunctionDecl * getOperatorDelete() const
CharUnits - This is an opaque type for sizes expressed in character units.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
const LocationContext * getParent() const
static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD)
static bool didPreviousFreeFail(ProgramStateRef State, SymbolRef Sym, SymbolRef &RetStatusSymbol)
Checks if the previous call to free on the given symbol failed - if free failed, returns true...
CheckName getCurrentCheckName() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a non-static C++ member function call, no matter how it is written.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
This represents one expression.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Represents an implicit call to a C++ destructor.
static bool retTrue(const RefState *RS)
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Represents a C++ destructor within a class.
The pointer has been passed to a function call directly.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
An expression that sends a message to the given Objective-C object or class.
unsigned getNumArgs() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
static const Stmt * getStmt(const ExplodedNode *N)
Given an exploded node, retrieve the statement that should be used for the diagnostic location...
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
CHECKER * registerChecker(AT &&... Args)
Used to register checkers.
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
ASTContext & getASTContext() const LLVM_READONLY
static bool checkIfNewOrNewArrayFamily(const RefState *RS)
QualType getAllocatedType() const
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, ProgramStateRef prevState)
static bool treatUnusedNewEscaped(const CXXNewExpr *NE)
StringRef getName() const
Return the actual identifier string.
virtual const ObjCMessageExpr * getOriginExpr() const
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
Selector getSelector() const
bool getCheckerBooleanOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Interprets an option's string value as a boolean.
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Represents a program point just after an implicit call event.
static std::string getName(const CallEvent &Call)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
static QualType getDeepPointeeType(QualType T)
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
AnalyzerOptions & getAnalyzerOptions()
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
Indicates that the tracking object is a descendant of a referenced-counted OSObject, used in the Darwin kernel.
#define REGISTER_CHECKER(name)
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword...
uint64_t getCharWidth() const
Return the size of the character type, in bits.
static Optional< bool > getFreeWhenDoneArg(const ObjCMethodCall &Call)
const StackFrameContext * getStackFrame() const
ProgramStateRef markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin)
SourceManager & getSourceManager()
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
const Expr * getArgExpr(unsigned Index) const override
static PathDiagnosticLocation createEndOfPath(const ExplodedNode *N, const SourceManager &SM)
Create a location corresponding to the next valid ExplodedNode as end of path location.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
std::string getQualifiedNameAsString() const
A reference to a declared variable, function, enum, etc.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
SourceLocation getLocation() const