84#include "llvm/ADT/STLExtras.h"
85#include "llvm/ADT/SmallVector.h"
86#include "llvm/ADT/StringExtras.h"
87#include "llvm/Support/Casting.h"
88#include "llvm/Support/Compiler.h"
89#include "llvm/Support/ErrorHandling.h"
90#include "llvm/Support/raw_ostream.h"
97using namespace std::placeholders;
109enum AllocationFamilyKind {
120struct AllocationFamily {
121 AllocationFamilyKind Kind;
122 std::optional<StringRef> CustomName;
124 explicit AllocationFamily(AllocationFamilyKind AKind,
125 std::optional<StringRef> Name = std::nullopt)
126 : Kind(AKind), CustomName(Name) {
127 assert((Kind != AF_Custom || CustomName.has_value()) &&
128 "Custom family must specify also the name");
131 if (Kind == AF_Custom && CustomName.value() ==
"malloc") {
133 CustomName = std::nullopt;
138 return std::tie(Kind, CustomName) == std::tie(
Other.Kind,
Other.CustomName);
142 return !(*
this ==
Other);
145 void Profile(llvm::FoldingSetNodeID &ID)
const {
148 if (Kind == AF_Custom)
149 ID.AddString(CustomName.value());
194 AllocationFamily Family;
196 RefState(Kind k,
const Stmt *s, AllocationFamily family)
197 : S(s), K(k), Family(family) {
198 assert(family.Kind != AF_None);
202 bool isAllocated()
const {
203 return K == AllocatedOfAnySize || K == AllocatedOfSizeZero;
205 bool isAllocatedOfSizeZero()
const {
return K == AllocatedOfSizeZero; }
206 bool isReleased()
const {
return K == Released; }
207 bool isRelinquished()
const {
return K == Relinquished; }
208 bool isEscaped()
const {
return K == Escaped; }
209 AllocationFamily getAllocationFamily()
const {
return Family; }
210 const Stmt *getStmt()
const {
return S; }
213 return K ==
X.K && S ==
X.S && Family ==
X.Family;
216 static RefState getAllocated(AllocationFamily F,
const Stmt *S) {
217 return RefState(AllocatedOfAnySize, S, F);
219 static RefState getAllocatedOfSizeZero(
const RefState *RS) {
220 return RefState(AllocatedOfSizeZero, RS->getStmt(),
221 RS->getAllocationFamily());
223 static RefState getReleased(AllocationFamily family,
const Stmt *s) {
224 return RefState(Released, s, family);
226 static RefState getRelinquished(AllocationFamily family,
const Stmt *s) {
227 return RefState(Relinquished, s, family);
229 static RefState getEscaped(
const RefState *RS) {
230 return RefState(Escaped, RS->getStmt(), RS->getAllocationFamily());
233 void Profile(llvm::FoldingSetNodeID &ID)
const {
239 LLVM_DUMP_METHOD
void dump(raw_ostream &
OS)
const {
241 case AllocatedOfAnySize:
244#define CASE(ID) case ID: OS << #ID; break;
245 CASE(AllocatedOfSizeZero)
252 LLVM_DUMP_METHOD
void dump()
const {
dump(llvm::errs()); }
267 AllocationFamily Family,
268 std::optional<SVal> RetVal = std::nullopt);
282enum OwnershipAfterReallocKind {
284 OAR_ToBeFreedAfterFailure,
294 OAR_DoNotTrackAfterFailure
307 OwnershipAfterReallocKind Kind;
309 ReallocPair(
SymbolRef S, OwnershipAfterReallocKind K)
310 : ReallocatedSym(S), Kind(K) {}
311 void Profile(llvm::FoldingSetNodeID &ID)
const {
313 ID.AddPointer(ReallocatedSym);
316 return ReallocatedSym ==
X.ReallocatedSym &&
352#define BUGTYPE_PROVIDER(NAME, DEF) \
353 struct NAME : virtual public CheckerFrontend { \
354 BugType NAME##Bug{this, DEF, categories::MemoryError}; \
376#undef BUGTYPE_PROVIDER
378template <
typename... BT_PROVIDERS>
379struct DynMemFrontend :
virtual public CheckerFrontend,
public BT_PROVIDERS... {
380 template <
typename T>
const T *getAs()
const {
381 if constexpr (std::is_same_v<T, CheckerFrontend> ||
382 (std::is_same_v<T, BT_PROVIDERS> || ...))
383 return static_cast<const T *
>(
this);
394 check::DeadSymbols, check::PointerEscape, check::ConstPointerEscape,
395 check::PreStmt<ReturnStmt>, check::EndFunction, check::PreCall,
396 check::PostCall, eval::Call, check::NewAllocator,
397 check::PostStmt<BlockExpr>, check::PostObjCMessage, check::Location,
404 bool ShouldIncludeOwnershipAnnotatedFunctions =
false;
406 bool ShouldRegisterNoOwnershipChangeVisitor =
false;
414 bool ModelAllocationFailure =
false;
423 DynMemFrontend<DoubleFree, Leak, UseFree, BadFree, FreeAlloca, OffsetFree,
426 DynMemFrontend<DoubleFree, UseFree, BadFree, OffsetFree, UseZeroAllocated>
428 DynMemFrontend<Leak> NewDeleteLeaksChecker;
429 DynMemFrontend<FreeAlloca, MismatchedDealloc> MismatchedDeallocatorChecker;
430 DynMemFrontend<UseFree> InnerPointerChecker;
433 CheckerFrontendWithBugType TaintedAllocChecker{
"Tainted Memory Allocation",
436 using LeakInfo = std::pair<const ExplodedNode *, const MemRegion *>;
438 void checkPreCall(
const CallEvent &
Call, CheckerContext &
C)
const;
439 void checkPostCall(
const CallEvent &
Call, CheckerContext &
C)
const;
440 bool evalCall(
const CallEvent &
Call, CheckerContext &
C)
const;
443 handleSmartPointerConstructorArguments(
const CallEvent &
Call,
448 void checkNewAllocator(
const CXXAllocatorCall &
Call, CheckerContext &
C)
const;
449 void checkPostObjCMessage(
const ObjCMethodCall &
Call, CheckerContext &
C)
const;
450 void checkPostStmt(
const BlockExpr *BE, CheckerContext &
C)
const;
451 void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &
C)
const;
452 void checkPreStmt(
const ReturnStmt *S, CheckerContext &
C)
const;
453 void checkEndFunction(
const ReturnStmt *S, CheckerContext &
C)
const;
455 bool Assumption)
const;
456 void checkLocation(SVal l,
bool isLoad,
const Stmt *S,
457 CheckerContext &
C)
const;
461 const CallEvent *
Call,
465 const CallEvent *
Call,
469 const char *NL,
const char *Sep)
const override;
471 StringRef getDebugTag()
const override {
return "MallocChecker"; }
474#define CHECK_FN(NAME) \
475 void NAME(ProgramStateRef State, const CallEvent &Call, CheckerContext &C) \
507 {{CDM::CLibrary, {
"getline"}, 3}, &MallocChecker::preGetDelimOrGetLine},
508 {{CDM::CLibrary, {
"getdelim"}, 4}, &MallocChecker::preGetDelimOrGetLine},
511 const CallDescriptionMap<CheckFn> PostFnMap{
514 {{CDM::CLibrary, {
"getline"}, 3}, &MallocChecker::checkGetDelimOrGetLine},
515 {{CDM::CLibrary, {
"getdelim"}, 4},
516 &MallocChecker::checkGetDelimOrGetLine},
519 const CallDescriptionMap<CheckFn> FreeingMemFnMap{
520 {{CDM::CLibrary, {
"free"}, 1}, &MallocChecker::checkFree},
521 {{CDM::CLibrary, {
"if_freenameindex"}, 1},
522 &MallocChecker::checkIfFreeNameIndex},
523 {{CDM::CLibrary, {
"kfree"}, 1}, &MallocChecker::checkFree},
524 {{CDM::CLibrary, {
"g_free"}, 1}, &MallocChecker::checkFree},
527 bool isFreeingCall(
const CallEvent &
Call)
const;
528 static bool isFreeingOwnershipAttrCall(
const FunctionDecl *
Func);
529 static bool isFreeingOwnershipAttrCall(
const CallEvent &
Call);
530 static bool isAllocatingOwnershipAttrCall(
const FunctionDecl *
Func);
531 static bool isAllocatingOwnershipAttrCall(
const CallEvent &
Call);
533 friend class NoMemOwnershipChangeVisitor;
535 CallDescriptionMap<CheckFn> AllocaMemFnMap{
536 {{CDM::CLibrary, {
"alloca"}, 1}, &MallocChecker::checkAlloca},
537 {{CDM::CLibrary, {
"_alloca"}, 1}, &MallocChecker::checkAlloca},
541 {{CDM::CLibrary, {
"__builtin_alloca_with_align"}, 2},
542 &MallocChecker::checkAlloca},
545 CallDescriptionMap<CheckFn> AllocatingMemFnMap{
546 {{CDM::CLibrary, {
"malloc"}, 1}, &MallocChecker::checkBasicAllocMayFail},
547 {{CDM::CLibrary, {
"malloc"}, 3}, &MallocChecker::checkKernelMalloc},
548 {{CDM::CLibrary, {
"calloc"}, 2}, &MallocChecker::checkCalloc},
549 {{CDM::CLibrary, {
"valloc"}, 1}, &MallocChecker::checkBasicAlloc},
550 {{CDM::CLibrary, {
"strndup"}, 2}, &MallocChecker::checkStrdup},
551 {{CDM::CLibrary, {
"strdup"}, 1}, &MallocChecker::checkStrdup},
552 {{CDM::CLibrary, {
"_strdup"}, 1}, &MallocChecker::checkStrdup},
553 {{CDM::CLibrary, {
"kmalloc"}, 2}, &MallocChecker::checkKernelMalloc},
554 {{CDM::CLibrary, {
"if_nameindex"}, 0}, &MallocChecker::checkIfNameIndex},
555 {{CDM::CLibrary, {
"wcsdup"}, 1}, &MallocChecker::checkStrdup},
556 {{CDM::CLibrary, {
"_wcsdup"}, 1}, &MallocChecker::checkStrdup},
557 {{CDM::CLibrary, {
"g_malloc"}, 1}, &MallocChecker::checkBasicAlloc},
558 {{CDM::CLibrary, {
"g_malloc0"}, 1}, &MallocChecker::checkGMalloc0},
559 {{CDM::CLibrary, {
"g_try_malloc"}, 1}, &MallocChecker::checkBasicAlloc},
560 {{CDM::CLibrary, {
"g_try_malloc0"}, 1}, &MallocChecker::checkGMalloc0},
561 {{CDM::CLibrary, {
"g_memdup"}, 2}, &MallocChecker::checkGMemdup},
562 {{CDM::CLibrary, {
"g_malloc_n"}, 2}, &MallocChecker::checkGMallocN},
563 {{CDM::CLibrary, {
"g_malloc0_n"}, 2}, &MallocChecker::checkGMallocN0},
564 {{CDM::CLibrary, {
"g_try_malloc_n"}, 2}, &MallocChecker::checkGMallocN},
565 {{CDM::CLibrary, {
"g_try_malloc0_n"}, 2}, &MallocChecker::checkGMallocN0},
568 CallDescriptionMap<CheckFn> ReallocatingMemFnMap{
569 {{CDM::CLibrary, {
"realloc"}, 2},
570 std::bind(&MallocChecker::checkRealloc, _1,
_2, _3, _4,
false)},
571 {{CDM::CLibrary, {
"reallocf"}, 2},
572 std::bind(&MallocChecker::checkRealloc, _1,
_2, _3, _4,
true)},
573 {{CDM::CLibrary, {
"g_realloc"}, 2},
574 std::bind(&MallocChecker::checkRealloc, _1,
_2, _3, _4,
false)},
575 {{CDM::CLibrary, {
"g_try_realloc"}, 2},
576 std::bind(&MallocChecker::checkRealloc, _1,
_2, _3, _4,
false)},
577 {{CDM::CLibrary, {
"g_realloc_n"}, 3}, &MallocChecker::checkReallocN},
578 {{CDM::CLibrary, {
"g_try_realloc_n"}, 3}, &MallocChecker::checkReallocN},
581 bool isMemCall(
const CallEvent &
Call)
const;
582 void reportTaintBug(StringRef Msg,
ProgramStateRef State, CheckerContext &
C,
583 llvm::ArrayRef<SymbolRef> TaintedSyms,
584 AllocationFamily Family)
const;
586 void checkTaintedness(CheckerContext &
C,
const CallEvent &
Call,
588 AllocationFamily Family)
const;
591 mutable std::optional<uint64_t> KernelZeroFlagVal;
593 using KernelZeroSizePtrValueTy = std::optional<int>;
598 mutable std::optional<KernelZeroSizePtrValueTy> KernelZeroSizePtrValue;
603 processNewAllocation(
const CXXAllocatorCall &
Call, CheckerContext &
C,
604 AllocationFamily Family)
const;
615 ProcessZeroAllocCheck(CheckerContext &
C,
const CallEvent &
Call,
617 std::optional<SVal> RetVal = std::nullopt);
636 MallocMemReturnsAttr(CheckerContext &
C,
const CallEvent &
Call,
646 const CallEvent &
Call,
648 bool isAlloca)
const;
660 MallocMemAux(CheckerContext &
C,
const CallEvent &
Call,
const Expr *SizeEx,
673 const CallEvent &
Call, SVal Size,
675 AllocationFamily Family)
const;
688 llvm::ArrayRef<unsigned> SizeArgIndexes = {})
const;
692 [[nodiscard]] std::optional<ProgramStateRef>
693 performKernelMalloc(
const CallEvent &
Call, CheckerContext &
C,
714 const CallEvent &
Call,
715 const OwnershipAttr *Att,
739 unsigned Num,
bool Hold,
bool &IsKnownToBeAllocated,
740 AllocationFamily Family,
bool ReturnsNullOnFailure =
false)
const;
764 FreeMemAux(CheckerContext &
C,
const Expr *ArgExpr,
const CallEvent &
Call,
766 AllocationFamily Family,
bool ReturnsNullOnFailure =
false,
767 std::optional<SVal> ArgValOpt = {})
const;
783 ReallocMemAux(CheckerContext &
C,
const CallEvent &
Call,
bool ShouldFreeOnFail,
785 bool SuffixWithN =
false)
const;
792 [[nodiscard]]
static SVal evalMulForBufferSize(CheckerContext &
C,
794 const Expr *BlockBytes);
802 const CallEvent &
Call,
807 bool suppressDeallocationsInSuspiciousContexts(
const CallEvent &
Call,
808 CheckerContext &
C)
const;
811 bool checkUseAfterFree(
SymbolRef Sym, CheckerContext &
C,
const Stmt *S)
const;
815 void checkUseZeroAllocated(
SymbolRef Sym, CheckerContext &
C,
816 const Stmt *S)
const;
829 bool ignoreDirectEscapeTo(
const CallEvent *
Call,
837 bool IsConstPointerEscape)
const;
840 void checkEscapeOnReturn(
const ReturnStmt *S, CheckerContext &
C)
const;
849 const T *getRelevantFrontendAs(AllocationFamily Family)
const;
852 const T *getRelevantFrontendAs(CheckerContext &
C,
SymbolRef Sym)
const;
854 static bool SummarizeValue(raw_ostream &os, SVal
V);
856 const MemRegion *MR);
858 void HandleNonHeapDealloc(CheckerContext &
C, SVal ArgVal, SourceRange Range,
859 const Expr *DeallocExpr,
860 AllocationFamily Family)
const;
862 void HandleFreeAlloca(CheckerContext &
C, SVal ArgVal,
863 SourceRange Range)
const;
865 void HandleMismatchedDealloc(CheckerContext &
C, SourceRange Range,
866 const Expr *DeallocExpr,
const RefState *RS,
867 SymbolRef Sym,
bool OwnershipTransferred)
const;
869 void HandleOffsetFree(CheckerContext &
C, SVal ArgVal, SourceRange Range,
870 const Expr *DeallocExpr, AllocationFamily Family,
871 const Expr *AllocExpr =
nullptr)
const;
873 void HandleUseAfterFree(CheckerContext &
C, SourceRange Range,
876 void HandleDoubleFree(CheckerContext &
C, SourceRange Range,
bool Released,
879 void HandleUseZeroAlloc(CheckerContext &
C, SourceRange Range,
882 void HandleFunctionPtrFree(CheckerContext &
C, SVal ArgVal, SourceRange Range,
883 const Expr *FreeExpr,
884 AllocationFamily Family)
const;
888 static LeakInfo getAllocationSite(
const ExplodedNode *N,
SymbolRef Sym,
891 void HandleLeak(
SymbolRef Sym, ExplodedNode *N, CheckerContext &
C)
const;
904class NoMemOwnershipChangeVisitor final :
public NoOwnershipChangeVisitor {
913 bool isFreeingCallAsWritten(
const CallExpr &
Call)
const {
914 const auto *MallocChk =
static_cast<const MallocChecker *
>(&Checker);
915 if (MallocChk->FreeingMemFnMap.lookupAsWritten(
Call) ||
916 MallocChk->ReallocatingMemFnMap.lookupAsWritten(
Call))
919 if (
const auto *
Func =
920 llvm::dyn_cast_or_null<FunctionDecl>(
Call.getCalleeDecl()))
921 return MallocChecker::isFreeingOwnershipAttrCall(
Func);
928 return CallEnterState->get<RegionState>(Sym) !=
929 CallExitEndState->get<RegionState>(Sym);
936 bool doesFnIntendToHandleOwnership(
const Decl *Callee,
937 ASTContext &ACtx)
final {
938 const FunctionDecl *FD = dyn_cast<FunctionDecl>(Callee);
953 using namespace clang::ast_matchers;
958 for (BoundNodes
Match : Matches) {
959 if (
Match.getNodeAs<CXXDeleteExpr>(
"delete"))
962 if (
const auto *
Call =
Match.getNodeAs<CallExpr>(
"call"))
963 if (isFreeingCallAsWritten(*
Call))
975 N->getState()->getStateManager().getContext().getSourceManager());
976 return std::make_shared<PathDiagnosticEventPiece>(
977 L,
"Returning without deallocating memory or storing the pointer for "
978 "later deallocation");
982 NoMemOwnershipChangeVisitor(
SymbolRef Sym,
const MallocChecker *Checker)
983 : NoOwnershipChangeVisitor(Sym, Checker) {}
985 void Profile(llvm::FoldingSetNodeID &ID)
const override {
1004 enum NotificationMode { Normal, ReallocationFailed };
1010 NotificationMode Mode;
1017 const StackFrame *ReleaseFunctionSF;
1022 MallocBugVisitor(
SymbolRef S,
bool isLeak =
false)
1023 : Sym(S), Mode(Normal), FailedReallocSymbol(
nullptr),
1024 ReleaseFunctionSF(
nullptr), IsLeak(isLeak) {}
1026 static void *getTag() {
1031 void Profile(llvm::FoldingSetNodeID &ID)
const override {
1032 ID.AddPointer(getTag());
1037 static inline bool isAllocated(
const RefState *RSCurr,
const RefState *RSPrev,
1039 return (isa_and_nonnull<CallExpr, CXXNewExpr>(Stmt) &&
1040 (RSCurr && RSCurr->isAllocated())) &&
1041 (!RSPrev || !RSPrev->isAllocated());
1046 static inline bool isReleased(
const RefState *RSCurr,
const RefState *RSPrev,
1049 (RSCurr && RSCurr->isReleased()) && (!RSPrev || !RSPrev->isReleased());
1050 assert(!IsReleased || (isa_and_nonnull<CallExpr, CXXDeleteExpr>(Stmt)) ||
1051 (!Stmt && RSCurr->getAllocationFamily().Kind == AF_InnerBuffer));
1056 static inline bool isRelinquished(
const RefState *RSCurr,
1057 const RefState *RSPrev,
const Stmt *Stmt) {
1059 isa_and_nonnull<CallExpr, ObjCMessageExpr, ObjCPropertyRefExpr>(Stmt) &&
1060 (RSCurr && RSCurr->isRelinquished()) &&
1061 (!RSPrev || !RSPrev->isRelinquished()));
1068 static inline bool hasReallocFailed(
const RefState *RSCurr,
1069 const RefState *RSPrev,
1071 return ((!isa_and_nonnull<CallExpr>(Stmt)) &&
1072 (RSCurr && RSCurr->isAllocated())) &&
1073 (RSPrev && !RSPrev->isAllocated());
1077 BugReporterContext &BRC,
1078 PathSensitiveBugReport &BR)
override;
1081 BugReporterContext &BRC,
1082 PathSensitiveBugReport &BR)
override {
1088 return std::make_shared<PathDiagnosticEventPiece>(L, BR.
getDescription(),
1093 class StackHintGeneratorForReallocationFailed
1094 :
public StackHintGeneratorForSymbol {
1096 StackHintGeneratorForReallocationFailed(
SymbolRef S, StringRef M)
1097 : StackHintGeneratorForSymbol(S, M) {}
1099 std::string getMessageForArg(
const Expr *ArgE,
unsigned ArgIndex)
override {
1103 SmallString<200> buf;
1104 llvm::raw_svector_ostream os(buf);
1106 os <<
"Reallocation of " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
1107 <<
" parameter failed";
1109 return std::string(os.str());
1112 std::string getMessageForReturn(
const CallExpr *CallExpr)
override {
1113 return "Reallocation of returned value failed";
1131 bool VisitSymbol(
SymbolRef sym)
override {
1132 state = state->remove<RegionState>(sym);
1152 explicit EscapeTrackedCallback(
ProgramStateRef S) : State(std::move(S)) {}
1155 bool VisitSymbol(
SymbolRef Sym)
override {
1156 if (
const RefState *RS = State->get<RegionState>(Sym)) {
1157 if (RS->isAllocated()) {
1158 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
1166 EscapeTrackedRegionsReachableFrom(ArrayRef<const MemRegion *> Roots,
1173 SmallVector<const MemRegion *, 10> Regions = llvm::to_vector<10>(Roots);
1174 EscapeTrackedCallback Visitor(State);
1175 State->scanReachableSymbols(Regions, Visitor);
1176 return Visitor.State;
1179 friend class SymbolVisitor;
1188 if (Kind != OO_New && Kind != OO_Array_New)
1204 if (Kind != OO_Delete && Kind != OO_Array_Delete)
1215 return L.
isInvalid() || (!HasBody && SM.isInSystemHeader(L));
1222bool MallocChecker::isFreeingOwnershipAttrCall(
const CallEvent &
Call) {
1223 const auto *
Func = dyn_cast_or_null<FunctionDecl>(
Call.getDecl());
1225 return Func && isFreeingOwnershipAttrCall(
Func);
1228bool MallocChecker::isFreeingOwnershipAttrCall(
const FunctionDecl *
Func) {
1229 if (
Func->hasAttrs()) {
1230 auto IsFreeing = [](
const OwnershipAttr *I) {
1231 OwnershipAttr::OwnershipKind OwnKind = I->getOwnKind();
1232 return OwnKind == OwnershipAttr::Takes || OwnKind == OwnershipAttr::Holds;
1234 return llvm::any_of(
Func->specific_attrs<OwnershipAttr>(), IsFreeing);
1239bool MallocChecker::isFreeingCall(
const CallEvent &
Call)
const {
1243 return isFreeingOwnershipAttrCall(
Call);
1246bool MallocChecker::isAllocatingOwnershipAttrCall(
const CallEvent &
Call) {
1247 const auto *
Func = dyn_cast_or_null<FunctionDecl>(
Call.getDecl());
1249 return Func && isAllocatingOwnershipAttrCall(
Func);
1252bool MallocChecker::isAllocatingOwnershipAttrCall(
const FunctionDecl *
Func) {
1253 auto IsAllocating = [](
const OwnershipAttr *I) {
1254 return I->getOwnKind() == OwnershipAttr::Returns;
1256 return llvm::any_of(
Func->specific_attrs<OwnershipAttr>(), IsAllocating);
1259bool MallocChecker::isMemCall(
const CallEvent &
Call)
const {
1264 if (!ShouldIncludeOwnershipAnnotatedFunctions)
1267 const auto *
Func = dyn_cast<FunctionDecl>(
Call.getDecl());
1268 return Func &&
Func->hasAttr<OwnershipAttr>();
1271std::optional<ProgramStateRef>
1272MallocChecker::performKernelMalloc(
const CallEvent &
Call, CheckerContext &
C,
1290 ASTContext &Ctx =
C.getASTContext();
1293 if (!KernelZeroFlagVal) {
1295 case llvm::Triple::FreeBSD:
1296 KernelZeroFlagVal = 0x0100;
1298 case llvm::Triple::NetBSD:
1299 KernelZeroFlagVal = 0x0002;
1301 case llvm::Triple::OpenBSD:
1302 KernelZeroFlagVal = 0x0008;
1304 case llvm::Triple::Linux:
1306 KernelZeroFlagVal = 0x8000;
1314 return std::nullopt;
1321 if (
Call.getNumArgs() < 2)
1322 return std::nullopt;
1324 const Expr *FlagsEx =
Call.getArgExpr(
Call.getNumArgs() - 1);
1325 const SVal
V =
C.getSVal(FlagsEx);
1329 return std::nullopt;
1332 NonLoc Flags =
V.castAs<NonLoc>();
1333 NonLoc ZeroFlag =
C.getSValBuilder()
1334 .makeIntVal(*KernelZeroFlagVal, FlagsEx->
getType())
1336 SVal MaskedFlagsUC =
C.getSValBuilder().evalBinOpNN(State, BO_And,
1339 if (MaskedFlagsUC.isUnknownOrUndef())
1340 return std::nullopt;
1341 DefinedSVal MaskedFlags = MaskedFlagsUC.castAs<DefinedSVal>();
1345 std::tie(TrueState, FalseState) = State->assume(MaskedFlags);
1348 if (TrueState && !FalseState) {
1349 SVal ZeroVal =
C.getSValBuilder().makeZeroVal(Ctx.
CharTy);
1350 return MallocMemAux(
C,
Call,
Call.getArgExpr(0), ZeroVal, TrueState,
1351 AllocationFamily(AF_Malloc));
1354 return std::nullopt;
1357SVal MallocChecker::evalMulForBufferSize(CheckerContext &
C,
const Expr *Blocks,
1358 const Expr *BlockBytes) {
1359 SValBuilder &SB =
C.getSValBuilder();
1360 SVal BlocksVal =
C.getSVal(Blocks);
1361 SVal BlockBytesVal =
C.getSVal(BlockBytes);
1363 SVal TotalSize = SB.
evalBinOp(State, BO_Mul, BlocksVal, BlockBytesVal,
1369 const CallEvent &
Call,
1370 CheckerContext &
C)
const {
1371 State = MallocMemAux(
C,
Call,
Call.getArgExpr(0), UndefinedVal(), State,
1372 AllocationFamily(AF_Malloc));
1373 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1374 C.addTransition(State);
1378 const CallEvent &
Call,
1379 CheckerContext &
C)
const {
1380 C.addTransition(FailedAlloc(
C,
Call, State, {0}));
1382 State = MallocMemAux(
C,
Call,
Call.getArgExpr(0), UndefinedVal(), State,
1383 AllocationFamily(AF_Malloc));
1384 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1385 C.addTransition(State);
1389 const CallEvent &
Call,
1390 CheckerContext &
C)
const {
1391 std::optional<ProgramStateRef> MaybeState =
1392 performKernelMalloc(
Call,
C, State);
1394 State = *MaybeState;
1396 State = MallocMemAux(
C,
Call,
Call.getArgExpr(0), UndefinedVal(), State,
1397 AllocationFamily(AF_Malloc));
1398 C.addTransition(State);
1422 bool ShouldFreeOnFail)
const {
1432 if (StandardRealloc)
1433 C.addTransition(FailedAlloc(
C,
Call, State, {1}));
1435 State = ReallocMemAux(
C,
Call, ShouldFreeOnFail, State,
1436 AllocationFamily(AF_Malloc));
1437 State = ProcessZeroAllocCheck(
C,
Call, 1, State);
1438 C.addTransition(State);
1442 CheckerContext &
C)
const {
1443 C.addTransition(FailedAlloc(
C,
Call, State, {0, 1}));
1445 State = CallocMem(
C,
Call, State);
1446 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1447 State = ProcessZeroAllocCheck(
C,
Call, 1, State);
1448 C.addTransition(State);
1452 CheckerContext &
C)
const {
1453 bool IsKnownToBeAllocatedMemory =
false;
1454 if (suppressDeallocationsInSuspiciousContexts(
Call,
C))
1456 State = FreeMemAux(
C,
Call, State, 0,
false, IsKnownToBeAllocatedMemory,
1457 AllocationFamily(AF_Malloc));
1458 C.addTransition(State);
1462 CheckerContext &
C)
const {
1463 State = MallocMemAux(
C,
Call,
Call.getArgExpr(0), UndefinedVal(), State,
1464 AllocationFamily(AF_Alloca));
1465 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1466 C.addTransition(State);
1470 CheckerContext &
C)
const {
1471 const auto *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
1475 C.addTransition(FailedAlloc(
C,
Call, State));
1477 State = MallocMemAux(
C,
Call, UnknownVal(), UnknownVal(), State,
1478 AllocationFamily(AF_Malloc));
1479 C.addTransition(State);
1483 const CallEvent &
Call,
1484 CheckerContext &
C)
const {
1485 C.addTransition(FailedAlloc(
C,
Call, State));
1489 State = MallocMemAux(
C,
Call, UnknownVal(), UnknownVal(), State,
1490 AllocationFamily(AF_IfNameIndex));
1491 C.addTransition(State);
1495 const CallEvent &
Call,
1496 CheckerContext &
C)
const {
1497 bool IsKnownToBeAllocatedMemory =
false;
1498 State = FreeMemAux(
C,
Call, State, 0,
false, IsKnownToBeAllocatedMemory,
1499 AllocationFamily(AF_IfNameIndex));
1500 C.addTransition(State);
1512 if (BuffType.isNull() || !BuffType->isVoidPointerType())
1518 const CallEvent &
Call,
1519 CheckerContext &
C)
const {
1520 bool IsKnownToBeAllocatedMemory =
false;
1521 const auto *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
1531 const FunctionDecl *FD =
C.getCalleeDecl(CE);
1534 auto RetVal = State->getSVal(BufArg,
Call.getStackFrame());
1535 State = State->BindExpr(CE,
C.getStackFrame(), RetVal);
1536 C.addTransition(State);
1542 State = MallocMemAux(
C,
Call, CE->getArg(0), UndefinedVal(), State,
1543 AllocationFamily(AF_CXXNew));
1544 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1547 State = MallocMemAux(
C,
Call, CE->getArg(0), UndefinedVal(), State,
1548 AllocationFamily(AF_CXXNewArray));
1549 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1552 State = FreeMemAux(
C,
Call, State, 0,
false, IsKnownToBeAllocatedMemory,
1553 AllocationFamily(AF_CXXNew));
1555 case OO_Array_Delete:
1556 State = FreeMemAux(
C,
Call, State, 0,
false, IsKnownToBeAllocatedMemory,
1557 AllocationFamily(AF_CXXNewArray));
1560 assert(
false &&
"not a new/delete operator");
1564 C.addTransition(State);
1568 CheckerContext &
C)
const {
1569 SValBuilder &svalBuilder =
C.getSValBuilder();
1571 State = MallocMemAux(
C,
Call,
Call.getArgExpr(0), zeroVal, State,
1572 AllocationFamily(AF_Malloc));
1573 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1574 C.addTransition(State);
1578 CheckerContext &
C)
const {
1579 State = MallocMemAux(
C,
Call,
Call.getArgExpr(1), UnknownVal(), State,
1580 AllocationFamily(AF_Malloc));
1581 State = ProcessZeroAllocCheck(
C,
Call, 1, State);
1582 C.addTransition(State);
1586 CheckerContext &
C)
const {
1587 SVal
Init = UndefinedVal();
1588 SVal TotalSize = evalMulForBufferSize(
C,
Call.getArgExpr(0),
Call.getArgExpr(1));
1589 State = MallocMemAux(
C,
Call, TotalSize,
Init, State,
1590 AllocationFamily(AF_Malloc));
1591 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1592 State = ProcessZeroAllocCheck(
C,
Call, 1, State);
1593 C.addTransition(State);
1597 CheckerContext &
C)
const {
1598 SValBuilder &SB =
C.getSValBuilder();
1600 SVal TotalSize = evalMulForBufferSize(
C,
Call.getArgExpr(0),
Call.getArgExpr(1));
1601 State = MallocMemAux(
C,
Call, TotalSize,
Init, State,
1602 AllocationFamily(AF_Malloc));
1603 State = ProcessZeroAllocCheck(
C,
Call, 0, State);
1604 State = ProcessZeroAllocCheck(
C,
Call, 1, State);
1605 C.addTransition(State);
1610 assert(FD &&
"a CallDescription cannot match a call without a Decl");
1615 const CallEvent &
Call,
1616 CheckerContext &
C)
const {
1630 bool IsKnownToBeAllocated =
false;
1631 State = FreeMemAux(
C,
Call.getArgExpr(0),
Call, State,
false,
1632 IsKnownToBeAllocated, AllocationFamily(AF_Malloc),
false,
1635 C.addTransition(State);
1639 const CallEvent &
Call,
1640 CheckerContext &
C)
const {
1648 const CallExpr *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
1654 if (!LinePtrOpt || !SizeOpt || LinePtrOpt->isUnknownOrUndef() ||
1655 SizeOpt->isUnknownOrUndef())
1658 const auto LinePtr = LinePtrOpt->getAs<DefinedSVal>();
1659 const auto Size = SizeOpt->getAs<DefinedSVal>();
1660 const MemRegion *LinePtrReg = LinePtr->getAsRegion();
1666 AllocationFamily(AF_Malloc), *LinePtr));
1670 CheckerContext &
C)
const {
1671 State = ReallocMemAux(
C,
Call,
false, State,
1672 AllocationFamily(AF_Malloc),
1674 State = ProcessZeroAllocCheck(
C,
Call, 1, State);
1675 State = ProcessZeroAllocCheck(
C,
Call, 2, State);
1676 C.addTransition(State);
1680 const CallEvent &
Call,
1681 CheckerContext &
C)
const {
1682 const auto *CE = dyn_cast_or_null<CallExpr>(
Call.getOriginExpr());
1685 const FunctionDecl *FD =
C.getCalleeDecl(CE);
1688 if (ShouldIncludeOwnershipAnnotatedFunctions ||
1689 MismatchedDeallocatorChecker.isEnabled()) {
1694 switch (I->getOwnKind()) {
1695 case OwnershipAttr::Returns:
1696 State = MallocMemReturnsAttr(
C,
Call, I, State);
1698 case OwnershipAttr::Takes:
1699 case OwnershipAttr::Holds:
1700 State = FreeMemAttr(
C,
Call, I, State);
1705 C.addTransition(State);
1708bool MallocChecker::evalCall(
const CallEvent &
Call, CheckerContext &
C)
const {
1709 if (!
Call.getOriginExpr())
1715 (*Callback)(
this, State,
Call,
C);
1720 State = MallocBindRetVal(
C,
Call, State,
false);
1721 (*Callback)(
this, State,
Call,
C);
1726 State = MallocBindRetVal(
C,
Call, State,
false);
1727 (*Callback)(
this, State,
Call,
C);
1732 State = MallocBindRetVal(
C,
Call, State,
false);
1733 checkCXXNewOrCXXDelete(State,
Call,
C);
1738 checkCXXNewOrCXXDelete(State,
Call,
C);
1743 State = MallocBindRetVal(
C,
Call, State,
true);
1744 (*Callback)(
this, State,
Call,
C);
1748 if (isFreeingOwnershipAttrCall(
Call) || isAllocatingOwnershipAttrCall(
Call)) {
1749 if (isAllocatingOwnershipAttrCall(
Call))
1750 State = MallocBindRetVal(
C,
Call, State,
false);
1751 checkOwnershipAttr(State,
Call,
C);
1760 CheckerContext &
C,
const CallEvent &
Call,
const unsigned IndexOfSizeArg,
1765 const Expr *Arg =
nullptr;
1767 if (
const CallExpr *CE = dyn_cast<CallExpr>(
Call.getOriginExpr())) {
1768 Arg = CE->
getArg(IndexOfSizeArg);
1769 }
else if (
const CXXNewExpr *NE =
1770 dyn_cast<CXXNewExpr>(
Call.getOriginExpr())) {
1771 if (
NE->isArray()) {
1772 Arg = *
NE->getArraySize();
1777 assert(
false &&
"not a CallExpr or CXXNewExpr");
1782 RetVal = State->getSVal(
Call.getOriginExpr(),
C.getStackFrame());
1787 State->getSVal(Arg,
Call.getStackFrame()).getAs<DefinedSVal>();
1794 SValBuilder &SvalBuilder = State->getStateManager().getSValBuilder();
1798 std::tie(TrueState, FalseState) =
1799 State->assume(SvalBuilder.
evalEQ(State, *DefArgVal,
Zero));
1801 if (TrueState && !FalseState) {
1802 SymbolRef Sym = RetVal->getAsLocSymbol();
1806 const RefState *RS = State->get<RegionState>(Sym);
1808 if (RS->isAllocated() && !RS->isAllocatedOfSizeZero())
1809 return TrueState->set<RegionState>(
1810 Sym, RefState::getAllocatedOfSizeZero(RS));
1817 return TrueState->add<ReallocSizeZeroSymbols>(Sym);
1827 while (!PointeeType.isNull()) {
1829 PointeeType = PointeeType->getPointeeType();
1842 if (!NE->getAllocatedType()->getAsCXXRecordDecl())
1848 for (
const auto *CtorParam : CtorD->
parameters()) {
1851 if (CtorParamPointeeT.
isNull())
1864MallocChecker::processNewAllocation(
const CXXAllocatorCall &
Call,
1866 AllocationFamily Family)
const {
1870 const CXXNewExpr *
NE =
Call.getOriginExpr();
1871 const ParentMap &PM =
C.getStackFrame()->getParentMap();
1885 SVal
Target =
Call.getObjectUnderConstruction();
1886 if (
Call.getOriginExpr()->isArray()) {
1887 if (
auto SizeEx =
NE->getArraySize())
1888 checkTaintedness(
C,
Call,
C.getSVal(*SizeEx), State,
1889 AllocationFamily(AF_CXXNewArray));
1893 State = ProcessZeroAllocCheck(
C,
Call, 0, State,
Target);
1897void MallocChecker::checkNewAllocator(
const CXXAllocatorCall &
Call,
1898 CheckerContext &
C)
const {
1899 if (!
C.wasInlined) {
1902 AllocationFamily(
Call.getOriginExpr()->isArray() ? AF_CXXNewArray
1904 C.addTransition(State);
1914 StringRef FirstSlot =
Call.getSelector().getNameForSlot(0);
1915 return FirstSlot ==
"dataWithBytesNoCopy" ||
1916 FirstSlot ==
"initWithBytesNoCopy" ||
1917 FirstSlot ==
"initWithCharactersNoCopy";
1924 for (
unsigned i = 1; i < S.
getNumArgs(); ++i)
1926 return !
Call.getArgSVal(i).isZeroConstant();
1928 return std::nullopt;
1931void MallocChecker::checkPostObjCMessage(
const ObjCMethodCall &
Call,
1932 CheckerContext &
C)
const {
1943 if (
Call.hasNonZeroCallbackArg())
1946 bool IsKnownToBeAllocatedMemory;
1948 true, IsKnownToBeAllocatedMemory,
1949 AllocationFamily(AF_Malloc),
1952 C.addTransition(State);
1956MallocChecker::MallocMemReturnsAttr(CheckerContext &
C,
const CallEvent &
Call,
1957 const OwnershipAttr *Att,
1962 auto attrClassName = Att->getModule()->getName();
1963 auto Family = AllocationFamily(AF_Custom, attrClassName);
1965 if (!Att->args().empty()) {
1966 return MallocMemAux(
C,
Call,
1967 Call.getArgExpr(Att->args_begin()->getASTIndex()),
1968 UnknownVal(), State, Family);
1970 return MallocMemAux(
C,
Call, UnknownVal(), UnknownVal(), State, Family);
1974 const CallEvent &
Call,
1976 bool isAlloca)
const {
1977 const Expr *CE =
Call.getOriginExpr();
1983 unsigned Count =
C.blockCount();
1984 SValBuilder &SVB =
C.getSValBuilder();
1985 const StackFrame *SF =
C.getPredecessor()->getStackFrame();
1986 DefinedSVal RetVal =
1990 return State->BindExpr(CE,
C.getStackFrame(), RetVal);
1994 const CallEvent &
Call,
1995 const Expr *SizeEx, SVal
Init,
1997 AllocationFamily Family)
const {
2002 return MallocMemAux(
C,
Call,
C.getSVal(SizeEx),
Init, State, Family);
2005void MallocChecker::reportTaintBug(StringRef Msg,
ProgramStateRef State,
2007 llvm::ArrayRef<SymbolRef> TaintedSyms,
2008 AllocationFamily Family)
const {
2009 if (ExplodedNode *N =
C.generateNonFatalErrorNode(State,
this)) {
2011 std::make_unique<PathSensitiveBugReport>(TaintedAllocChecker, Msg, N);
2012 for (
const auto *TaintedSym : TaintedSyms) {
2013 R->markInteresting(TaintedSym);
2015 C.emitReport(std::move(R));
2019void MallocChecker::checkTaintedness(CheckerContext &
C,
const CallEvent &
Call,
2021 AllocationFamily Family)
const {
2024 std::vector<SymbolRef> TaintedSyms =
2026 if (TaintedSyms.empty())
2029 SValBuilder &SVB =
C.getSValBuilder();
2035 const llvm::APSInt MaxValInt = BVF.
getMaxValue(SizeTy);
2037 SVB.
makeIntVal(MaxValInt / APSIntType(MaxValInt).getValue(4));
2038 std::optional<NonLoc> SizeNL = SizeSVal.
getAs<NonLoc>();
2039 auto Cmp = SVB.
evalBinOpNN(State, BO_GE, *SizeNL, MaxLength, CmpTy)
2040 .
getAs<DefinedOrUnknownSVal>();
2043 auto [StateTooLarge, StateNotTooLarge] = State->assume(*
Cmp);
2044 if (!StateTooLarge && StateNotTooLarge) {
2049 std::string
Callee =
"Memory allocation function";
2050 if (
Call.getCalleeIdentifier())
2051 Callee =
Call.getCalleeIdentifier()->getName().str();
2053 Callee +
" is called with a tainted (potentially attacker controlled) "
2054 "value; make sure the value is bound checked",
2055 State,
C, TaintedSyms, Family);
2059 const CallEvent &
Call, SVal Size,
2061 AllocationFamily Family)
const {
2065 const Expr *CE =
Call.getOriginExpr();
2070 "Allocation functions must return a pointer");
2072 const StackFrame *SF =
C.getPredecessor()->getStackFrame();
2073 SVal RetVal = State->getSVal(CE,
C.getStackFrame());
2077 State = State->bindDefaultInitial(RetVal,
Init, SF);
2081 Size = UnknownVal();
2083 checkTaintedness(
C,
Call, Size, State, AllocationFamily(AF_Malloc));
2087 Size.castAs<DefinedOrUnknownSVal>());
2093MallocChecker::FailedAlloc(CheckerContext &
C,
const CallEvent &
Call,
2095 llvm::ArrayRef<unsigned> SizeArgIndexes)
const {
2096 if (!State || !ModelAllocationFailure)
2099 for (
unsigned SizeArgI : SizeArgIndexes) {
2100 auto DefArgVal =
Call.getArgSVal(SizeArgI).getAs<DefinedOrUnknownSVal>();
2103 State = State->assume(*DefArgVal,
true);
2108 auto RetVal = State->getSVal(
Call.getOriginExpr(),
C.getStackFrame())
2109 .castAs<DefinedOrUnknownSVal>();
2110 return State->assume(RetVal,
false);
2115 AllocationFamily Family,
2116 std::optional<SVal> RetVal) {
2122 RetVal = State->getSVal(E,
C.getStackFrame());
2125 if (!RetVal->getAs<
Loc>())
2128 SymbolRef Sym = RetVal->getAsLocSymbol();
2136 return State->set<RegionState>(Sym, RefState::getAllocated(Family, E));
2142 const CallEvent &
Call,
2143 const OwnershipAttr *Att,
2148 auto attrClassName = Att->getModule()->getName();
2149 auto Family = AllocationFamily(AF_Custom, attrClassName);
2151 bool IsKnownToBeAllocated =
false;
2153 for (
const auto &Arg : Att->args()) {
2155 FreeMemAux(
C,
Call, State, Arg.getASTIndex(),
2156 Att->getOwnKind() == OwnershipAttr::Holds,
2157 IsKnownToBeAllocated, Family);
2165 const CallEvent &
Call,
2167 bool Hold,
bool &IsKnownToBeAllocated,
2168 AllocationFamily Family,
2169 bool ReturnsNullOnFailure)
const {
2173 if (
Call.getNumArgs() < (
Num + 1))
2176 return FreeMemAux(
C,
Call.getArgExpr(
Num),
Call, State, Hold,
2177 IsKnownToBeAllocated, Family, ReturnsNullOnFailure);
2184 const SymbolRef *Ret = State->get<FreeReturnValue>(Sym);
2186 assert(*Ret &&
"We should not store the null return symbol");
2189 RetStatusSymbol = *Ret;
2197 const CallExpr *CE = dyn_cast<CallExpr>(E);
2208 if (I->getOwnKind() != OwnershipAttr::Takes)
2211 os <<
", which takes ownership of '" << I->getModule()->getName() <<
'\'';
2217 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2233 if (Msg->isInstanceMessage())
2237 Msg->getSelector().print(os);
2241 if (
const CXXNewExpr *NE = dyn_cast<CXXNewExpr>(E)) {
2260 switch (Family.Kind) {
2267 case AF_CXXNewArray:
2270 case AF_IfNameIndex:
2271 os <<
"'if_nameindex()'";
2273 case AF_InnerBuffer:
2274 os <<
"container-specific allocator";
2277 os << Family.CustomName.value();
2281 assert(
false &&
"not a deallocation expression");
2286 switch (Family.Kind) {
2293 case AF_CXXNewArray:
2296 case AF_IfNameIndex:
2297 os <<
"'if_freenameindex()'";
2299 case AF_InnerBuffer:
2300 os <<
"container-specific deallocator";
2303 os <<
"function that takes ownership of '" << Family.CustomName.value()
2308 assert(
false &&
"not a deallocation expression");
2313MallocChecker::FreeMemAux(CheckerContext &
C,
const Expr *ArgExpr,
2315 bool Hold,
bool &IsKnownToBeAllocated,
2316 AllocationFamily Family,
bool ReturnsNullOnFailure,
2317 std::optional<SVal> ArgValOpt)
const {
2322 SVal ArgVal = ArgValOpt.value_or(
C.getSVal(ArgExpr));
2325 DefinedOrUnknownSVal location = ArgVal.
castAs<DefinedOrUnknownSVal>();
2333 std::tie(notNullState, nullState) = State->assume(location);
2334 if (nullState && !notNullState)
2343 const Expr *ParentExpr =
Call.getOriginExpr();
2362 if (Family.Kind != AF_Malloc || !isArgZERO_SIZE_PTR(State,
C, ArgVal))
2363 HandleNonHeapDealloc(
C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr,
2368 R =
R->StripCasts();
2372 HandleNonHeapDealloc(
C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr,
2379 if (!
R->hasMemorySpace<UnknownSpaceRegion, HeapSpaceRegion>(State)) {
2388 HandleNonHeapDealloc(
C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr,
2394 const SymbolicRegion *SrBase = dyn_cast<SymbolicRegion>(
R->getBaseRegion());
2401 const RefState *RsBase = State->get<RegionState>(SymBase);
2402 SymbolRef PreviousRetStatusSymbol =
nullptr;
2404 IsKnownToBeAllocated = RsBase && RsBase->isAllocated();
2409 if (RsBase->getAllocationFamily().Kind == AF_Alloca) {
2415 if ((RsBase->isReleased() || RsBase->isRelinquished()) &&
2417 HandleDoubleFree(
C, ParentExpr->
getSourceRange(), RsBase->isReleased(),
2418 SymBase, PreviousRetStatusSymbol);
2424 if (RsBase->isAllocated() || RsBase->isEscaped()) {
2427 bool DeallocMatchesAlloc = RsBase->getAllocationFamily() == Family;
2428 if (!DeallocMatchesAlloc) {
2430 RsBase, SymBase, Hold);
2436 RegionOffset Offset =
R->getAsOffset();
2440 const Expr *AllocExpr =
cast<Expr>(RsBase->getStmt());
2449 HandleFunctionPtrFree(
C, ArgVal, ArgExpr->
getSourceRange(), ParentExpr,
2455 State = State->remove<FreeReturnValue>(SymBase);
2459 if (ReturnsNullOnFailure) {
2460 SVal RetVal =
C.getSVal(ParentExpr);
2462 if (RetStatusSymbol) {
2463 C.getSymbolManager().addSymbolDependency(SymBase, RetStatusSymbol);
2464 State = State->set<FreeReturnValue>(SymBase, RetStatusSymbol);
2472 assert(!RsBase || (RsBase && RsBase->getAllocationFamily() == Family));
2477 State = State->invalidateRegions({location},
Call.getCFGElementRef(),
2478 C.blockCount(),
C.getStackFrame(),
2484 return State->set<RegionState>(SymBase,
2485 RefState::getRelinquished(Family,
2488 return State->set<RegionState>(SymBase,
2489 RefState::getReleased(Family, ParentExpr));
2493const T *MallocChecker::getRelevantFrontendAs(AllocationFamily Family)
const {
2494 switch (Family.Kind) {
2498 case AF_IfNameIndex:
2499 return MallocChecker.getAs<T>();
2501 case AF_CXXNewArray: {
2502 const T *ND = NewDeleteChecker.getAs<T>();
2503 const T *NDL = NewDeleteLeaksChecker.getAs<T>();
2506 if constexpr (std::is_same_v<T, CheckerFrontend>) {
2507 assert(ND && NDL &&
"Casting to CheckerFrontend always succeeds");
2509 return (!ND->isEnabled() && NDL->isEnabled()) ? NDL : ND;
2511 assert(!(ND && NDL) &&
2512 "NewDelete and NewDeleteLeaks must not share a bug type");
2513 return ND ? ND : NDL;
2515 case AF_InnerBuffer:
2516 return InnerPointerChecker.getAs<T>();
2518 assert(
false &&
"no family");
2521 assert(
false &&
"unhandled family");
2525const T *MallocChecker::getRelevantFrontendAs(CheckerContext &
C,
2527 if (
C.getState()->contains<ReallocSizeZeroSymbols>(Sym))
2528 return MallocChecker.getAs<T>();
2530 const RefState *RS =
C.getState()->get<RegionState>(Sym);
2532 return getRelevantFrontendAs<T>(RS->getAllocationFamily());
2535bool MallocChecker::SummarizeValue(raw_ostream &os, SVal
V) {
2536 if (std::optional<nonloc::ConcreteInt> IntVal =
2537 V.getAs<nonloc::ConcreteInt>())
2538 os <<
"an integer (" << IntVal->getValue() <<
")";
2539 else if (std::optional<loc::ConcreteInt> ConstAddr =
2540 V.getAs<loc::ConcreteInt>())
2541 os <<
"a constant address (" << ConstAddr->getValue() <<
")";
2542 else if (std::optional<loc::GotoLabel> Label =
V.getAs<loc::GotoLabel>())
2543 os <<
"the address of the label '" << Label->getLabel()->getName() <<
"'";
2550bool MallocChecker::SummarizeRegion(
ProgramStateRef State, raw_ostream &os,
2551 const MemRegion *MR) {
2553 case MemRegion::FunctionCodeRegionKind: {
2556 os <<
"the address of the function '" << *FD <<
'\'';
2558 os <<
"the address of a function";
2561 case MemRegion::BlockCodeRegionKind:
2564 case MemRegion::BlockDataRegionKind:
2572 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2580 os <<
"the address of the local variable '" << VD->
getName() <<
"'";
2582 os <<
"the address of a local stack variable";
2587 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2595 os <<
"the address of the parameter '" << VD->
getName() <<
"'";
2597 os <<
"the address of a parameter";
2602 const VarRegion *VR = dyn_cast<VarRegion>(MR);
2611 os <<
"the address of the static variable '" << VD->
getName() <<
"'";
2613 os <<
"the address of the global variable '" << VD->
getName() <<
"'";
2615 os <<
"the address of a global variable";
2624void MallocChecker::HandleNonHeapDealloc(CheckerContext &
C, SVal ArgVal,
2626 const Expr *DeallocExpr,
2627 AllocationFamily Family)
const {
2628 const BadFree *Frontend = getRelevantFrontendAs<BadFree>(Family);
2631 if (!Frontend->isEnabled()) {
2636 if (ExplodedNode *N =
C.addSink()) {
2637 SmallString<100> buf;
2638 llvm::raw_svector_ostream os(buf);
2641 while (
const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2642 MR = ER->getSuperRegion();
2644 os <<
"Argument to ";
2646 os <<
"deallocator";
2650 MR ? SummarizeRegion(
C.getState(), os, MR) : SummarizeValue(os, ArgVal);
2652 os <<
", which is not memory allocated by ";
2654 os <<
"not memory allocated by ";
2658 auto R = std::make_unique<PathSensitiveBugReport>(Frontend->BadFreeBug,
2660 R->markInteresting(MR);
2662 C.emitReport(std::move(R));
2666void MallocChecker::HandleFreeAlloca(CheckerContext &
C, SVal ArgVal,
2667 SourceRange Range)
const {
2668 const FreeAlloca *Frontend;
2670 if (MallocChecker.isEnabled())
2671 Frontend = &MallocChecker;
2672 else if (MismatchedDeallocatorChecker.isEnabled())
2673 Frontend = &MismatchedDeallocatorChecker;
2679 if (ExplodedNode *N =
C.addSink()) {
2680 auto R = std::make_unique<PathSensitiveBugReport>(
2681 Frontend->FreeAllocaBug,
2682 "Memory allocated by 'alloca()' should not be deallocated", N);
2685 C.emitReport(std::move(R));
2689void MallocChecker::HandleMismatchedDealloc(CheckerContext &
C,
2691 const Expr *DeallocExpr,
2693 bool OwnershipTransferred)
const {
2694 if (!MismatchedDeallocatorChecker.isEnabled()) {
2699 if (ExplodedNode *N =
C.addSink()) {
2700 SmallString<100> buf;
2701 llvm::raw_svector_ostream os(buf);
2703 const Expr *AllocExpr =
cast<Expr>(RS->getStmt());
2704 SmallString<20> AllocBuf;
2705 llvm::raw_svector_ostream AllocOs(AllocBuf);
2706 SmallString<20> DeallocBuf;
2707 llvm::raw_svector_ostream DeallocOs(DeallocBuf);
2709 if (OwnershipTransferred) {
2711 os << DeallocOs.str() <<
" cannot";
2715 os <<
" take ownership of memory";
2718 os <<
" allocated by " << AllocOs.str();
2722 os <<
" allocated by " << AllocOs.str();
2724 os <<
" should be deallocated by ";
2728 os <<
", not " << DeallocOs.str();
2733 auto R = std::make_unique<PathSensitiveBugReport>(
2734 MismatchedDeallocatorChecker.MismatchedDeallocBug, os.str(), N);
2735 R->markInteresting(Sym);
2737 R->addVisitor<MallocBugVisitor>(Sym);
2738 C.emitReport(std::move(R));
2742void MallocChecker::HandleOffsetFree(CheckerContext &
C, SVal ArgVal,
2743 SourceRange Range,
const Expr *DeallocExpr,
2744 AllocationFamily Family,
2745 const Expr *AllocExpr)
const {
2746 const OffsetFree *Frontend = getRelevantFrontendAs<OffsetFree>(Family);
2749 if (!Frontend->isEnabled()) {
2754 ExplodedNode *N =
C.addSink();
2758 SmallString<100> buf;
2759 llvm::raw_svector_ostream os(buf);
2760 SmallString<20> AllocNameBuf;
2761 llvm::raw_svector_ostream AllocNameOs(AllocNameBuf);
2764 assert(MR &&
"Only MemRegion based symbols can have offset free errors");
2770 "Only symbols with a valid offset can have offset free errors");
2772 int offsetBytes = Offset.
getOffset() /
C.getASTContext().getCharWidth();
2774 os <<
"Argument to ";
2776 os <<
"deallocator";
2777 os <<
" is offset by "
2780 << ((
abs(offsetBytes) > 1) ?
"bytes" :
"byte")
2781 <<
" from the start of ";
2783 os <<
"memory allocated by " << AllocNameOs.str();
2785 os <<
"allocated memory";
2787 auto R = std::make_unique<PathSensitiveBugReport>(Frontend->OffsetFreeBug,
2791 C.emitReport(std::move(R));
2794void MallocChecker::HandleUseAfterFree(CheckerContext &
C, SourceRange Range,
2796 const UseFree *Frontend = getRelevantFrontendAs<UseFree>(
C, Sym);
2799 if (!Frontend->isEnabled()) {
2804 if (ExplodedNode *N =
C.addSink()) {
2805 AllocationFamily AF =
2806 C.getState()->get<RegionState>(Sym)->getAllocationFamily();
2808 auto R = std::make_unique<PathSensitiveBugReport>(
2809 Frontend->UseFreeBug,
2810 AF.Kind == AF_InnerBuffer
2811 ?
"Inner pointer of container used after re/deallocation"
2812 :
"Use of memory after it is released",
2815 R->markInteresting(Sym);
2817 R->addVisitor<MallocBugVisitor>(Sym);
2819 if (AF.Kind == AF_InnerBuffer)
2822 C.emitReport(std::move(R));
2826void MallocChecker::HandleDoubleFree(CheckerContext &
C, SourceRange Range,
2829 const DoubleFree *Frontend = getRelevantFrontendAs<DoubleFree>(
C, Sym);
2832 if (!Frontend->isEnabled()) {
2837 if (ExplodedNode *N =
C.addSink()) {
2838 auto R = std::make_unique<PathSensitiveBugReport>(
2839 Frontend->DoubleFreeBug,
2840 (Released ?
"Attempt to release already released memory"
2841 :
"Attempt to release non-owned memory"),
2843 if (
Range.isValid())
2845 R->markInteresting(Sym);
2847 R->markInteresting(PrevSym);
2848 R->addVisitor<MallocBugVisitor>(Sym);
2849 C.emitReport(std::move(R));
2853void MallocChecker::HandleUseZeroAlloc(CheckerContext &
C, SourceRange Range,
2855 const UseZeroAllocated *Frontend =
2856 getRelevantFrontendAs<UseZeroAllocated>(
C, Sym);
2859 if (!Frontend->isEnabled()) {
2864 if (ExplodedNode *N =
C.addSink()) {
2865 auto R = std::make_unique<PathSensitiveBugReport>(
2866 Frontend->UseZeroAllocatedBug,
"Use of memory allocated with size zero",
2871 R->markInteresting(Sym);
2872 R->addVisitor<MallocBugVisitor>(Sym);
2874 C.emitReport(std::move(R));
2878void MallocChecker::HandleFunctionPtrFree(CheckerContext &
C, SVal ArgVal,
2880 const Expr *FreeExpr,
2881 AllocationFamily Family)
const {
2882 const BadFree *Frontend = getRelevantFrontendAs<BadFree>(Family);
2885 if (!Frontend->isEnabled()) {
2890 if (ExplodedNode *N =
C.addSink()) {
2891 SmallString<100> Buf;
2892 llvm::raw_svector_ostream Os(Buf);
2895 while (
const ElementRegion *ER = dyn_cast_or_null<ElementRegion>(MR))
2896 MR = ER->getSuperRegion();
2898 Os <<
"Argument to ";
2900 Os <<
"deallocator";
2902 Os <<
" is a function pointer";
2904 auto R = std::make_unique<PathSensitiveBugReport>(Frontend->BadFreeBug,
2906 R->markInteresting(MR);
2908 C.emitReport(std::move(R));
2913MallocChecker::ReallocMemAux(CheckerContext &
C,
const CallEvent &
Call,
2915 AllocationFamily Family,
bool SuffixWithN)
const {
2924 const Expr *arg0Expr = CE->
getArg(0);
2925 SVal Arg0Val =
C.getSVal(arg0Expr);
2928 DefinedOrUnknownSVal arg0Val = Arg0Val.
castAs<DefinedOrUnknownSVal>();
2930 SValBuilder &svalBuilder =
C.getSValBuilder();
2932 DefinedOrUnknownSVal PtrEQ = svalBuilder.
evalEQ(
2933 State, arg0Val, svalBuilder.makeNullWithType(arg0Expr->
getType()));
2936 const Expr *Arg1 = CE->
getArg(1);
2939 SVal TotalSize =
C.getSVal(Arg1);
2941 TotalSize = evalMulForBufferSize(
C, Arg1, CE->
getArg(2));
2946 DefinedOrUnknownSVal SizeZero = svalBuilder.evalEQ(
2947 State, TotalSize.
castAs<DefinedOrUnknownSVal>(),
2948 svalBuilder.makeIntValWithWidth(
2949 svalBuilder.getContext().getCanonicalSizeType(), 0));
2952 std::tie(StatePtrIsNull, StatePtrNotNull) = State->assume(PtrEQ);
2954 std::tie(StateSizeIsZero, StateSizeNotZero) = State->assume(SizeZero);
2957 bool PrtIsNull = StatePtrIsNull && !StatePtrNotNull;
2958 bool SizeIsZero = StateSizeIsZero && !StateSizeNotZero;
2962 if (PrtIsNull && !SizeIsZero) {
2964 C,
Call, TotalSize, UndefinedVal(), StatePtrIsNull, Family);
2969 if (PrtIsNull && SizeIsZero)
2974 bool IsKnownToBeAllocated =
false;
2983 C,
Call, StateSizeIsZero, 0,
false, IsKnownToBeAllocated, Family))
2988 FreeMemAux(
C,
Call, State, 0,
false, IsKnownToBeAllocated, Family)) {
2991 MallocMemAux(
C,
Call, TotalSize, UnknownVal(), stateFree, Family);
2995 OwnershipAfterReallocKind
Kind = OAR_ToBeFreedAfterFailure;
2996 if (ShouldFreeOnFail)
2997 Kind = OAR_FreeOnFailure;
2998 else if (!IsKnownToBeAllocated)
2999 Kind = OAR_DoNotTrackAfterFailure;
3003 SVal RetVal = stateRealloc->getSVal(CE,
C.getStackFrame());
3005 assert(FromPtr && ToPtr &&
3006 "By this point, FreeMemAux and MallocMemAux should have checked "
3007 "whether the argument or the return value is symbolic!");
3011 stateRealloc = stateRealloc->set<ReallocPairs>(ToPtr,
3012 ReallocPair(FromPtr, Kind));
3014 C.getSymbolManager().addSymbolDependency(ToPtr, FromPtr);
3015 return stateRealloc;
3021 const CallEvent &
Call,
3026 if (
Call.getNumArgs() < 2)
3029 SValBuilder &svalBuilder =
C.getSValBuilder();
3032 evalMulForBufferSize(
C,
Call.getArgExpr(0),
Call.getArgExpr(1));
3034 return MallocMemAux(
C,
Call, TotalSize, zeroVal, State,
3035 AllocationFamily(AF_Malloc));
3038MallocChecker::LeakInfo MallocChecker::getAllocationSite(
const ExplodedNode *N,
3040 CheckerContext &
C) {
3044 const ExplodedNode *AllocNode = N;
3045 const MemRegion *ReferenceRegion =
nullptr;
3049 if (!State->get<RegionState>(Sym))
3054 if (!ReferenceRegion) {
3055 if (
const MemRegion *MR =
C.getLocationRegionIfPostStore(N)) {
3056 SVal Val = State->getSVal(MR);
3062 ReferenceRegion = MR;
3070 if (NSF == LeakStackFrame || NSF->
isParentOf(LeakStackFrame))
3075 return LeakInfo(AllocNode, ReferenceRegion);
3078void MallocChecker::HandleLeak(
SymbolRef Sym, ExplodedNode *N,
3079 CheckerContext &
C)
const {
3080 assert(N &&
"HandleLeak is only called with a non-null node");
3082 const RefState *RS =
C.getState()->get<RegionState>(Sym);
3083 assert(RS &&
"cannot leak an untracked symbol");
3084 AllocationFamily Family = RS->getAllocationFamily();
3086 if (Family.Kind == AF_Alloca)
3089 const Leak *Frontend = getRelevantFrontendAs<Leak>(Family);
3093 if (!Frontend || !Frontend->isEnabled())
3099 PathDiagnosticLocation LocUsedForUniqueing;
3100 const ExplodedNode *AllocNode =
nullptr;
3101 const MemRegion *Region =
nullptr;
3102 std::tie(AllocNode, Region) = getAllocationSite(N, Sym,
C);
3107 AllocationStmt,
C.getSourceManager(), AllocNode->
getStackFrame());
3109 SmallString<200> buf;
3110 llvm::raw_svector_ostream os(buf);
3112 os <<
"Potential leak of memory pointed to by ";
3115 os <<
"Potential memory leak";
3118 auto R = std::make_unique<PathSensitiveBugReport>(
3119 Frontend->LeakBug, os.str(), N, LocUsedForUniqueing,
3121 R->markInteresting(Sym);
3122 R->addVisitor<MallocBugVisitor>(Sym,
true);
3123 if (ShouldRegisterNoOwnershipChangeVisitor)
3124 R->addVisitor<NoMemOwnershipChangeVisitor>(Sym,
this);
3125 C.emitReport(std::move(R));
3128void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3129 CheckerContext &
C)
const
3132 RegionStateTy OldRS = state->get<RegionState>();
3133 RegionStateTy::Factory &F = state->get_context<RegionState>();
3135 RegionStateTy RS = OldRS;
3136 SmallVector<SymbolRef, 2> Errors;
3137 for (
auto [Sym, State] : RS) {
3138 if (SymReaper.
isDead(Sym)) {
3139 if (State.isAllocated())
3140 Errors.push_back(Sym);
3142 RS = F.remove(RS, Sym);
3148 assert(state->get<ReallocPairs>() ==
3149 C.getState()->get<ReallocPairs>());
3150 assert(state->get<FreeReturnValue>() ==
3151 C.getState()->get<FreeReturnValue>());
3156 ReallocPairsTy RP = state->get<ReallocPairs>();
3157 for (
auto [Sym, ReallocPair] : RP) {
3158 if (SymReaper.
isDead(Sym) || SymReaper.
isDead(ReallocPair.ReallocatedSym)) {
3159 state = state->remove<ReallocPairs>(Sym);
3164 FreeReturnValueTy FR = state->get<FreeReturnValue>();
3165 for (
auto [Sym, RetSym] : FR) {
3166 if (SymReaper.
isDead(Sym) || SymReaper.
isDead(RetSym)) {
3167 state = state->remove<FreeReturnValue>(Sym);
3172 ExplodedNode *N =
C.getPredecessor();
3173 if (!Errors.empty()) {
3174 N =
C.generateNonFatalErrorNode(
C.getState());
3177 HandleLeak(Sym, N,
C);
3182 C.addTransition(state->set<RegionState>(RS), N);
3189 return Name ==
"unique_ptr" || Name ==
"shared_ptr";
3196 if (
const auto *TST = QT->
getAs<TemplateSpecializationType>()) {
3197 const TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
3220 llvm::SmallPtrSetImpl<const MemRegion *> *
Out;
3223 llvm::SmallPtrSetImpl<const MemRegion *> &
Out)
3236 C->getState()->getLValue(BaseDecl,
Reg->getAs<
SubRegion>(), IsVirtual);
3241 return std::nullopt;
3257 std::optional<FieldConsumer> FC = std::nullopt) {
3270 BaseSpec.getType()->getAsCXXRecordDecl()) {
3271 std::optional<FieldConsumer> NewFC;
3273 NewFC = FC->switchToBase(BaseDecl, BaseSpec.isVirtual());
3291 if (!T->isRecordType() || T->isReferenceType())
3323 const auto *CD = dyn_cast_or_null<CXXConstructorDecl>(
Call.getDecl());
3327 const auto *RD = CD->getParent();
3332 for (
const auto *Param : CD->parameters()) {
3333 QualType ParamType = Param->getType();
3348 llvm::SmallPtrSetImpl<const MemRegion *> &Out) {
3365 for (
unsigned I = 0, E = std::min(
Call.getNumArgs(), CD->getNumParams());
3367 const Expr *ArgExpr =
Call.getArgExpr(I);
3371 QualType ParamType = CD->getParamDecl(I)->
getType();
3375 SVal ArgVal =
Call.getArgSVal(I);
3377 if (Sym && State->contains<RegionState>(Sym)) {
3378 const RefState *RS = State->get<RegionState>(Sym);
3379 if (RS && RS->isAllocated()) {
3380 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
3396 return handleSmartPointerConstructorArguments(
Call, State);
3400 llvm::SmallPtrSet<const MemRegion *, 8> SmartPtrFieldRoots;
3401 for (
unsigned I = 0, E =
Call.getNumArgs(); I != E; ++I) {
3402 const Expr *AE =
Call.getArgExpr(I);
3411 SVal ArgVal =
Call.getArgSVal(I);
3412 const MemRegion *ArgRegion = ArgVal.
getAsRegion();
3415 SmartPtrFieldRoots);
3419 if (!SmartPtrFieldRoots.empty()) {
3420 SmallVector<const MemRegion *, 8> SmartPtrFieldRootsVec(
3421 SmartPtrFieldRoots.begin(), SmartPtrFieldRoots.end());
3422 State = EscapeTrackedCallback::EscapeTrackedRegionsReachableFrom(
3423 SmartPtrFieldRootsVec, State);
3429void MallocChecker::checkPostCall(
const CallEvent &
Call,
3430 CheckerContext &
C)
const {
3432 if (
const auto *PostFN = PostFnMap.
lookup(
Call)) {
3433 (*PostFN)(
this,
C.getState(),
Call,
C);
3438 C.addTransition(handleSmartPointerRelatedCalls(
Call,
C,
C.getState()));
3441void MallocChecker::checkPreCall(
const CallEvent &
Call,
3442 CheckerContext &
C)
const {
3444 if (
const auto *DC = dyn_cast<CXXDeallocatorCall>(&
Call)) {
3445 const CXXDeleteExpr *DE = DC->getOriginExpr();
3451 if (!NewDeleteChecker.isEnabled())
3459 bool IsKnownToBeAllocated;
3462 false, IsKnownToBeAllocated,
3463 AllocationFamily(DE->
isArrayForm() ? AF_CXXNewArray : AF_CXXNew));
3465 C.addTransition(State);
3476 if (
const auto *DC = dyn_cast<CXXDestructorCall>(&
Call)) {
3477 SymbolRef Sym = DC->getCXXThisVal().getAsSymbol();
3481 HandleDoubleFree(
C, SourceRange(),
true, Sym,
3489 if (
const auto *PreFN = PreFnMap.
lookup(
Call)) {
3490 (*PreFN)(
this,
C.getState(),
Call,
C);
3498 if (
const AnyFunctionCall *FC = dyn_cast<AnyFunctionCall>(&
Call)) {
3499 const FunctionDecl *FD = FC->getDecl();
3506 if (MallocChecker.isEnabled() && isFreeingCall(
Call))
3511 if (
const CXXInstanceCall *CC = dyn_cast<CXXInstanceCall>(&
Call)) {
3512 SymbolRef Sym = CC->getCXXThisVal().getAsSymbol();
3513 if (!Sym || checkUseAfterFree(Sym,
C, CC->getCXXThisExpr()))
3518 for (
unsigned I = 0, E =
Call.getNumArgs(); I != E; ++I) {
3519 SVal ArgSVal =
Call.getArgSVal(I);
3524 if (checkUseAfterFree(Sym,
C,
Call.getArgExpr(I)))
3530void MallocChecker::checkPreStmt(
const ReturnStmt *S,
3531 CheckerContext &
C)
const {
3532 checkEscapeOnReturn(S,
C);
3538void MallocChecker::checkEndFunction(
const ReturnStmt *S,
3539 CheckerContext &
C)
const {
3540 checkEscapeOnReturn(S,
C);
3543void MallocChecker::checkEscapeOnReturn(
const ReturnStmt *S,
3544 CheckerContext &
C)
const {
3553 SVal RetVal =
C.getSVal(E);
3560 if (
const SymbolicRegion *BMR =
3562 Sym = BMR->getSymbol();
3566 checkUseAfterFree(Sym,
C, E);
3572void MallocChecker::checkPostStmt(
const BlockExpr *BE,
3573 CheckerContext &
C)
const {
3581 const BlockDataRegion *
R =
3584 auto ReferencedVars =
R->referenced_vars();
3585 if (ReferencedVars.empty())
3588 SmallVector<const MemRegion *, 10> Regions;
3589 MemRegionManager &MemMgr =
C.getSValBuilder().getRegionManager();
3591 for (
const auto &Var : ReferencedVars) {
3592 const VarRegion *VR = Var.getCapturedRegion();
3596 Regions.push_back(VR);
3600 state->scanReachableSymbols<StopTrackingCallback>(Regions).getState();
3601 C.addTransition(state);
3606 const RefState *RS =
C.getState()->get<RegionState>(Sym);
3607 return (RS && RS->isReleased());
3610bool MallocChecker::suppressDeallocationsInSuspiciousContexts(
3611 const CallEvent &
Call, CheckerContext &
C)
const {
3612 if (
Call.getNumArgs() == 0)
3615 StringRef FunctionStr =
"";
3616 if (
const auto *FD = dyn_cast<FunctionDecl>(
C.getStackFrame()->getDecl()))
3617 if (
const Stmt *Body = FD->
getBody())
3622 C.getSourceManager(),
C.getLangOpts());
3625 if (!FunctionStr.contains(
"__isl_"))
3631 if (
SymbolRef Sym =
C.getSVal(Arg).getAsSymbol())
3632 if (
const RefState *RS = State->get<RegionState>(Sym))
3633 State = State->set<RegionState>(Sym, RefState::getEscaped(RS));
3635 C.addTransition(State);
3639bool MallocChecker::checkUseAfterFree(
SymbolRef Sym, CheckerContext &
C,
3640 const Stmt *S)
const {
3650void MallocChecker::checkUseZeroAllocated(
SymbolRef Sym, CheckerContext &
C,
3651 const Stmt *S)
const {
3654 if (
const RefState *RS =
C.getState()->get<RegionState>(Sym)) {
3655 if (RS->isAllocatedOfSizeZero())
3656 HandleUseZeroAlloc(
C, RS->getStmt()->getSourceRange(), Sym);
3658 else if (
C.getState()->contains<ReallocSizeZeroSymbols>(Sym)) {
3664void MallocChecker::checkLocation(SVal l,
bool isLoad,
const Stmt *S,
3665 CheckerContext &
C)
const {
3668 checkUseAfterFree(Sym,
C, S);
3669 checkUseZeroAllocated(Sym,
C, S);
3677 bool Assumption)
const {
3678 RegionStateTy RS = state->get<RegionState>();
3679 for (
SymbolRef Sym : llvm::make_first_range(RS)) {
3681 ConstraintManager &CMgr = state->getConstraintManager();
3682 ConditionTruthVal AllocFailed = CMgr.
isNull(state, Sym);
3684 state = state->remove<RegionState>(Sym);
3689 ReallocPairsTy RP = state->get<ReallocPairs>();
3690 for (
auto [Sym, ReallocPair] : RP) {
3692 ConstraintManager &CMgr = state->getConstraintManager();
3693 ConditionTruthVal AllocFailed = CMgr.
isNull(state, Sym);
3697 SymbolRef ReallocSym = ReallocPair.ReallocatedSym;
3698 if (
const RefState *RS = state->get<RegionState>(ReallocSym)) {
3699 if (RS->isReleased()) {
3700 switch (ReallocPair.Kind) {
3701 case OAR_ToBeFreedAfterFailure:
3702 state = state->set<RegionState>(ReallocSym,
3703 RefState::getAllocated(RS->getAllocationFamily(), RS->getStmt()));
3705 case OAR_DoNotTrackAfterFailure:
3706 state = state->remove<RegionState>(ReallocSym);
3709 assert(ReallocPair.Kind == OAR_FreeOnFailure);
3713 state = state->remove<ReallocPairs>(Sym);
3719bool MallocChecker::ignoreDirectEscapeTo(
const CallEvent *
Call,
3722 EscapingSymbol =
nullptr;
3732 if (
const ObjCMethodCall *Msg = dyn_cast<ObjCMethodCall>(
Call)) {
3735 if (!
Call->isInSystemHeader() ||
Call->argumentsMayEscape())
3748 return !*FreeWhenDone;
3754 StringRef FirstSlot = Msg->getSelector().getNameForSlot(0);
3755 if (FirstSlot.ends_with(
"NoCopy"))
3762 if (FirstSlot.starts_with(
"addPointer") ||
3763 FirstSlot.starts_with(
"insertPointer") ||
3764 FirstSlot.starts_with(
"replacePointer") ||
3765 FirstSlot ==
"valueWithPointer") {
3772 if (Msg->getMethodFamily() ==
OMF_init) {
3773 EscapingSymbol = Msg->getReceiverSVal().getAsSymbol();
3788 if (!
Call->isInSystemHeader())
3795 StringRef FName = II->
getName();
3799 if (FName.ends_with(
"NoCopy")) {
3803 for (
unsigned i = 1; i <
Call->getNumArgs(); ++i) {
3804 const Expr *ArgE =
Call->getArgExpr(i)->IgnoreParenCasts();
3805 if (
const DeclRefExpr *DE = dyn_cast<DeclRefExpr>(ArgE)) {
3806 StringRef DeallocatorName = DE->getFoundDecl()->getName();
3807 if (DeallocatorName ==
"kCFAllocatorNull")
3818 if (FName ==
"funopen")
3819 if (
Call->getNumArgs() >= 5 &&
Call->getArgSVal(4).isConstant(0))
3825 if (FName ==
"setbuf" || FName ==
"setbuffer" ||
3826 FName ==
"setlinebuf" || FName ==
"setvbuf") {
3827 if (
Call->getNumArgs() >= 1) {
3829 if (
const DeclRefExpr *ArgDRE = dyn_cast<DeclRefExpr>(ArgE))
3830 if (
const VarDecl *D = dyn_cast<VarDecl>(ArgDRE->getDecl()))
3831 if (D->getCanonicalDecl()->getName().contains(
"std"))
3841 if (FName ==
"CGBitmapContextCreate" ||
3842 FName ==
"CGBitmapContextCreateWithData" ||
3843 FName ==
"CVPixelBufferCreateWithBytes" ||
3844 FName ==
"CVPixelBufferCreateWithPlanarBytes" ||
3845 FName ==
"OSAtomicEnqueue") {
3849 if (FName ==
"postEvent" &&
3854 if (FName ==
"connectImpl" &&
3859 if (FName ==
"singleShotImpl" &&
3869 if (FName ==
"GetOwnedMessageInternal") {
3877 if (
Call->argumentsMayEscape())
3887 const CallEvent *
Call,
3889 return checkPointerEscapeAux(State, Escaped,
Call, Kind,
3895 const CallEvent *
Call,
3898 return checkPointerEscapeAux(State, Escaped,
Call, Kind,
3903 return (RS->getAllocationFamily().Kind == AF_CXXNewArray ||
3904 RS->getAllocationFamily().Kind == AF_CXXNew);
3910 bool IsConstPointerEscape)
const {
3919 if (ignoreDirectEscapeTo(
Call, EscapingSymbol))
3924 if (EscapingSymbol && EscapingSymbol != sym)
3927 if (
const RefState *RS = State->get<RegionState>(sym))
3928 if (RS->isAllocated())
3930 State = State->set<RegionState>(sym, RefState::getEscaped(RS));
3935bool MallocChecker::isArgZERO_SIZE_PTR(
ProgramStateRef State, CheckerContext &
C,
3936 SVal ArgVal)
const {
3937 if (!KernelZeroSizePtrValue)
3938 KernelZeroSizePtrValue =
3941 const llvm::APSInt *ArgValKnown =
3942 C.getSValBuilder().getKnownValue(State, ArgVal);
3943 return ArgValKnown && *KernelZeroSizePtrValue &&
3944 ArgValKnown->getSExtValue() == **KernelZeroSizePtrValue;
3949 ReallocPairsTy currMap = currState->get<ReallocPairs>();
3950 ReallocPairsTy prevMap = prevState->get<ReallocPairs>();
3952 for (
const ReallocPairsTy::value_type &Pair : prevMap) {
3954 if (!currMap.lookup(sym))
3964 if (N.contains_insensitive(
"ptr") || N.contains_insensitive(
"pointer")) {
3965 if (N.contains_insensitive(
"ref") || N.contains_insensitive(
"cnt") ||
3966 N.contains_insensitive(
"intrusive") ||
3967 N.contains_insensitive(
"shared") || N.ends_with_insensitive(
"rc")) {
3976 BugReporterContext &BRC,
3977 PathSensitiveBugReport &BR) {
3981 const RefState *RSCurr = state->get<RegionState>(Sym);
3982 const RefState *RSPrev = statePrev->get<RegionState>(Sym);
3987 if (!S && (!RSCurr || RSCurr->getAllocationFamily().Kind != AF_InnerBuffer))
4000 if (ReleaseFunctionSF && (ReleaseFunctionSF == CurrentSF ||
4002 if (
const auto *AE = dyn_cast<AtomicExpr>(S)) {
4005 if (Op == AtomicExpr::AO__c11_atomic_fetch_add ||
4006 Op == AtomicExpr::AO__c11_atomic_fetch_sub) {
4012 }
else if (
const auto *CE = dyn_cast<CallExpr>(S)) {
4015 if (
const auto *MD =
4017 const CXXRecordDecl *RD = MD->getParent();
4035 std::unique_ptr<StackHintGeneratorForSymbol> StackHint =
nullptr;
4036 SmallString<256> Buf;
4037 llvm::raw_svector_ostream
OS(Buf);
4040 if (isAllocated(RSCurr, RSPrev, S)) {
4041 Msg =
"Memory is allocated";
4042 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4043 Sym,
"Returned allocated memory");
4045 const auto Family = RSCurr->getAllocationFamily();
4046 switch (Family.Kind) {
4051 case AF_CXXNewArray:
4052 case AF_IfNameIndex:
4053 Msg =
"Memory is released";
4054 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4055 Sym,
"Returning; memory was released");
4057 case AF_InnerBuffer: {
4058 const MemRegion *ObjRegion =
4061 QualType ObjTy = TypedRegion->getValueType();
4062 OS <<
"Inner buffer of '" << ObjTy <<
"' ";
4065 OS <<
"deallocated by call to destructor";
4066 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4067 Sym,
"Returning; inner buffer was deallocated");
4069 OS <<
"reallocated by call to '";
4070 const Stmt *S = RSCurr->getStmt();
4071 if (
const auto *MemCallE = dyn_cast<CXXMemberCallExpr>(S)) {
4072 OS << MemCallE->getMethodDecl()->getDeclName();
4073 }
else if (
const auto *OpCallE = dyn_cast<CXXOperatorCallExpr>(S)) {
4074 OS << OpCallE->getDirectCallee()->getDeclName();
4075 }
else if (
const auto *CallE = dyn_cast<CallExpr>(S)) {
4077 CallEventRef<>
Call =
4079 if (
const auto *D = dyn_cast_or_null<NamedDecl>(
Call->getDecl()))
4080 OS << D->getDeclName();
4085 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4086 Sym,
"Returning; inner buffer was reallocated");
4092 assert(
false &&
"Unhandled allocation family!");
4102 ReleaseFunctionSF = CurrentSF;
4106 if (
const auto *DD = dyn_cast<CXXDestructorDecl>(SF.
getDecl())) {
4142 ReleaseFunctionSF = &SF;
4146 }
else if (isRelinquished(RSCurr, RSPrev, S)) {
4147 Msg =
"Memory ownership is transferred";
4148 StackHint = std::make_unique<StackHintGeneratorForSymbol>(Sym,
"");
4149 }
else if (hasReallocFailed(RSCurr, RSPrev, S)) {
4150 Mode = ReallocationFailed;
4151 Msg =
"Reallocation failed";
4152 StackHint = std::make_unique<StackHintGeneratorForReallocationFailed>(
4153 Sym,
"Reallocation failed");
4157 assert((!FailedReallocSymbol || FailedReallocSymbol == sym) &&
4158 "We only support one failed realloc at a time.");
4160 FailedReallocSymbol = sym;
4165 }
else if (Mode == ReallocationFailed) {
4166 assert(FailedReallocSymbol &&
"No symbol to look for.");
4169 if (!statePrev->get<RegionState>(FailedReallocSymbol)) {
4171 Msg =
"Attempt to reallocate memory";
4172 StackHint = std::make_unique<StackHintGeneratorForSymbol>(
4173 Sym,
"Returned reallocated memory");
4174 FailedReallocSymbol =
nullptr;
4187 PathDiagnosticLocation Pos;
4189 assert(RSCurr->getAllocationFamily().Kind == AF_InnerBuffer);
4193 Pos = PathDiagnosticLocation(PostImplCall->getLocation(),
4199 auto P = std::make_shared<PathDiagnosticEventPiece>(Pos, Msg,
true);
4204void MallocChecker::printState(raw_ostream &Out,
ProgramStateRef State,
4205 const char *NL,
const char *Sep)
const {
4207 RegionStateTy RS = State->get<RegionState>();
4209 if (!RS.isEmpty()) {
4210 Out << Sep <<
"MallocChecker :" << NL;
4211 for (
auto [Sym,
Data] : RS) {
4212 const RefState *RefS = State->get<RegionState>(Sym);
4213 AllocationFamily Family = RefS->getAllocationFamily();
4215 const CheckerFrontend *Frontend =
4216 getRelevantFrontendAs<CheckerFrontend>(Family);
4230namespace allocation_state {
4234 AllocationFamily Family(AF_InnerBuffer);
4235 return State->set<RegionState>(Sym, RefState::getReleased(Family, Origin));
4245 Mgr.
getChecker<MallocChecker>()->InnerPointerChecker.enable(Mgr);
4253 Chk->ShouldIncludeOwnershipAnnotatedFunctions =
4255 Chk->ShouldRegisterNoOwnershipChangeVisitor =
4257 DMMName,
"AddNoOwnershipChangeNotes");
4258 Chk->ModelAllocationFailure =
4260 DMMName,
"ModelAllocationFailure");
4263bool ento::shouldRegisterDynamicMemoryModeling(
const CheckerManager &mgr) {
4267#define REGISTER_CHECKER(NAME) \
4268 void ento::register##NAME(CheckerManager &Mgr) { \
4269 Mgr.getChecker<MallocChecker>()->NAME.enable(Mgr); \
4272 bool ento::shouldRegister##NAME(const CheckerManager &) { return true; }
4281#undef REGISTER_CHECKER
#define REGISTER_CHECKER(name)
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::Expr interface and subclasses for C++ expressions.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
llvm::MachO::Target Target
static bool isRvalueByValueRecordWithSmartPtr(const Expr *AE)
Check if an expression is an rvalue record with smart owning pointer fields passed by value.
static bool isFromStdNamespace(const CallEvent &Call)
static bool isStandardNew(const FunctionDecl *FD)
static bool hasNonTrivialConstructorCall(const CXXNewExpr *NE)
static QualType getDeepPointeeType(QualType T)
static bool isReleased(SymbolRef Sym, CheckerContext &C)
Check if the memory associated with this symbol was released.
static void printExpectedAllocName(raw_ostream &os, AllocationFamily Family)
Print expected name of an allocator based on the deallocator's family derived from the DeallocExpr.
static void collectSmartPtrFieldRegions(const MemRegion *Reg, QualType RecQT, CheckerContext &C, llvm::SmallPtrSetImpl< const MemRegion * > &Out)
Collect memory regions of smart owning pointer fields from a record type (including fields from base ...
static bool hasSmartPtrField(const CXXRecordDecl *CRD, std::optional< FieldConsumer > FC=std::nullopt)
Check if a record type has smart owning pointer fields (directly or in base classes).
static bool isStandardDelete(const FunctionDecl *FD)
static bool isReferenceCountingPointerDestructor(const CXXDestructorDecl *DD)
static bool isSmartPtrType(QualType QT)
static bool isStandardNewDelete(const T &FD)
Tells if the callee is one of the builtin new/delete operators, including placement operators and oth...
static SymbolRef findFailedReallocSymbol(ProgramStateRef currState, ProgramStateRef prevState)
static bool isRvalueByValueRecord(const Expr *AE)
Check if an expression is an rvalue record type passed by value.
#define BUGTYPE_PROVIDER(NAME, DEF)
static bool isGRealloc(const CallEvent &Call)
static const Expr * getPlacementNewBufferArg(const CallExpr *CE, const FunctionDecl *FD)
static bool isSmartPtrRecord(const CXXRecordDecl *RD)
Check if a CXXRecordDecl has a name matching recognized smart pointer names.
static void printExpectedDeallocName(raw_ostream &os, AllocationFamily Family)
Print expected name of a deallocator based on the allocator's family.
static bool isStandardRealloc(const CallEvent &Call)
static bool isSmartPtrCall(const CallEvent &Call)
Check if a call is a constructor of a smart owning pointer class that accepts pointer parameters.
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.
static ProgramStateRef MallocUpdateRefState(CheckerContext &C, const Expr *E, ProgramStateRef State, AllocationFamily Family, std::optional< SVal > RetVal=std::nullopt)
Update the RefState to reflect the new memory allocation.
static bool printMemFnName(raw_ostream &os, CheckerContext &C, const Expr *E)
Print names of allocators and deallocators.
static bool isSmartPtrName(StringRef Name)
static void printOwnershipTakesList(raw_ostream &os, CheckerContext &C, const Expr *E)
static bool isKnownDeallocObjCMethodName(const ObjCMethodCall &Call)
static std::optional< bool > getFreeWhenDoneArg(const ObjCMethodCall &Call)
static bool checkIfNewOrNewArrayFamily(const RefState *RS)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_SET_WITH_PROGRAMSTATE(Name, Elem)
Declares an immutable set of type NameTy, suitable for placement into the ProgramState.
Defines the SourceManager interface.
__DEVICE__ long long abs(long long __n)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
CanQualType getCanonicalSizeType() const
CanQualType UnsignedLongTy
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
const BlockDecl * getBlockDecl() const
Represents a base class of a C++ class.
Represents binding an expression to a temporary.
Represents a call to a C++ constructor.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ constructor within a class.
Represents a delete expression for memory deallocation and destructor calls, e.g.
Represents a C++ destructor within a class.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Represents a C++ struct/union/class.
Represents a C++ functional cast expression that builds a temporary object.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
static CharSourceRange getTokenRange(SourceRange R)
Decl - This represents one declaration (or definition), e.g.
bool isInStdNamespace() const
ASTContext & getASTContext() const LLVM_READONLY
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Represents a member of a struct/union/class.
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
ArrayRef< ParmVarDecl * > parameters() const
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Describes an C or C++ initializer list.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
std::string getQualifiedNameAsString() const
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
An expression that sends a message to the given Objective-C object or class.
bool isConsumedExpr(Expr *E) const
std::optional< T > getAs() const
Convert to the specified ProgramPoint type, returning std::nullopt if this ProgramPoint is not of the...
A (possibly-)qualified type.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
field_range fields() const
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
unsigned getNumArgs() const
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isParentOf(const StackFrame *SF) const
const Decl * getDecl() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
SourceLocation getBeginLoc() const LLVM_READONLY
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
The base class of all kinds of template declarations (e.g., class, function, etc.).
NamedDecl * getTemplatedDecl() const
Get the underlying, templated declaration.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool isVoidPointerType() const
bool isFunctionPointerType() const
bool isPointerType() const
CanQualType getCanonicalTypeUnqualified() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
const T * getAs() const
Member-template getAs<specific type>'.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
APSIntPtr getMaxValue(const llvm::APSInt &v)
StringRef getDescription() const
A verbose warning message that is appropriate for displaying next to the source code that introduces ...
ProgramStateManager & getStateManager() const
const SourceManager & getSourceManager() const
BugReporterVisitors are used to add custom diagnostics along a path.
An immutable map from CallDescriptions to arbitrary data.
const T * lookup(const CallEvent &Call) const
CallEventRef getSimpleCall(const CallExpr *E, ProgramStateRef State, const StackFrame *SF, CFGBlock::ConstCFGElementRef ElemRef)
Represents an abstract call to a function or method along a particular path.
Checker families (where a single backend class implements multiple related frontends) should derive f...
A CheckerFrontend instance is what the user recognizes as "one checker": it has a public canonical na...
CheckerNameRef getName() const
const AnalyzerOptions & getAnalyzerOptions() const
CheckerNameRef getCurrentCheckerName() const
CHECKER * getChecker(AT &&...Args)
If the the singleton instance of a checker class is not yet constructed, then construct it (with the ...
This wrapper is used to ensure that only StringRefs originating from the CheckerRegistry are used as ...
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
ConditionTruthVal isNull(ProgramStateRef State, SymbolRef Sym)
Convenience method to query the state to see if a symbol is null or not null, or if neither assumptio...
const ProgramStateRef & getState() const
pred_iterator pred_begin()
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ProgramPoint getLocation() const
getLocation - Returns the edge associated with the given node.
llvm::iterator_range< StackFrame::parent_iterator > stackframes() const
Iterates over the current stack frame and all of its ancestors.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
static bool isLocType(QualType T)
const VarRegion * getVarRegion(const VarDecl *VD, const StackFrame *SF)
getVarRegion - Retrieve or create the memory region associated with a specified VarDecl and StackFram...
MemRegion - The root abstract class for all memory regions.
RegionOffset getAsOffset() const
Compute the offset within the top level memory object.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemSpaceRegion * getMemorySpace(ProgramStateRef State) const
Returns the most specific memory space for this memory region in the given ProgramStateRef.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getBaseRegion() const
virtual void printPretty(raw_ostream &os) const
Print the region for use in diagnostics.
const RegionTy * getAs() const
virtual bool canPrintPretty() const
Returns true if this region can be printed in a user-friendly way.
Represents any expression that calls an Objective-C method.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
static PathDiagnosticLocation create(const Decl *D, const SourceManager &SM)
Create a location corresponding to the given declaration.
void markInteresting(SymbolRef sym, bugreporter::TrackingKind TKind=bugreporter::TrackingKind::Thorough)
Marks a symbol as interesting.
void addCallStackHint(PathDiagnosticPieceRef Piece, std::unique_ptr< StackHintGenerator > StackHint)
PathDiagnosticLocation getLocation() const override
The primary location of the bug report that points at the undesirable behavior in the code.
void markInvalid(const void *Tag, const void *Data)
Marks the current report as invalid, meaning that it is probably a false positive and should not be r...
CallEventManager & getCallEventManager()
bool hasSymbolicOffset() const
int64_t getOffset() const
DefinedOrUnknownSVal makeZeroVal(QualType type)
Construct an SVal representing '0' for the specified type.
BasicValueFactory & getBasicValueFactory()
ASTContext & getContext()
nonloc::ConcreteInt makeIntVal(const IntegerLiteral *integer)
virtual SVal evalBinOpNN(ProgramStateRef state, BinaryOperator::Opcode op, NonLoc lhs, NonLoc rhs, QualType resultTy)=0
Create a new value which represents a binary expression with two non- location operands.
QualType getConditionType() const
SVal evalEQ(ProgramStateRef state, SVal lhs, SVal rhs)
loc::MemRegionVal getAllocaRegionVal(const Expr *E, const StackFrame *SF, unsigned Count)
Create an SVal representing the result of an alloca()-like call, that is, an AllocaRegion on the stac...
DefinedSVal getConjuredHeapSymbolVal(ConstCFGElementRef elem, const StackFrame *SF, QualType type, unsigned Count)
Conjure a symbol representing heap allocated memory region.
SVal evalBinOp(ProgramStateRef state, BinaryOperator::Opcode op, SVal lhs, SVal rhs, QualType type)
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
bool isUnknownOrUndef() const
SymbolRef getAsSymbol(bool IncludeBaseRegions=false) const
If this SVal wraps a symbol return that SymbolRef.
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
SymbolRef getAsLocSymbol(bool IncludeBaseRegions=false) const
If this SVal is a location and wraps a symbol, return that SymbolRef.
const MemRegion * getAsRegion() const
SymbolRef getLocSymbolInBase() const
Get the symbol in the SVal or its base region.
T castAs() const
Convert to the specified SVal type, asserting that this SVal is of the desired type.
SubRegion - A region that subsets another larger region.
LLVM_ATTRIBUTE_RETURNS_NONNULL const MemRegion * getSuperRegion() const
virtual void dumpToStream(raw_ostream &os) const
virtual QualType getType() const =0
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
SymbolRef getSymbol() const
It might return null.
const VarDecl * getDecl() const override=0
const StackFrame * getStackFrame() const
It might return null.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
const internal::VariadicDynCastAllOfMatcher< Stmt, CXXDeleteExpr > cxxDeleteExpr
Matches delete expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
internal::Matcher< T > findAll(const internal::Matcher< T > &Matcher)
Matches if the node or any descendant matches.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
ProgramStateRef markReleased(ProgramStateRef State, SymbolRef Sym, const Expr *Origin)
std::unique_ptr< BugReporterVisitor > getInnerPointerBRVisitor(SymbolRef Sym)
This function provides an additional visitor that augments the bug report with information relevant t...
const MemRegion * getContainerObjRegion(ProgramStateRef State, SymbolRef Sym)
'Sym' represents a pointer to the inner buffer of a container object.
const char *const MemoryError
const char *const TaintedData
std::vector< SymbolRef > getTaintedSymbols(ProgramStateRef State, const Expr *E, const StackFrame *SF, TaintTagType Kind=TaintTagGeneric)
Returns the tainted Symbols for a given expression and state.
PointerEscapeKind
Describes the different reasons a pointer escapes during analysis.
@ PSK_DirectEscapeOnCall
The pointer has been passed to a function call directly.
llvm::DenseSet< SymbolRef > InvalidatedSymbols
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
ProgramStateRef setDynamicExtent(ProgramStateRef State, const MemRegion *MR, DefinedOrUnknownSVal Extent)
Set the dynamic extent Extent of the region MR.
void registerInnerPointerCheckerAux(CheckerManager &Mgr)
Register the part of MallocChecker connected to InnerPointerChecker.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::optional< SVal > getPointeeVal(SVal PtrSVal, ProgramStateRef State)
std::optional< int > tryExpandAsInteger(StringRef Macro, const Preprocessor &PP)
Try to parse the value of a defined preprocessor macro.
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
bool NE(InterpState &S, CodePtr OpPC)
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
bool isa(CodeGen::Address addr)
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool operator!=(CanQual< T > x, CanQual< U > y)
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
int const char * function
Helper struct for collecting smart owning pointer field regions.
void consume(const FieldDecl *FD)
std::optional< FieldConsumer > switchToBase(const CXXRecordDecl *BaseDecl, bool IsVirtual)
FieldConsumer(const MemRegion *Reg, CheckerContext &C, llvm::SmallPtrSetImpl< const MemRegion * > &Out)
llvm::SmallPtrSetImpl< const MemRegion * > * Out