63 #include "llvm/ADT/STLExtras.h" 64 #include "llvm/ADT/SmallString.h" 65 #include "llvm/ADT/StringExtras.h" 70 using namespace clang;
90 struct MemFunctionInfoTy;
108 const MemFunctionInfoTy &MemFunctionInfo,
109 CheckerContext &
C,
const Expr *E);
144 : S(s), K(k), Family(family) {
145 assert(family != AF_None);
149 bool isAllocated()
const {
return K == Allocated; }
150 bool isAllocatedOfSizeZero()
const {
return K == AllocatedOfSizeZero; }
151 bool isReleased()
const {
return K == Released; }
152 bool isRelinquished()
const {
return K == Relinquished; }
153 bool isEscaped()
const {
return K == Escaped; }
155 const Stmt *getStmt()
const {
return S; }
158 return K == X.K && S == X.S && Family == X.Family;
162 return RefState(Allocated, s, family);
164 static RefState getAllocatedOfSizeZero(
const RefState *RS) {
165 return RefState(AllocatedOfSizeZero, RS->getStmt(),
166 RS->getAllocationFamily());
169 return RefState(Released, s, family);
172 return RefState(Relinquished, s, family);
174 static RefState getEscaped(
const RefState *RS) {
175 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
178 void Profile(llvm::FoldingSetNodeID &
ID)
const {
181 ID.AddInteger(Family);
184 LLVM_DUMP_METHOD
void dump(raw_ostream &
OS)
const {
186 #define CASE(ID) case ID: OS << #ID; break; 188 CASE(AllocatedOfSizeZero)
195 LLVM_DUMP_METHOD
void dump()
const {
dump(llvm::errs()); }
227 OAR_ToBeFreedAfterFailure,
237 OAR_DoNotTrackAfterFailure
253 : ReallocatedSym(S),
Kind(K) {}
254 void Profile(llvm::FoldingSetNodeID &
ID)
const {
256 ID.AddPointer(ReallocatedSym);
259 return ReallocatedSym == X.ReallocatedSym &&
276 struct MemFunctionInfoTy {
283 DefaultBool ShouldIncludeOwnershipAnnotatedFunctions;
286 mutable IdentifierInfo *II_alloca =
nullptr, *II_win_alloca =
nullptr,
287 *II_malloc =
nullptr, *II_free =
nullptr,
288 *II_realloc =
nullptr, *II_calloc =
nullptr,
289 *II_valloc =
nullptr, *II_reallocf =
nullptr,
290 *II_strndup =
nullptr, *II_strdup =
nullptr,
291 *II_win_strdup =
nullptr, *II_kmalloc =
nullptr,
292 *II_if_nameindex =
nullptr,
293 *II_if_freenameindex =
nullptr, *II_wcsdup =
nullptr,
294 *II_win_wcsdup =
nullptr, *II_g_malloc =
nullptr,
295 *II_g_malloc0 =
nullptr, *II_g_realloc =
nullptr,
296 *II_g_try_malloc =
nullptr,
297 *II_g_try_malloc0 =
nullptr,
298 *II_g_try_realloc =
nullptr, *II_g_free =
nullptr,
299 *II_g_memdup =
nullptr, *II_g_malloc_n =
nullptr,
300 *II_g_malloc0_n =
nullptr, *II_g_realloc_n =
nullptr,
301 *II_g_try_malloc_n =
nullptr,
302 *II_g_try_malloc0_n =
nullptr, *II_kfree =
nullptr,
303 *II_g_try_realloc_n =
nullptr;
330 :
public Checker<check::DeadSymbols, check::PointerEscape,
331 check::ConstPointerEscape, check::PreStmt<ReturnStmt>,
332 check::EndFunction, check::PreCall,
333 check::PostStmt<CallExpr>, check::PostStmt<CXXNewExpr>,
334 check::NewAllocator, check::PreStmt<CXXDeleteExpr>,
335 check::PostStmt<BlockExpr>, check::PostObjCMessage,
336 check::Location, eval::Assume> {
338 MemFunctionInfoTy MemFunctionInfo;
348 CK_NewDeleteLeaksChecker,
349 CK_MismatchedDeallocatorChecker,
350 CK_InnerPointerChecker,
354 using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
356 DefaultBool ChecksEnabled[CK_NumCheckKinds];
357 CheckerNameRef CheckNames[CK_NumCheckKinds];
359 void checkPreCall(
const CallEvent &Call, CheckerContext &C)
const;
360 void checkPostStmt(
const CallExpr *CE, CheckerContext &C)
const;
361 void checkPostStmt(
const CXXNewExpr *
NE, CheckerContext &C)
const;
363 CheckerContext &C)
const;
364 void checkPreStmt(
const CXXDeleteExpr *DE, CheckerContext &C)
const;
365 void checkPostObjCMessage(
const ObjCMethodCall &Call, CheckerContext &C)
const;
366 void checkPostStmt(
const BlockExpr *BE, CheckerContext &C)
const;
367 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C)
const;
368 void checkPreStmt(
const ReturnStmt *S, CheckerContext &C)
const;
369 void checkEndFunction(
const ReturnStmt *S, CheckerContext &C)
const;
371 bool Assumption)
const;
372 void checkLocation(SVal l,
bool isLoad,
const Stmt *S,
373 CheckerContext &C)
const;
385 const char *NL,
const char *Sep)
const override;
388 mutable std::unique_ptr<BugType> BT_DoubleFree[CK_NumCheckKinds];
389 mutable std::unique_ptr<BugType> BT_DoubleDelete;
390 mutable std::unique_ptr<BugType> BT_Leak[CK_NumCheckKinds];
391 mutable std::unique_ptr<BugType> BT_UseFree[CK_NumCheckKinds];
392 mutable std::unique_ptr<BugType> BT_BadFree[CK_NumCheckKinds];
393 mutable std::unique_ptr<BugType> BT_FreeAlloca[CK_NumCheckKinds];
394 mutable std::unique_ptr<BugType> BT_MismatchedDealloc;
395 mutable std::unique_ptr<BugType> BT_OffsetFree[CK_NumCheckKinds];
396 mutable std::unique_ptr<BugType> BT_UseZerroAllocated[CK_NumCheckKinds];
403 void processNewAllocation(
const CXXNewExpr *NE, CheckerContext &C,
415 const unsigned IndexOfSizeArg,
437 const OwnershipAttr* Att,
450 const Expr *SizeEx, SVal Init,
464 SVal Size, SVal Init,
474 performKernelMalloc(
const CallExpr *CE, CheckerContext &C,
495 const OwnershipAttr* Att,
519 bool &IsKnownToBeAllocated,
520 bool ReturnsNullOnFailure =
false)
const;
543 bool Hold,
bool &IsKnownToBeAllocated,
544 bool ReturnsNullOnFailure =
false)
const;
561 bool SuffixWithN =
false)
const;
568 static SVal evalMulForBufferSize(CheckerContext &C,
const Expr *Blocks,
569 const Expr *BlockBytes);
581 bool suppressDeallocationsInSuspiciousContexts(
const CallExpr *CE,
582 CheckerContext &C)
const;
585 bool checkUseAfterFree(
SymbolRef Sym, CheckerContext &C,
const Stmt *S)
const;
589 void checkUseZeroAllocated(
SymbolRef Sym, CheckerContext &C,
590 const Stmt *S)
const;
593 bool checkDoubleDelete(
SymbolRef Sym, CheckerContext &C)
const;
605 bool mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
const CallEvent *Call,
614 bool IsConstPointerEscape)
const;
617 void checkEscapeOnReturn(
const ReturnStmt *S, CheckerContext &C)
const;
624 bool IsALeakCheck =
false)
const;
626 const Stmt *AllocDeallocStmt,
627 bool IsALeakCheck =
false)
const;
629 bool IsALeakCheck =
false)
const;
631 static bool SummarizeValue(raw_ostream &os, SVal
V);
632 static bool SummarizeRegion(raw_ostream &os,
const MemRegion *MR);
634 void ReportBadFree(CheckerContext &C, SVal ArgVal,
SourceRange Range,
635 const Expr *DeallocExpr)
const;
636 void ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
638 void ReportMismatchedDealloc(CheckerContext &C,
SourceRange Range,
639 const Expr *DeallocExpr,
const RefState *RS,
640 SymbolRef Sym,
bool OwnershipTransferred)
const;
641 void ReportOffsetFree(CheckerContext &C, SVal ArgVal,
SourceRange Range,
642 const Expr *DeallocExpr,
643 const Expr *AllocExpr =
nullptr)
const;
644 void ReportUseAfterFree(CheckerContext &C,
SourceRange Range,
646 void ReportDoubleFree(CheckerContext &C,
SourceRange Range,
bool Released,
649 void ReportDoubleDelete(CheckerContext &C,
SymbolRef Sym)
const;
651 void ReportUseZeroAllocated(CheckerContext &C,
SourceRange Range,
654 void ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
659 static LeakInfo getAllocationSite(
const ExplodedNode *N,
SymbolRef Sym,
662 void reportLeak(
SymbolRef Sym, ExplodedNode *N, CheckerContext &C)
const;
674 enum NotificationMode {
Normal, ReallocationFailed };
680 NotificationMode Mode;
692 MallocBugVisitor(
SymbolRef S,
bool isLeak =
false)
693 : Sym(S), Mode(
Normal), FailedReallocSymbol(
nullptr),
694 ReleaseDestructorLC(
nullptr), IsLeak(isLeak) {}
696 static void *getTag() {
701 void Profile(llvm::FoldingSetNodeID &
ID)
const override {
702 ID.AddPointer(getTag());
707 static inline bool isAllocated(
const RefState *RSCurr,
const RefState *RSPrev,
709 return (Stmt && (isa<CallExpr>(Stmt) || isa<CXXNewExpr>(Stmt)) &&
711 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
713 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
718 static inline bool isReleased(
const RefState *RSCurr,
const RefState *RSPrev,
721 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
722 assert(!IsReleased ||
723 (Stmt && (isa<CallExpr>(Stmt) || isa<CXXDeleteExpr>(Stmt))) ||
724 (!Stmt && RSCurr->getAllocationFamily() == AF_InnerBuffer));
729 static inline bool isRelinquished(
const RefState *RSCurr,
730 const RefState *RSPrev,
const Stmt *Stmt) {
732 (isa<CallExpr>(Stmt) || isa<ObjCMessageExpr>(Stmt) ||
733 isa<ObjCPropertyRefExpr>(Stmt)) &&
734 (RSCurr && RSCurr->isRelinquished()) &&
735 (!RSPrev || !RSPrev->isRelinquished()));
742 static inline bool hasReallocFailed(
const RefState *RSCurr,
743 const RefState *RSPrev,
745 return ((!Stmt || !isa<CallExpr>(Stmt)) &&
747 (RSCurr->isAllocated() || RSCurr->isAllocatedOfSizeZero())) &&
749 !(RSPrev->isAllocated() || RSPrev->isAllocatedOfSizeZero())));
753 BugReporterContext &BRC,
754 PathSensitiveBugReport &BR)
override;
757 const ExplodedNode *EndPathNode,
758 PathSensitiveBugReport &BR)
override {
762 PathDiagnosticLocation L = BR.getLocation();
764 return std::make_shared<PathDiagnosticEventPiece>(L, BR.getDescription(),
769 class StackHintGeneratorForReallocationFailed
770 :
public StackHintGeneratorForSymbol {
772 StackHintGeneratorForReallocationFailed(
SymbolRef S, StringRef M)
773 : StackHintGeneratorForSymbol(S, M) {}
775 std::string getMessageForArg(
const Expr *ArgE,
unsigned ArgIndex)
override {
780 llvm::raw_svector_ostream os(buf);
782 os <<
"Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
783 <<
" parameter failed";
789 return "Reallocation of returned value failed";
801 class StopTrackingCallback final :
public SymbolVisitor {
807 bool VisitSymbol(
SymbolRef sym)
override {
808 state = state->remove<RegionState>(sym);
818 void MemFunctionInfoTy::initIdentifierInfo(
ASTContext &Ctx)
const {
825 II_reallocf = &Ctx.
Idents.
get(
"reallocf");
833 II_if_nameindex = &Ctx.
Idents.
get(
"if_nameindex");
834 II_if_freenameindex = &Ctx.
Idents.
get(
"if_freenameindex");
837 II_win_strdup = &Ctx.
Idents.
get(
"_strdup");
838 II_win_wcsdup = &Ctx.
Idents.
get(
"_wcsdup");
839 II_win_alloca = &Ctx.
Idents.
get(
"_alloca");
842 II_g_malloc = &Ctx.
Idents.
get(
"g_malloc");
843 II_g_malloc0 = &Ctx.
Idents.
get(
"g_malloc0");
844 II_g_realloc = &Ctx.
Idents.
get(
"g_realloc");
845 II_g_try_malloc = &Ctx.
Idents.
get(
"g_try_malloc");
846 II_g_try_malloc0 = &Ctx.
Idents.
get(
"g_try_malloc0");
847 II_g_try_realloc = &Ctx.
Idents.
get(
"g_try_realloc");
849 II_g_memdup = &Ctx.
Idents.
get(
"g_memdup");
850 II_g_malloc_n = &Ctx.
Idents.
get(
"g_malloc_n");
851 II_g_malloc0_n = &Ctx.
Idents.
get(
"g_malloc0_n");
852 II_g_realloc_n = &Ctx.
Idents.
get(
"g_realloc_n");
853 II_g_try_malloc_n = &Ctx.
Idents.
get(
"g_try_malloc_n");
854 II_g_try_malloc0_n = &Ctx.
Idents.
get(
"g_try_malloc0_n");
855 II_g_try_realloc_n = &Ctx.
Idents.
get(
"g_try_realloc_n");
858 bool MemFunctionInfoTy::isMemFunction(
const FunctionDecl *FD,
860 if (isCMemFunction(FD, C, AF_Malloc, MemoryOperationKind::MOK_Any))
863 if (isCMemFunction(FD, C, AF_IfNameIndex, MemoryOperationKind::MOK_Any))
866 if (isCMemFunction(FD, C, AF_Alloca, MemoryOperationKind::MOK_Any))
869 if (isStandardNewDelete(FD, C))
881 bool CheckFree = (MemKind == MemoryOperationKind::MOK_Any ||
882 MemKind == MemoryOperationKind::MOK_Free);
883 bool CheckAlloc = (MemKind == MemoryOperationKind::MOK_Any ||
884 MemKind == MemoryOperationKind::MOK_Allocate);
888 initIdentifierInfo(C);
890 if (Family == AF_Malloc && CheckFree) {
891 if (FunI == II_free || FunI == II_realloc || FunI == II_reallocf ||
892 FunI == II_g_free || FunI == II_kfree)
896 if (Family == AF_Malloc && CheckAlloc) {
897 if (FunI == II_malloc || FunI == II_realloc || FunI == II_reallocf ||
898 FunI == II_calloc || FunI == II_valloc || FunI == II_strdup ||
899 FunI == II_win_strdup || FunI == II_strndup || FunI == II_wcsdup ||
900 FunI == II_win_wcsdup || FunI == II_kmalloc ||
901 FunI == II_g_malloc || FunI == II_g_malloc0 ||
902 FunI == II_g_realloc || FunI == II_g_try_malloc ||
903 FunI == II_g_try_malloc0 || FunI == II_g_try_realloc ||
904 FunI == II_g_memdup || FunI == II_g_malloc_n ||
905 FunI == II_g_malloc0_n || FunI == II_g_realloc_n ||
906 FunI == II_g_try_malloc_n || FunI == II_g_try_malloc0_n ||
907 FunI == II_g_try_realloc_n)
911 if (Family == AF_IfNameIndex && CheckFree) {
912 if (FunI == II_if_freenameindex)
916 if (Family == AF_IfNameIndex && CheckAlloc) {
917 if (FunI == II_if_nameindex)
921 if (Family == AF_Alloca && CheckAlloc) {
922 if (FunI == II_alloca || FunI == II_win_alloca)
927 if (Family != AF_Malloc)
930 if (ShouldIncludeOwnershipAnnotatedFunctions && FD->
hasAttrs()) {
932 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
933 if(OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds) {
936 }
else if (OwnKind == OwnershipAttr::Returns) {
945 bool MemFunctionInfoTy::isStandardNewDelete(
const FunctionDecl *FD,
951 if (Kind != OO_New && Kind != OO_Array_New &&
952 Kind != OO_Delete && Kind != OO_Array_Delete)
987 if (!KernelZeroFlagVal.hasValue()) {
988 if (OS == llvm::Triple::FreeBSD)
989 KernelZeroFlagVal = 0x0100;
990 else if (OS == llvm::Triple::NetBSD)
991 KernelZeroFlagVal = 0x0002;
992 else if (OS == llvm::Triple::OpenBSD)
993 KernelZeroFlagVal = 0x0008;
994 else if (OS == llvm::Triple::Linux)
996 KernelZeroFlagVal = 0x8000;
1013 const SVal
V = C.getSVal(FlagsEx);
1014 if (!V.getAs<NonLoc>()) {
1020 NonLoc Flags = V.castAs<NonLoc>();
1021 NonLoc ZeroFlag = C.getSValBuilder()
1022 .makeIntVal(KernelZeroFlagVal.getValue(), FlagsEx->
getType())
1024 SVal MaskedFlagsUC = C.getSValBuilder().evalBinOpNN(State, BO_And,
1027 if (MaskedFlagsUC.isUnknownOrUndef())
1029 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
1033 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
1036 if (TrueState && !FalseState) {
1037 SVal ZeroVal = C.getSValBuilder().makeZeroVal(Ctx.
CharTy);
1038 return MallocMemAux(C, CE, CE->
getArg(0), ZeroVal, TrueState);
1044 SVal MallocChecker::evalMulForBufferSize(CheckerContext &C,
const Expr *Blocks,
1045 const Expr *BlockBytes) {
1046 SValBuilder &SB = C.getSValBuilder();
1047 SVal BlocksVal = C.getSVal(Blocks);
1048 SVal BlockBytesVal = C.getSVal(BlockBytes);
1050 SVal TotalSize = SB.evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1051 SB.getContext().getSizeType());
1055 void MallocChecker::checkPostStmt(
const CallExpr *CE, CheckerContext &C)
const {
1064 bool IsKnownToBeAllocatedMemory =
false;
1067 MemFunctionInfo.initIdentifierInfo(C.getASTContext());
1070 if (FunI == MemFunctionInfo.II_malloc ||
1071 FunI == MemFunctionInfo.II_g_malloc ||
1072 FunI == MemFunctionInfo.II_g_try_malloc) {
1077 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
1078 State = ProcessZeroAllocCheck(C, CE, 0, State);
1081 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
1085 performKernelMalloc(CE, C, State);
1086 if (MaybeState.hasValue())
1087 State = MaybeState.getValue();
1089 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
1092 }
else if (FunI == MemFunctionInfo.II_kmalloc) {
1096 performKernelMalloc(CE, C, State);
1097 if (MaybeState.hasValue())
1098 State = MaybeState.getValue();
1100 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
1101 }
else if (FunI == MemFunctionInfo.II_valloc) {
1104 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State);
1105 State = ProcessZeroAllocCheck(C, CE, 0, State);
1106 }
else if (FunI == MemFunctionInfo.II_realloc ||
1107 FunI == MemFunctionInfo.II_g_realloc ||
1108 FunI == MemFunctionInfo.II_g_try_realloc) {
1109 State = ReallocMemAux(C, CE,
false, State);
1110 State = ProcessZeroAllocCheck(C, CE, 1, State);
1111 }
else if (FunI == MemFunctionInfo.II_reallocf) {
1112 State = ReallocMemAux(C, CE,
true, State);
1113 State = ProcessZeroAllocCheck(C, CE, 1, State);
1114 }
else if (FunI == MemFunctionInfo.II_calloc) {
1115 State = CallocMem(C, CE, State);
1116 State = ProcessZeroAllocCheck(C, CE, 0, State);
1117 State = ProcessZeroAllocCheck(C, CE, 1, State);
1118 }
else if (FunI == MemFunctionInfo.II_free ||
1119 FunI == MemFunctionInfo.II_g_free ||
1120 FunI == MemFunctionInfo.II_kfree) {
1121 if (suppressDeallocationsInSuspiciousContexts(CE, C))
1124 State = FreeMemAux(C, CE, State, 0,
false, IsKnownToBeAllocatedMemory);
1125 }
else if (FunI == MemFunctionInfo.II_strdup ||
1126 FunI == MemFunctionInfo.II_win_strdup ||
1127 FunI == MemFunctionInfo.II_wcsdup ||
1128 FunI == MemFunctionInfo.II_win_wcsdup) {
1130 }
else if (FunI == MemFunctionInfo.II_strndup) {
1132 }
else if (FunI == MemFunctionInfo.II_alloca ||
1133 FunI == MemFunctionInfo.II_win_alloca) {
1136 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State,
1138 State = ProcessZeroAllocCheck(C, CE, 0, State);
1139 }
else if (MemFunctionInfo.isStandardNewDelete(FD, C.
getASTContext())) {
1146 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State,
1148 State = ProcessZeroAllocCheck(C, CE, 0, State);
1151 State = MallocMemAux(C, CE, CE->
getArg(0), UndefinedVal(),
State,
1153 State = ProcessZeroAllocCheck(C, CE, 0, State);
1156 case OO_Array_Delete:
1157 State = FreeMemAux(C, CE, State, 0,
false, IsKnownToBeAllocatedMemory);
1160 llvm_unreachable(
"not a new/delete operator");
1162 }
else if (FunI == MemFunctionInfo.II_if_nameindex) {
1165 State = MallocMemAux(C, CE, UnknownVal(), UnknownVal(), State,
1167 }
else if (FunI == MemFunctionInfo.II_if_freenameindex) {
1168 State = FreeMemAux(C, CE, State, 0,
false, IsKnownToBeAllocatedMemory);
1169 }
else if (FunI == MemFunctionInfo.II_g_malloc0 ||
1170 FunI == MemFunctionInfo.II_g_try_malloc0) {
1173 SValBuilder &svalBuilder = C.getSValBuilder();
1174 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
1175 State = MallocMemAux(C, CE, CE->
getArg(0), zeroVal,
State);
1176 State = ProcessZeroAllocCheck(C, CE, 0, State);
1177 }
else if (FunI == MemFunctionInfo.II_g_memdup) {
1180 State = MallocMemAux(C, CE, CE->
getArg(1), UndefinedVal(),
State);
1181 State = ProcessZeroAllocCheck(C, CE, 1, State);
1182 }
else if (FunI == MemFunctionInfo.II_g_malloc_n ||
1183 FunI == MemFunctionInfo.II_g_try_malloc_n ||
1184 FunI == MemFunctionInfo.II_g_malloc0_n ||
1185 FunI == MemFunctionInfo.II_g_try_malloc0_n) {
1188 SVal Init = UndefinedVal();
1189 if (FunI == MemFunctionInfo.II_g_malloc0_n ||
1190 FunI == MemFunctionInfo.II_g_try_malloc0_n) {
1191 SValBuilder &SB = C.getSValBuilder();
1192 Init = SB.makeZeroVal(SB.getContext().CharTy);
1194 SVal TotalSize = evalMulForBufferSize(C, CE->
getArg(0), CE->
getArg(1));
1195 State = MallocMemAux(C, CE, TotalSize, Init, State);
1196 State = ProcessZeroAllocCheck(C, CE, 0, State);
1197 State = ProcessZeroAllocCheck(C, CE, 1, State);
1198 }
else if (FunI == MemFunctionInfo.II_g_realloc_n ||
1199 FunI == MemFunctionInfo.II_g_try_realloc_n) {
1202 State = ReallocMemAux(C, CE,
false, State,
1204 State = ProcessZeroAllocCheck(C, CE, 1, State);
1205 State = ProcessZeroAllocCheck(C, CE, 2, State);
1209 if (MemFunctionInfo.ShouldIncludeOwnershipAnnotatedFunctions ||
1210 ChecksEnabled[CK_MismatchedDeallocatorChecker]) {
1215 switch (I->getOwnKind()) {
1216 case OwnershipAttr::Returns:
1217 State = MallocMemReturnsAttr(C, CE, I, State);
1219 case OwnershipAttr::Takes:
1220 case OwnershipAttr::Holds:
1221 State = FreeMemAttr(C, CE, I, State);
1226 C.addTransition(State);
1231 CheckerContext &C,
const Expr *E,
const unsigned IndexOfSizeArg,
1237 RetVal = C.getSVal(E);
1239 const Expr *Arg =
nullptr;
1241 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1242 Arg = CE->
getArg(IndexOfSizeArg);
1244 else if (
const CXXNewExpr *
NE = dyn_cast<CXXNewExpr>(E)) {
1246 Arg = *
NE->getArraySize();
1251 llvm_unreachable(
"not a CallExpr or CXXNewExpr");
1262 SValBuilder &SvalBuilder = C.getSValBuilder();
1264 SvalBuilder.makeZeroVal(Arg->
getType()).castAs<DefinedSVal>();
1266 std::tie(TrueState, FalseState) =
1267 State->assume(SvalBuilder.evalEQ(
State, *DefArgVal, Zero));
1269 if (TrueState && !FalseState) {
1270 SymbolRef Sym = RetVal->getAsLocSymbol();
1274 const RefState *RS =
State->get<RegionState>(Sym);
1276 if (RS->isAllocated())
1277 return TrueState->set<RegionState>(Sym,
1278 RefState::getAllocatedOfSizeZero(RS));
1286 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1297 while (!PointeeType.isNull()) {
1298 Result = PointeeType;
1318 for (
const auto *CtorParam : CtorD->
parameters()) {
1321 if (CtorParamPointeeT.
isNull())
1333 void MallocChecker::processNewAllocation(
const CXXNewExpr *
NE,
1340 const ParentMap &PM = C.getLocationContext()->getParentMap();
1355 : AF_CXXNew, Target);
1356 State = addExtentSize(C, NE, State, Target);
1357 State = ProcessZeroAllocCheck(C, NE, 0, State, Target);
1358 C.addTransition(State);
1361 void MallocChecker::checkPostStmt(
const CXXNewExpr *NE,
1362 CheckerContext &C)
const {
1363 if (!C.getAnalysisManager().getAnalyzerOptions().MayInlineCXXAllocator)
1364 processNewAllocation(NE, C, C.getSVal(NE));
1368 CheckerContext &C)
const {
1370 processNewAllocation(NE, C,
Target);
1382 SValBuilder &svalBuilder = C.getSValBuilder();
1384 const SubRegion *Region;
1387 ElementCount = C.getSVal(SizeExpr);
1390 Region = Target.getAsRegion()
1391 ->castAs<SubRegion>()
1393 ->castAs<SubRegion>();
1395 ElementCount = svalBuilder.makeIntVal(1,
true);
1396 Region = Target.getAsRegion()->castAs<SubRegion>();
1404 if (ElementCount.getAs<NonLoc>()) {
1405 DefinedOrUnknownSVal Extent = Region->getExtent(svalBuilder);
1407 SVal SizeInBytes = svalBuilder.evalBinOpNN(
1408 State, BO_Mul, ElementCount.castAs<NonLoc>(),
1409 svalBuilder.makeArrayIndex(TypeSize.
getQuantity()),
1410 svalBuilder.getArrayIndexType());
1411 DefinedOrUnknownSVal extentMatchesSize = svalBuilder.evalEQ(
1412 State, Extent, SizeInBytes.castAs<DefinedOrUnknownSVal>());
1413 State =
State->assume(extentMatchesSize,
true);
1419 CheckerContext &C)
const {
1421 if (!ChecksEnabled[CK_NewDeleteChecker])
1430 bool IsKnownToBeAllocated;
1432 false, IsKnownToBeAllocated);
1434 C.addTransition(State);
1444 return FirstSlot ==
"dataWithBytesNoCopy" ||
1445 FirstSlot ==
"initWithBytesNoCopy" ||
1446 FirstSlot ==
"initWithCharactersNoCopy";
1453 for (
unsigned i = 1; i < S.
getNumArgs(); ++i)
1455 return !Call.getArgSVal(i).isZeroConstant();
1460 void MallocChecker::checkPostObjCMessage(
const ObjCMethodCall &Call,
1461 CheckerContext &C)
const {
1472 if (Call.hasNonZeroCallbackArg())
1475 bool IsKnownToBeAllocatedMemory;
1478 true, IsKnownToBeAllocatedMemory,
1481 C.addTransition(State);
1485 MallocChecker::MallocMemReturnsAttr(CheckerContext &C,
const CallExpr *CE,
1486 const OwnershipAttr *Att,
1491 if (Att->getModule() != MemFunctionInfo.II_malloc)
1494 OwnershipAttr::args_iterator I = Att->args_begin(), E = Att->args_end();
1496 return MallocMemAux(C, CE, CE->
getArg(I->getASTIndex()), UndefinedVal(),
1499 return MallocMemAux(C, CE, UnknownVal(), UndefinedVal(), State);
1504 const Expr *SizeEx, SVal Init,
1510 return MallocMemAux(C, CE, C.getSVal(SizeEx), Init,
State, Family);
1515 SVal Size, SVal Init,
1528 unsigned Count = C.blockCount();
1529 SValBuilder &svalBuilder = C.getSValBuilder();
1530 const LocationContext *LCtx = C.getPredecessor()->getLocationContext();
1531 DefinedSVal RetVal = svalBuilder.getConjuredHeapSymbolVal(CE, LCtx, Count)
1532 .castAs<DefinedSVal>();
1533 State = State->BindExpr(CE, C.getLocationContext(), RetVal);
1536 State = State->bindDefaultInitial(RetVal, Init, LCtx);
1539 const SymbolicRegion *R =
1540 dyn_cast_or_null<SymbolicRegion>(RetVal.getAsRegion());
1544 Size.getAs<DefinedOrUnknownSVal>()) {
1545 SValBuilder &svalBuilder = C.getSValBuilder();
1546 DefinedOrUnknownSVal Extent = R->getExtent(svalBuilder);
1547 DefinedOrUnknownSVal extentMatchesSize =
1548 svalBuilder.evalEQ(State, Extent, *DefinedSize);
1550 State = State->assume(extentMatchesSize,
true);
1566 RetVal = C.getSVal(E);
1569 if (!RetVal->getAs<Loc>())
1572 SymbolRef Sym = RetVal->getAsLocSymbol();
1578 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
1583 const OwnershipAttr *Att,
1588 if (Att->getModule() != MemFunctionInfo.II_malloc)
1591 bool IsKnownToBeAllocated =
false;
1593 for (
const auto &Arg : Att->args()) {
1595 C, CE, State, Arg.getASTIndex(),
1596 Att->getOwnKind() == OwnershipAttr::Holds, IsKnownToBeAllocated);
1605 bool Hold,
bool &IsKnownToBeAllocated,
1606 bool ReturnsNullOnFailure)
const {
1613 return FreeMemAux(C, CE->
getArg(Num), CE,
State, Hold, IsKnownToBeAllocated,
1614 ReturnsNullOnFailure);
1621 const SymbolRef *
Ret = State->get<FreeReturnValue>(Sym);
1623 assert(*Ret &&
"We should not store the null return symbol");
1624 ConstraintManager &CMgr = State->getConstraintManager();
1625 ConditionTruthVal FreeFailed = CMgr.isNull(State, *Ret);
1626 RetStatusSymbol = *
Ret;
1627 return FreeFailed.isConstrainedTrue();
1639 if (
const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1647 if (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_Malloc,
1648 MemoryOperationKind::MOK_Any))
1651 if (MemFunctionInfo.isStandardNewDelete(FD, Ctx)) {
1653 if (Kind == OO_New || Kind == OO_Delete)
1655 else if (Kind == OO_Array_New || Kind == OO_Array_Delete)
1656 return AF_CXXNewArray;
1659 if (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_IfNameIndex,
1660 MemoryOperationKind::MOK_Any))
1661 return AF_IfNameIndex;
1663 if (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_Alloca,
1664 MemoryOperationKind::MOK_Any))
1670 if (
const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(S))
1671 return NE->
isArray() ? AF_CXXNewArray : AF_CXXNew;
1674 return DE->
isArrayForm() ? AF_CXXNewArray : AF_CXXNew;
1676 if (isa<ObjCMessageExpr>(S))
1684 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
1691 if (!FD->isOverloadedOperator())
1697 if (Msg->isInstanceMessage())
1701 Msg->getSelector().
print(os);
1705 if (
const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
1723 const MemFunctionInfoTy &MemFunctionInfo,
1724 CheckerContext &C,
const Expr *E) {
1728 case AF_Malloc: os <<
"malloc()";
return;
1729 case AF_CXXNew: os <<
"'new'";
return;
1730 case AF_CXXNewArray: os <<
"'new[]'";
return;
1731 case AF_IfNameIndex: os <<
"'if_nameindex()'";
return;
1732 case AF_InnerBuffer: os <<
"container-specific allocator";
return;
1734 case AF_None: llvm_unreachable(
"not a deallocation expression");
1740 case AF_Malloc: os <<
"free()";
return;
1741 case AF_CXXNew: os <<
"'delete'";
return;
1742 case AF_CXXNewArray: os <<
"'delete[]'";
return;
1743 case AF_IfNameIndex: os <<
"'if_freenameindex()'";
return;
1744 case AF_InnerBuffer: os <<
"container-specific deallocator";
return;
1746 case AF_None: llvm_unreachable(
"suspicious argument");
1751 const Expr *ArgExpr,
1752 const Expr *ParentExpr,
1754 bool &IsKnownToBeAllocated,
1755 bool ReturnsNullOnFailure)
const {
1760 SVal ArgVal = C.getSVal(ArgExpr);
1761 if (!ArgVal.getAs<DefinedOrUnknownSVal>())
1763 DefinedOrUnknownSVal location = ArgVal.castAs<DefinedOrUnknownSVal>();
1766 if (!location.getAs<Loc>())
1771 std::tie(notNullState, nullState) =
State->assume(location);
1772 if (nullState && !notNullState)
1777 if (ArgVal.isUnknownOrUndef())
1780 const MemRegion *R = ArgVal.getAsRegion();
1789 R = R->StripCasts();
1792 if (isa<BlockDataRegion>(R)) {
1797 const MemSpaceRegion *MS = R->getMemorySpace();
1801 if (!(isa<UnknownSpaceRegion>(MS) || isa<HeapSpaceRegion>(MS))) {
1810 if (isa<AllocaRegion>(R))
1818 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(R->getBaseRegion());
1824 SymbolRef SymBase = SrBase->getSymbol();
1825 const RefState *RsBase =
State->get<RegionState>(SymBase);
1826 SymbolRef PreviousRetStatusSymbol =
nullptr;
1828 IsKnownToBeAllocated =
1829 RsBase && (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero());
1834 if (RsBase->getAllocationFamily() == AF_Alloca) {
1840 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
1842 ReportDoubleFree(C, ParentExpr->
getSourceRange(), RsBase->isReleased(),
1843 SymBase, PreviousRetStatusSymbol);
1848 }
else if (RsBase->isAllocated() || RsBase->isAllocatedOfSizeZero() ||
1849 RsBase->isEscaped()) {
1852 bool DeallocMatchesAlloc =
1853 RsBase->getAllocationFamily() ==
1855 if (!DeallocMatchesAlloc) {
1857 ParentExpr, RsBase, SymBase, Hold);
1863 RegionOffset
Offset = R->getAsOffset();
1864 if (Offset.isValid() &&
1865 !Offset.hasSymbolicOffset() &&
1866 Offset.getOffset() != 0) {
1867 const Expr *AllocExpr = cast<Expr>(RsBase->getStmt());
1868 ReportOffsetFree(C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr,
1875 if (SymBase->getType()->isFunctionPointerType()) {
1876 ReportFunctionPointerFree(C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr);
1881 State =
State->remove<FreeReturnValue>(SymBase);
1885 if (ReturnsNullOnFailure) {
1886 SVal RetVal = C.getSVal(ParentExpr);
1887 SymbolRef RetStatusSymbol = RetVal.getAsSymbol();
1888 if (RetStatusSymbol) {
1889 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
1890 State =
State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
1895 RsBase ? RsBase->getAllocationFamily()
1899 return State->set<RegionState>(SymBase,
1900 RefState::getRelinquished(Family,
1903 return State->set<RegionState>(SymBase,
1904 RefState::getReleased(Family, ParentExpr));
1909 bool IsALeakCheck)
const {
1913 case AF_IfNameIndex: {
1914 if (ChecksEnabled[CK_MallocChecker])
1915 return CK_MallocChecker;
1919 case AF_CXXNewArray: {
1921 if (ChecksEnabled[CK_NewDeleteLeaksChecker])
1922 return CK_NewDeleteLeaksChecker;
1925 if (ChecksEnabled[CK_NewDeleteChecker])
1926 return CK_NewDeleteChecker;
1930 case AF_InnerBuffer: {
1931 if (ChecksEnabled[CK_InnerPointerChecker])
1932 return CK_InnerPointerChecker;
1936 llvm_unreachable(
"no family");
1939 llvm_unreachable(
"unhandled family");
1943 MallocChecker::getCheckIfTracked(CheckerContext &C,
1944 const Stmt *AllocDeallocStmt,
1945 bool IsALeakCheck)
const {
1946 return getCheckIfTracked(
1951 MallocChecker::getCheckIfTracked(CheckerContext &C,
SymbolRef Sym,
1952 bool IsALeakCheck)
const {
1953 if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
1954 return CK_MallocChecker;
1956 const RefState *RS = C.getState()->get<RegionState>(Sym);
1958 return getCheckIfTracked(RS->getAllocationFamily(), IsALeakCheck);
1961 bool MallocChecker::SummarizeValue(raw_ostream &os, SVal
V) {
1963 os <<
"an integer (" << IntVal->getValue() <<
")";
1965 os <<
"a constant address (" << ConstAddr->getValue() <<
")";
1967 os <<
"the address of the label '" <<
Label->getLabel()->getName() <<
"'";
1974 bool MallocChecker::SummarizeRegion(raw_ostream &os,
1975 const MemRegion *MR) {
1976 switch (MR->getKind()) {
1977 case MemRegion::FunctionCodeRegionKind: {
1978 const NamedDecl *FD = cast<FunctionCodeRegion>(MR)->getDecl();
1980 os <<
"the address of the function '" << *FD <<
'\'';
1982 os <<
"the address of a function";
1985 case MemRegion::BlockCodeRegionKind:
1988 case MemRegion::BlockDataRegionKind:
1993 const MemSpaceRegion *MS = MR->getMemorySpace();
1995 if (isa<StackLocalsSpaceRegion>(MS)) {
1996 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2004 os <<
"the address of the local variable '" << VD->
getName() <<
"'";
2006 os <<
"the address of a local stack variable";
2010 if (isa<StackArgumentsSpaceRegion>(MS)) {
2011 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2019 os <<
"the address of the parameter '" << VD->
getName() <<
"'";
2021 os <<
"the address of a parameter";
2025 if (isa<GlobalsSpaceRegion>(MS)) {
2026 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2034 if (VD->isStaticLocal())
2035 os <<
"the address of the static variable '" << VD->
getName() <<
"'";
2037 os <<
"the address of the global variable '" << VD->getName() <<
"'";
2039 os <<
"the address of a global variable";
2048 void MallocChecker::ReportBadFree(CheckerContext &C, SVal ArgVal,
2050 const Expr *DeallocExpr)
const {
2052 if (!ChecksEnabled[CK_MallocChecker] &&
2053 !ChecksEnabled[CK_NewDeleteChecker])
2057 getCheckIfTracked(C, DeallocExpr);
2058 if (!CheckKind.hasValue())
2061 if (ExplodedNode *N = C.generateErrorNode()) {
2062 if (!BT_BadFree[*CheckKind])
2063 BT_BadFree[*CheckKind].reset(
new BugType(
2067 llvm::raw_svector_ostream os(buf);
2069 const MemRegion *MR = ArgVal.getAsRegion();
2070 while (
const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2071 MR = ER->getSuperRegion();
2073 os <<
"Argument to ";
2075 os <<
"deallocator";
2078 bool Summarized = MR ? SummarizeRegion(os, MR)
2079 : SummarizeValue(os, ArgVal);
2081 os <<
", which is not memory allocated by ";
2083 os <<
"not memory allocated by ";
2087 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2089 R->markInteresting(MR);
2091 C.emitReport(std::move(R));
2095 void MallocChecker::ReportFreeAlloca(CheckerContext &C, SVal ArgVal,
2100 if (ChecksEnabled[CK_MallocChecker])
2101 CheckKind = CK_MallocChecker;
2102 else if (ChecksEnabled[CK_MismatchedDeallocatorChecker])
2103 CheckKind = CK_MismatchedDeallocatorChecker;
2107 if (ExplodedNode *N = C.generateErrorNode()) {
2108 if (!BT_FreeAlloca[*CheckKind])
2109 BT_FreeAlloca[*CheckKind].reset(
new BugType(
2112 auto R = std::make_unique<PathSensitiveBugReport>(
2113 *BT_FreeAlloca[*CheckKind],
2114 "Memory allocated by alloca() should not be deallocated", N);
2115 R->markInteresting(ArgVal.getAsRegion());
2117 C.emitReport(std::move(R));
2121 void MallocChecker::ReportMismatchedDealloc(CheckerContext &C,
2123 const Expr *DeallocExpr,
2126 bool OwnershipTransferred)
const {
2128 if (!ChecksEnabled[CK_MismatchedDeallocatorChecker])
2131 if (ExplodedNode *N = C.generateErrorNode()) {
2132 if (!BT_MismatchedDealloc)
2133 BT_MismatchedDealloc.reset(
2134 new BugType(CheckNames[CK_MismatchedDeallocatorChecker],
2138 llvm::raw_svector_ostream os(buf);
2140 const Expr *AllocExpr = cast<Expr>(RS->getStmt());
2142 llvm::raw_svector_ostream AllocOs(AllocBuf);
2144 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2146 if (OwnershipTransferred) {
2148 os << DeallocOs.str() <<
" cannot";
2152 os <<
" take ownership of memory";
2155 os <<
" allocated by " << AllocOs.str();
2159 os <<
" allocated by " << AllocOs.str();
2161 os <<
" should be deallocated by ";
2165 os <<
", not " << DeallocOs.str();
2168 auto R = std::make_unique<PathSensitiveBugReport>(*BT_MismatchedDealloc,
2170 R->markInteresting(Sym);
2172 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2173 C.emitReport(std::move(R));
2177 void MallocChecker::ReportOffsetFree(CheckerContext &C, SVal ArgVal,
2179 const Expr *AllocExpr)
const {
2182 if (!ChecksEnabled[CK_MallocChecker] &&
2183 !ChecksEnabled[CK_NewDeleteChecker])
2187 getCheckIfTracked(C, AllocExpr);
2188 if (!CheckKind.hasValue())
2191 ExplodedNode *N = C.generateErrorNode();
2195 if (!BT_OffsetFree[*CheckKind])
2196 BT_OffsetFree[*CheckKind].reset(
new BugType(
2200 llvm::raw_svector_ostream os(buf);
2202 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2204 const MemRegion *MR = ArgVal.getAsRegion();
2205 assert(MR &&
"Only MemRegion based symbols can have offset free errors");
2207 RegionOffset
Offset = MR->getAsOffset();
2208 assert((Offset.isValid() &&
2209 !Offset.hasSymbolicOffset() &&
2210 Offset.getOffset() != 0) &&
2211 "Only symbols with a valid offset can have offset free errors");
2213 int offsetBytes = Offset.getOffset() / C.getASTContext().
getCharWidth();
2215 os <<
"Argument to ";
2217 os <<
"deallocator";
2218 os <<
" is offset by " 2221 << ((
abs(offsetBytes) > 1) ?
"bytes" :
"byte")
2222 <<
" from the start of ";
2224 os <<
"memory allocated by " << AllocNameOs.str();
2226 os <<
"allocated memory";
2228 auto R = std::make_unique<PathSensitiveBugReport>(*BT_OffsetFree[*CheckKind],
2230 R->markInteresting(MR->getBaseRegion());
2232 C.emitReport(std::move(R));
2235 void MallocChecker::ReportUseAfterFree(CheckerContext &C,
SourceRange Range,
2238 if (!ChecksEnabled[CK_MallocChecker] &&
2239 !ChecksEnabled[CK_NewDeleteChecker] &&
2240 !ChecksEnabled[CK_InnerPointerChecker])
2244 if (!CheckKind.hasValue())
2247 if (ExplodedNode *N = C.generateErrorNode()) {
2248 if (!BT_UseFree[*CheckKind])
2249 BT_UseFree[*CheckKind].reset(
new BugType(
2255 auto R = std::make_unique<PathSensitiveBugReport>(
2256 *BT_UseFree[*CheckKind],
2257 AF == AF_InnerBuffer
2258 ?
"Inner pointer of container used after re/deallocation" 2259 :
"Use of memory after it is freed",
2262 R->markInteresting(Sym);
2264 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2266 if (AF == AF_InnerBuffer)
2269 C.emitReport(std::move(R));
2273 void MallocChecker::ReportDoubleFree(CheckerContext &C,
SourceRange Range,
2277 if (!ChecksEnabled[CK_MallocChecker] &&
2278 !ChecksEnabled[CK_NewDeleteChecker])
2282 if (!CheckKind.hasValue())
2285 if (ExplodedNode *N = C.generateErrorNode()) {
2286 if (!BT_DoubleFree[*CheckKind])
2287 BT_DoubleFree[*CheckKind].reset(
new BugType(
2290 auto R = std::make_unique<PathSensitiveBugReport>(
2291 *BT_DoubleFree[*CheckKind],
2292 (Released ?
"Attempt to free released memory" 2293 :
"Attempt to free non-owned memory"),
2296 R->markInteresting(Sym);
2298 R->markInteresting(PrevSym);
2299 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2300 C.emitReport(std::move(R));
2304 void MallocChecker::ReportDoubleDelete(CheckerContext &C,
SymbolRef Sym)
const {
2306 if (!ChecksEnabled[CK_NewDeleteChecker])
2310 if (!CheckKind.hasValue())
2313 if (ExplodedNode *N = C.generateErrorNode()) {
2314 if (!BT_DoubleDelete)
2315 BT_DoubleDelete.reset(
new BugType(CheckNames[CK_NewDeleteChecker],
2319 auto R = std::make_unique<PathSensitiveBugReport>(
2320 *BT_DoubleDelete,
"Attempt to delete released memory", N);
2322 R->markInteresting(Sym);
2323 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2324 C.emitReport(std::move(R));
2328 void MallocChecker::ReportUseZeroAllocated(CheckerContext &C,
2332 if (!ChecksEnabled[CK_MallocChecker] &&
2333 !ChecksEnabled[CK_NewDeleteChecker])
2338 if (!CheckKind.hasValue())
2341 if (ExplodedNode *N = C.generateErrorNode()) {
2342 if (!BT_UseZerroAllocated[*CheckKind])
2343 BT_UseZerroAllocated[*CheckKind].reset(
2344 new BugType(CheckNames[*CheckKind],
"Use of zero allocated",
2347 auto R = std::make_unique<PathSensitiveBugReport>(
2348 *BT_UseZerroAllocated[*CheckKind],
"Use of zero-allocated memory", N);
2352 R->markInteresting(Sym);
2353 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym));
2355 C.emitReport(std::move(R));
2359 void MallocChecker::ReportFunctionPointerFree(CheckerContext &C, SVal ArgVal,
2361 const Expr *FreeExpr)
const {
2362 if (!ChecksEnabled[CK_MallocChecker])
2366 if (!CheckKind.hasValue())
2369 if (ExplodedNode *N = C.generateErrorNode()) {
2370 if (!BT_BadFree[*CheckKind])
2371 BT_BadFree[*CheckKind].reset(
new BugType(
2375 llvm::raw_svector_ostream Os(Buf);
2377 const MemRegion *MR = ArgVal.getAsRegion();
2378 while (
const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2379 MR = ER->getSuperRegion();
2381 Os <<
"Argument to ";
2383 Os <<
"deallocator";
2385 Os <<
" is a function pointer";
2387 auto R = std::make_unique<PathSensitiveBugReport>(*BT_BadFree[*CheckKind],
2389 R->markInteresting(MR);
2391 C.emitReport(std::move(R));
2397 bool ShouldFreeOnFail,
2399 bool SuffixWithN)
const {
2409 SVal Arg0Val = C.getSVal(arg0Expr);
2410 if (!Arg0Val.getAs<DefinedOrUnknownSVal>())
2412 DefinedOrUnknownSVal arg0Val = Arg0Val.castAs<DefinedOrUnknownSVal>();
2414 SValBuilder &svalBuilder = C.getSValBuilder();
2416 DefinedOrUnknownSVal PtrEQ =
2417 svalBuilder.evalEQ(
State, arg0Val, svalBuilder.makeNull());
2423 SVal TotalSize = C.getSVal(Arg1);
2425 TotalSize = evalMulForBufferSize(C, Arg1, CE->
getArg(2));
2426 if (!TotalSize.getAs<DefinedOrUnknownSVal>())
2430 DefinedOrUnknownSVal SizeZero =
2431 svalBuilder.evalEQ(
State, TotalSize.castAs<DefinedOrUnknownSVal>(),
2432 svalBuilder.makeIntValWithPtrWidth(0,
false));
2435 std::tie(StatePtrIsNull, StatePtrNotNull) =
State->assume(PtrEQ);
2437 std::tie(StateSizeIsZero, StateSizeNotZero) =
State->assume(SizeZero);
2440 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2441 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2445 if (PrtIsNull && !SizeIsZero) {
2447 UndefinedVal(), StatePtrIsNull);
2451 if (PrtIsNull && SizeIsZero)
2456 SymbolRef FromPtr = arg0Val.getAsSymbol();
2457 SVal RetVal = C.getSVal(CE);
2459 if (!FromPtr || !ToPtr)
2462 bool IsKnownToBeAllocated =
false;
2471 FreeMemAux(C, CE, StateSizeIsZero, 0,
false, IsKnownToBeAllocated))
2476 FreeMemAux(C, CE,
State, 0,
false, IsKnownToBeAllocated)) {
2479 UnknownVal(), stateFree);
2484 if (ShouldFreeOnFail)
2485 Kind = OAR_FreeOnFailure;
2486 else if (!IsKnownToBeAllocated)
2487 Kind = OAR_DoNotTrackAfterFailure;
2491 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
2492 ReallocPair(FromPtr, Kind));
2494 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
2495 return stateRealloc;
2508 SValBuilder &svalBuilder = C.getSValBuilder();
2509 SVal zeroVal = svalBuilder.makeZeroVal(svalBuilder.getContext().CharTy);
2510 SVal TotalSize = evalMulForBufferSize(C, CE->
getArg(0), CE->
getArg(1));
2512 return MallocMemAux(C, CE, TotalSize, zeroVal, State);
2515 MallocChecker::LeakInfo MallocChecker::getAllocationSite(
const ExplodedNode *N,
2517 CheckerContext &C) {
2521 const ExplodedNode *AllocNode = N;
2522 const MemRegion *ReferenceRegion =
nullptr;
2526 if (!State->get<RegionState>(Sym))
2531 if (!ReferenceRegion) {
2532 if (
const MemRegion *MR = C.getLocationRegionIfPostStore(N)) {
2533 SVal Val = State->getSVal(MR);
2534 if (Val.getAsLocSymbol() == Sym) {
2535 const VarRegion *VR = MR->getBaseRegion()->getAs<VarRegion>();
2538 if (!VR || (VR->getStackFrame() == LeakContext->
getStackFrame()))
2539 ReferenceRegion = MR;
2547 if (NContext == LeakContext ||
2550 N = N->pred_empty() ? nullptr : *(N->pred_begin());
2553 return LeakInfo(AllocNode, ReferenceRegion);
2556 void MallocChecker::reportLeak(
SymbolRef Sym, ExplodedNode *N,
2557 CheckerContext &C)
const {
2559 if (!ChecksEnabled[CK_MallocChecker] &&
2560 !ChecksEnabled[CK_NewDeleteLeaksChecker])
2563 const RefState *RS = C.getState()->get<RegionState>(Sym);
2564 assert(RS &&
"cannot leak an untracked symbol");
2567 if (Family == AF_Alloca)
2571 CheckKind = getCheckIfTracked(Family,
true);
2573 if (!CheckKind.hasValue())
2577 if (!BT_Leak[*CheckKind]) {
2583 BT_Leak[*CheckKind].reset(
new BugType(CheckNames[*CheckKind],
"Memory leak",
2591 PathDiagnosticLocation LocUsedForUniqueing;
2592 const ExplodedNode *AllocNode =
nullptr;
2593 const MemRegion *Region =
nullptr;
2594 std::tie(AllocNode, Region) = getAllocationSite(N, Sym, C);
2596 const Stmt *AllocationStmt = AllocNode->getStmtForDiagnostics();
2599 C.getSourceManager(),
2600 AllocNode->getLocationContext());
2603 llvm::raw_svector_ostream os(buf);
2604 if (Region && Region->canPrintPretty()) {
2605 os <<
"Potential leak of memory pointed to by ";
2606 Region->printPretty(os);
2608 os <<
"Potential memory leak";
2611 auto R = std::make_unique<PathSensitiveBugReport>(
2612 *BT_Leak[*CheckKind], os.str(), N, LocUsedForUniqueing,
2613 AllocNode->getLocationContext()->getDecl());
2614 R->markInteresting(Sym);
2615 R->addVisitor(std::make_unique<MallocBugVisitor>(Sym,
true));
2616 C.emitReport(std::move(R));
2619 void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
2620 CheckerContext &C)
const 2623 RegionStateTy OldRS = state->get<RegionState>();
2624 RegionStateTy::Factory &F = state->get_context<RegionState>();
2626 RegionStateTy RS = OldRS;
2628 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2629 if (SymReaper.isDead(I->first)) {
2630 if (I->second.isAllocated() || I->second.isAllocatedOfSizeZero())
2631 Errors.push_back(I->first);
2633 RS = F.remove(RS, I->first);
2639 assert(state->get<ReallocPairs>() ==
2640 C.getState()->get<ReallocPairs>());
2641 assert(state->get<FreeReturnValue>() ==
2642 C.getState()->get<FreeReturnValue>());
2647 ReallocPairsTy RP = state->get<ReallocPairs>();
2648 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2649 if (SymReaper.isDead(I->first) ||
2650 SymReaper.isDead(I->second.ReallocatedSym)) {
2651 state = state->remove<ReallocPairs>(I->first);
2656 FreeReturnValueTy FR = state->get<FreeReturnValue>();
2657 for (FreeReturnValueTy::iterator I = FR.begin(), E = FR.end(); I != E; ++I) {
2658 if (SymReaper.isDead(I->first) ||
2659 SymReaper.isDead(I->second)) {
2660 state = state->remove<FreeReturnValue>(I->first);
2665 ExplodedNode *N = C.getPredecessor();
2666 if (!Errors.empty()) {
2667 static CheckerProgramPointTag Tag(
"MallocChecker",
"DeadSymbolsLeak");
2668 N = C.generateNonFatalErrorNode(C.getState(), &Tag);
2671 I = Errors.begin(), E = Errors.end(); I != E; ++I) {
2672 reportLeak(*I, N, C);
2677 C.addTransition(state->set<RegionState>(RS), N);
2680 void MallocChecker::checkPreCall(
const CallEvent &Call,
2681 CheckerContext &C)
const {
2684 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
2685 if (!Sym || checkDoubleDelete(Sym, C))
2696 if (ChecksEnabled[CK_MallocChecker] &&
2697 (MemFunctionInfo.isCMemFunction(FD, Ctx, AF_Malloc,
2698 MemoryOperationKind::MOK_Free) ||
2699 MemFunctionInfo.isCMemFunction(FD, Ctx, AF_IfNameIndex,
2700 MemoryOperationKind::MOK_Free)))
2706 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
2707 if (!Sym || checkUseAfterFree(Sym, C, CC->getCXXThisExpr()))
2712 for (
unsigned I = 0, E = Call.getNumArgs(); I != E; ++I) {
2713 SVal ArgSVal = Call.getArgSVal(I);
2714 if (ArgSVal.getAs<Loc>()) {
2718 if (checkUseAfterFree(Sym, C, Call.getArgExpr(I)))
2724 void MallocChecker::checkPreStmt(
const ReturnStmt *S,
2725 CheckerContext &C)
const {
2726 checkEscapeOnReturn(S, C);
2732 void MallocChecker::checkEndFunction(
const ReturnStmt *S,
2733 CheckerContext &C)
const {
2734 checkEscapeOnReturn(S, C);
2737 void MallocChecker::checkEscapeOnReturn(
const ReturnStmt *S,
2738 CheckerContext &C)
const {
2748 SVal RetVal = C.getSVal(E);
2754 if (
const MemRegion *MR = RetVal.getAsRegion())
2755 if (isa<FieldRegion>(MR) || isa<ElementRegion>(MR))
2756 if (
const SymbolicRegion *BMR =
2757 dyn_cast<SymbolicRegion>(MR->getBaseRegion()))
2758 Sym = BMR->getSymbol();
2762 checkUseAfterFree(Sym, C, E);
2768 void MallocChecker::checkPostStmt(
const BlockExpr *BE,
2769 CheckerContext &C)
const {
2777 const BlockDataRegion *R =
2778 cast<BlockDataRegion>(C.getSVal(BE).getAsRegion());
2780 BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2781 E = R->referenced_vars_end();
2788 MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2790 for ( ; I != E; ++I) {
2791 const VarRegion *VR = I.getCapturedRegion();
2792 if (VR->getSuperRegion() == R) {
2793 VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2795 Regions.push_back(VR);
2799 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
2800 C.addTransition(state);
2805 const RefState *RS = C.getState()->get<RegionState>(Sym);
2806 return (RS && RS->isReleased());
2809 bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
2810 const CallExpr *CE, CheckerContext &C)
const {
2814 StringRef FunctionStr =
"";
2815 if (
const auto *FD = dyn_cast<FunctionDecl>(C.getStackFrame()->getDecl()))
2817 if (Body->getBeginLoc().isValid())
2821 C.getSourceManager(), C.getLangOpts());
2824 if (!FunctionStr.contains(
"__isl_"))
2830 if (
SymbolRef Sym = C.getSVal(Arg).getAsSymbol())
2831 if (
const RefState *RS = State->get<RegionState>(Sym))
2832 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
2834 C.addTransition(State);
2838 bool MallocChecker::checkUseAfterFree(
SymbolRef Sym, CheckerContext &C,
2839 const Stmt *S)
const {
2849 void MallocChecker::checkUseZeroAllocated(
SymbolRef Sym, CheckerContext &C,
2850 const Stmt *S)
const {
2853 if (
const RefState *RS = C.getState()->get<RegionState>(Sym)) {
2854 if (RS->isAllocatedOfSizeZero())
2855 ReportUseZeroAllocated(C, RS->getStmt()->getSourceRange(), Sym);
2857 else if (C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
2862 bool MallocChecker::checkDoubleDelete(
SymbolRef Sym, CheckerContext &C)
const {
2865 ReportDoubleDelete(C, Sym);
2872 void MallocChecker::checkLocation(SVal l,
bool isLoad,
const Stmt *S,
2873 CheckerContext &C)
const {
2876 checkUseAfterFree(Sym, C, S);
2877 checkUseZeroAllocated(Sym, C, S);
2885 bool Assumption)
const {
2886 RegionStateTy RS =
state->get<RegionState>();
2887 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
2889 ConstraintManager &CMgr =
state->getConstraintManager();
2890 ConditionTruthVal AllocFailed = CMgr.isNull(
state, I.getKey());
2891 if (AllocFailed.isConstrainedTrue())
2892 state =
state->remove<RegionState>(I.getKey());
2897 ReallocPairsTy RP =
state->get<ReallocPairs>();
2898 for (ReallocPairsTy::iterator I = RP.begin(), E = RP.end(); I != E; ++I) {
2900 ConstraintManager &CMgr =
state->getConstraintManager();
2901 ConditionTruthVal AllocFailed = CMgr.isNull(
state, I.getKey());
2902 if (!AllocFailed.isConstrainedTrue())
2905 SymbolRef ReallocSym = I.getData().ReallocatedSym;
2906 if (
const RefState *RS =
state->get<RegionState>(ReallocSym)) {
2907 if (RS->isReleased()) {
2908 switch (I.getData().Kind) {
2909 case OAR_ToBeFreedAfterFailure:
2911 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
2913 case OAR_DoNotTrackAfterFailure:
2914 state =
state->remove<RegionState>(ReallocSym);
2917 assert(I.getData().Kind == OAR_FreeOnFailure);
2921 state = state->remove<ReallocPairs>(I.getKey());
2927 bool MallocChecker::mayFreeAnyEscapedMemoryOrIsModeledExplicitly(
2932 EscapingSymbol =
nullptr;
2938 if (!(isa<SimpleFunctionCall>(Call) || isa<ObjCMethodCall>(Call)))
2942 if (
const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(Call)) {
2945 if (!Call->isInSystemHeader() || Call->argumentsMayEscape())
2958 return *FreeWhenDone;
2964 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
2965 if (FirstSlot.endswith(
"NoCopy"))
2972 if (FirstSlot.startswith(
"addPointer") ||
2973 FirstSlot.startswith(
"insertPointer") ||
2974 FirstSlot.startswith(
"replacePointer") ||
2975 FirstSlot.equals(
"valueWithPointer")) {
2982 if (Msg->getMethodFamily() ==
OMF_init) {
2983 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
2993 const FunctionDecl *FD = cast<SimpleFunctionCall>(Call)->getDecl();
3001 if (MemFunctionInfo.isMemFunction(FD, ASTC))
3005 if (!Call->isInSystemHeader())
3012 StringRef FName = II->
getName();
3016 if (FName.endswith(
"NoCopy")) {
3020 for (
unsigned i = 1; i < Call->getNumArgs(); ++i) {
3021 const Expr *ArgE = Call->getArgExpr(i)->IgnoreParenCasts();
3022 if (
const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3023 StringRef DeallocatorName = DE->getFoundDecl()->getName();
3024 if (DeallocatorName ==
"kCFAllocatorNull")
3035 if (FName ==
"funopen")
3036 if (Call->getNumArgs() >= 4 && Call->getArgSVal(4).isConstant(0))
3042 if (FName ==
"setbuf" || FName ==
"setbuffer" ||
3043 FName ==
"setlinebuf" || FName ==
"setvbuf") {
3044 if (Call->getNumArgs() >= 1) {
3045 const Expr *ArgE = Call->getArgExpr(0)->IgnoreParenCasts();
3046 if (
const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3047 if (
const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3048 if (D->getCanonicalDecl()->getName().find(
"std") != StringRef::npos)
3058 if (FName ==
"CGBitmapContextCreate" ||
3059 FName ==
"CGBitmapContextCreateWithData" ||
3060 FName ==
"CVPixelBufferCreateWithBytes" ||
3061 FName ==
"CVPixelBufferCreateWithPlanarBytes" ||
3062 FName ==
"OSAtomicEnqueue") {
3066 if (FName ==
"postEvent" &&
3071 if (FName ==
"postEvent" &&
3076 if (FName ==
"connectImpl" &&
3085 if (Call->argumentsMayEscape())
3097 return checkPointerEscapeAux(
State, Escaped, Call, Kind,
3106 return checkPointerEscapeAux(
State, Escaped, Call, Kind,
3111 return (RS->getAllocationFamily() == AF_CXXNewArray ||
3112 RS->getAllocationFamily() == AF_CXXNew);
3118 bool IsConstPointerEscape)
const {
3123 !mayFreeAnyEscapedMemoryOrIsModeledExplicitly(Call,
State,
3129 for (InvalidatedSymbols::const_iterator I = Escaped.begin(),
3134 if (EscapingSymbol && EscapingSymbol != sym)
3137 if (
const RefState *RS =
State->get<RegionState>(sym))
3138 if (RS->isAllocated() || RS->isAllocatedOfSizeZero())
3140 State =
State->set<RegionState>(sym, RefState::getEscaped(RS));
3147 ReallocPairsTy currMap = currState->get<ReallocPairs>();
3148 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3150 for (
const ReallocPairsTy::value_type &Pair : prevMap) {
3152 if (!currMap.lookup(sym))
3161 StringRef N = II->getName();
3162 if (N.contains_lower(
"ptr") || N.contains_lower(
"pointer")) {
3163 if (N.contains_lower(
"ref") || N.contains_lower(
"cnt") ||
3164 N.contains_lower(
"intrusive") || N.contains_lower(
"shared")) {
3173 BugReporterContext &BRC,
3174 PathSensitiveBugReport &BR) {
3178 const RefState *RSCurr = state->get<RegionState>(Sym);
3179 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3181 const Stmt *S = N->getStmtForDiagnostics();
3184 if (!S && (!RSCurr || RSCurr->getAllocationFamily() != AF_InnerBuffer))
3196 if (ReleaseDestructorLC) {
3197 if (
const auto *AE = dyn_cast<AtomicExpr>(S)) {
3199 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
3200 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
3201 if (ReleaseDestructorLC == CurrentLC ||
3202 ReleaseDestructorLC->
isParentOf(CurrentLC)) {
3203 BR.markInvalid(getTag(), S);
3214 std::unique_ptr<StackHintGeneratorForSymbol> StackHint =
nullptr;
3216 llvm::raw_svector_ostream
OS(Buf);
3219 if (isAllocated(RSCurr, RSPrev, S)) {
3220 Msg =
"Memory is allocated";
3221 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3222 Sym,
"Returned allocated memory");
3224 const auto Family = RSCurr->getAllocationFamily();
3229 case AF_CXXNewArray:
3230 case AF_IfNameIndex:
3231 Msg =
"Memory is released";
3232 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3233 Sym,
"Returning; memory was released");
3235 case AF_InnerBuffer: {
3236 const MemRegion *ObjRegion =
3238 const auto *TypedRegion = cast<TypedValueRegion>(ObjRegion);
3239 QualType ObjTy = TypedRegion->getValueType();
3240 OS <<
"Inner buffer of '" << ObjTy.getAsString() <<
"' ";
3243 OS <<
"deallocated by call to destructor";
3244 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3245 Sym,
"Returning; inner buffer was deallocated");
3247 OS <<
"reallocated by call to '";
3248 const Stmt *S = RSCurr->getStmt();
3249 if (
const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
3250 OS << MemCallE->getMethodDecl()->getNameAsString();
3251 }
else if (
const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
3252 OS << OpCallE->getDirectCallee()->getNameAsString();
3253 }
else if (
const auto *CallE = dyn_cast<CallExpr>(S)) {
3254 auto &CEMgr = BRC.getStateManager().getCallEventManager();
3255 CallEventRef<> Call = CEMgr.getSimpleCall(CallE, state, CurrentLC);
3256 const auto *D = dyn_cast_or_null<NamedDecl>(Call->getDecl());
3257 OS << (D ? D->getNameAsString() :
"unknown");
3260 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3261 Sym,
"Returning; inner buffer was reallocated");
3267 llvm_unreachable(
"Unhandled allocation family!");
3273 bool FoundAnyDestructor =
false;
3275 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(LC->getDecl())) {
3280 BR.markInvalid(getTag(), DD);
3281 }
else if (!FoundAnyDestructor) {
3282 assert(!ReleaseDestructorLC &&
3283 "There can be only one release point!");
3289 ReleaseDestructorLC = LC->getStackFrame();
3295 FoundAnyDestructor =
true;
3299 }
else if (isRelinquished(RSCurr, RSPrev, S)) {
3300 Msg =
"Memory ownership is transferred";
3301 StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym,
"");
3302 }
else if (hasReallocFailed(RSCurr, RSPrev, S)) {
3303 Mode = ReallocationFailed;
3304 Msg =
"Reallocation failed";
3305 StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
3306 Sym,
"Reallocation failed");
3310 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
3311 "We only support one failed realloc at a time.");
3312 BR.markInteresting(sym);
3313 FailedReallocSymbol = sym;
3318 }
else if (Mode == ReallocationFailed) {
3319 assert(FailedReallocSymbol &&
"No symbol to look for.");
3322 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
3324 Msg =
"Attempt to reallocate memory";
3325 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
3326 Sym,
"Returned reallocated memory");
3327 FailedReallocSymbol =
nullptr;
3340 PathDiagnosticLocation Pos;
3342 assert(RSCurr->getAllocationFamily() == AF_InnerBuffer);
3346 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
3347 BRC.getSourceManager());
3349 Pos = PathDiagnosticLocation(S, BRC.getSourceManager(),
3350 N->getLocationContext());
3353 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg,
true);
3354 BR.addCallStackHint(P, std::move(StackHint));
3359 const char *NL,
const char *Sep)
const {
3361 RegionStateTy RS =
State->get<RegionState>();
3363 if (!RS.isEmpty()) {
3364 Out << Sep <<
"MallocChecker :" << NL;
3365 for (RegionStateTy::iterator I = RS.begin(), E = RS.end(); I != E; ++I) {
3366 const RefState *RefS =
State->get<RegionState>(I.getKey());
3369 if (!CheckKind.hasValue())
3370 CheckKind = getCheckIfTracked(Family,
true);
3372 I.getKey()->dumpToStream(Out);
3374 I.getData().dump(Out);
3375 if (CheckKind.hasValue())
3376 Out <<
" (" << CheckNames[*CheckKind].
getName() <<
")";
3384 namespace allocation_state {
3389 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
3399 MallocChecker *checker = mgr.
getChecker<MallocChecker>();
3400 checker->ChecksEnabled[MallocChecker::CK_InnerPointerChecker] =
true;
3401 checker->CheckNames[MallocChecker::CK_InnerPointerChecker] =
3407 checker->MemFunctionInfo.ShouldIncludeOwnershipAnnotatedFunctions =
3411 bool ento::shouldRegisterDynamicMemoryModeling(
const LangOptions &LO) {
3415 #define REGISTER_CHECKER(name) \ 3416 void ento::register##name(CheckerManager &mgr) { \ 3417 MallocChecker *checker = mgr.getChecker<MallocChecker>(); \ 3418 checker->ChecksEnabled[MallocChecker::CK_##name] = true; \ 3419 checker->CheckNames[MallocChecker::CK_##name] = \ 3420 mgr.getCurrentCheckerName(); \ 3423 bool ento::shouldRegister##name(const LangOptions &LO) { return true; }
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
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.
const SymExpr * SymbolRef
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 ...
bool Zero(InterpState &S, CodePtr OpPC)
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
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
ArrayRef< ParmVarDecl * > parameters() const
static bool isLocType(QualType T)
Represents any expression that calls an Objective-C method.
Optional< Expr * > getArraySize()
static bool printAllocDeallocName(raw_ostream &os, CheckerContext &C, const Expr *E)
Print names of allocators and deallocators.
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 void printExpectedAllocName(raw_ostream &os, const MemFunctionInfoTy &MemFunctionInfo, CheckerContext &C, const Expr *E)
Print expected name of an allocator based on the deallocator's family derived from the DeallocExpr...
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...
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.
CheckerNameRef getCurrentCheckerName() const
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.
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.
static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, AllocationFamily Family=AF_Malloc, Optional< SVal > RetVal=None)
Update the RefState to reflect the new memory allocation.
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 AllocationFamily getAllocationFamily(const MemFunctionInfoTy &MemFunctionInfo, CheckerContext &C, const Stmt *S)
Determine family of a deallocation expression.
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.
static bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
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 void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family)
Print expected name of a deallocator based on the allocator's family.
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, ProgramStateRef prevState)
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)
bool NE(InterpState &S, CodePtr OpPC)
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
AnalyzerOptions & getAnalyzerOptions()
static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE)
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...
OwnershipAfterReallocKind
The state of 'fromPtr' after reallocation is known to have failed.
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
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.
static bool isReleased(SymbolRef Sym, CheckerContext &C)
Check if the memory associated with this symbol was released.
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