37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/StringExtras.h"
39#include "llvm/Support/Path.h"
53 std::min(
static_cast<char>(Lhs),
static_cast<char>(Rhs)));
56const char *getNullabilityString(
Nullability Nullab) {
58 case Nullability::Contradicted:
59 return "contradicted";
60 case Nullability::Nullable:
62 case Nullability::Unspecified:
64 case Nullability::Nonnull:
67 llvm_unreachable(
"Unexpected enumeration.");
73enum class ErrorKind :
int {
77 NullableAssignedToNonnull,
78 NullableReturnedToNonnull,
80 NullablePassedToNonnull
83class NullabilityChecker
85 check::Bind, check::PreCall, check::PreStmt<ReturnStmt>,
86 check::PostCall, check::PostStmt<ExplicitCastExpr>,
87 check::PostObjCMessage, check::DeadSymbols, eval::Assume,
88 check::Location, check::Event<ImplicitNullDerefEvent>,
89 check::BeginFunction> {
98 bool NoDiagnoseCallsToSystemHeaders =
false;
100 void checkBind(SVal L, SVal
V,
const Stmt *S,
bool AtDeclInit,
101 CheckerContext &
C)
const;
102 void checkPostStmt(
const ExplicitCastExpr *CE, CheckerContext &
C)
const;
103 void checkPreStmt(
const ReturnStmt *S, CheckerContext &
C)
const;
104 void checkPostObjCMessage(
const ObjCMethodCall &M, CheckerContext &
C)
const;
105 void checkPostCall(
const CallEvent &
Call, CheckerContext &
C)
const;
106 void checkPreCall(
const CallEvent &
Call, CheckerContext &
C)
const;
107 void checkDeadSymbols(SymbolReaper &SR, CheckerContext &
C)
const;
108 void checkEvent(ImplicitNullDerefEvent Event)
const;
109 void checkLocation(SVal Location,
bool IsLoad,
const Stmt *S,
110 CheckerContext &
C)
const;
111 void checkBeginFunction(CheckerContext &Ctx)
const;
113 bool Assumption)
const;
115 void printState(raw_ostream &Out,
ProgramStateRef State,
const char *NL,
116 const char *Sep)
const override;
118 StringRef getDebugTag()
const override {
return "NullabilityChecker"; }
123 CheckerFrontendWithBugType NullPassedToNonnull{
"Nullability",
125 CheckerFrontendWithBugType NullReturnedFromNonnull{
"Nullability",
127 CheckerFrontendWithBugType NullableDereferenced{
"Nullability",
129 CheckerFrontendWithBugType NullablePassedToNonnull{
"Nullability",
131 CheckerFrontendWithBugType NullableReturnedFromNonnull{
138 bool NeedTracking =
false;
141 class NullabilityBugVisitor :
public BugReporterVisitor {
143 NullabilityBugVisitor(
const MemRegion *M) : Region(M) {}
145 void Profile(llvm::FoldingSetNodeID &ID)
const override {
148 ID.AddPointer(Region);
152 BugReporterContext &BRC,
153 PathSensitiveBugReport &BR)
override;
157 const MemRegion *Region;
165 void reportBugIfInvariantHolds(StringRef Msg, ErrorKind
Error,
166 const BugType &BT, ExplodedNode *N,
167 const MemRegion *Region, CheckerContext &
C,
168 const Stmt *ValueExpr =
nullptr,
169 bool SuppressPath =
false)
const;
171 void reportBug(StringRef Msg, ErrorKind
Error,
const BugType &BT,
172 ExplodedNode *N,
const MemRegion *Region, BugReporter &BR,
173 const Stmt *ValueExpr =
nullptr)
const {
174 auto R = std::make_unique<PathSensitiveBugReport>(BT, Msg, N);
176 R->markInteresting(Region);
177 R->addVisitor<NullabilityBugVisitor>(Region);
180 R->addRange(ValueExpr->getSourceRange());
181 if (
Error == ErrorKind::NilAssignedToNonnull ||
182 Error == ErrorKind::NilPassedToNonnull ||
183 Error == ErrorKind::NilReturnedToNonnull)
184 if (
const auto *Ex = dyn_cast<Expr>(ValueExpr))
192 const SymbolicRegion *getTrackRegion(SVal Val,
193 bool CheckSuperRegion =
false)
const;
197 bool isDiagnosableCall(
const CallEvent &
Call)
const {
198 if (NoDiagnoseCallsToSystemHeaders &&
Call.isInSystemHeader())
205class NullabilityState {
207 NullabilityState(
Nullability Nullab,
const Stmt *Source =
nullptr)
208 : Nullab(Nullab), Source(Source) {}
210 const Stmt *getNullabilitySource()
const {
return Source; }
214 void Profile(llvm::FoldingSetNodeID &ID)
const {
215 ID.AddInteger(
static_cast<char>(Nullab));
216 ID.AddPointer(Source);
219 void print(raw_ostream &Out)
const {
220 Out << getNullabilityString(Nullab) <<
"\n";
232bool operator==(NullabilityState Lhs, NullabilityState Rhs) {
233 return Lhs.getValue() == Rhs.getValue() &&
234 Lhs.getNullabilitySource() == Rhs.getNullabilitySource();
240using ObjectPropPair = std::pair<const MemRegion *, const IdentifierInfo *>;
243struct ConstrainedPropertyVal {
246 DefinedOrUnknownSVal Value;
249 bool isConstrainedNonnull;
251 ConstrainedPropertyVal(DefinedOrUnknownSVal SV)
252 : Value(SV), isConstrainedNonnull(
false) {}
254 void Profile(llvm::FoldingSetNodeID &ID)
const {
256 ID.AddInteger(isConstrainedNonnull ? 1 : 0);
260bool operator==(
const ConstrainedPropertyVal &Lhs,
261 const ConstrainedPropertyVal &Rhs) {
262 return Lhs.Value == Rhs.Value &&
263 Lhs.isConstrainedNonnull == Rhs.isConstrainedNonnull;
271 ConstrainedPropertyVal)
312 return T->isAnyPointerType() || T->isBlockPointerType();
316NullabilityChecker::getTrackRegion(
SVal Val,
bool CheckSuperRegion)
const {
320 auto RegionSVal = Val.
getAs<loc::MemRegionVal>();
324 const MemRegion *Region = RegionSVal->getRegion();
326 if (CheckSuperRegion) {
327 if (
const SubRegion *FieldReg = Region->
getAs<FieldRegion>()) {
328 if (
const auto *ER = dyn_cast<ElementRegion>(FieldReg->getSuperRegion()))
330 return dyn_cast<SymbolicRegion>(FieldReg->getSuperRegion());
332 if (
auto ElementReg = Region->
getAs<ElementRegion>())
333 return dyn_cast<SymbolicRegion>(ElementReg->getSuperRegion());
336 return dyn_cast<SymbolicRegion>(Region);
340 const ExplodedNode *N, BugReporterContext &BRC,
341 PathSensitiveBugReport &BR) {
345 const NullabilityState *TrackedNullab = State->get<NullabilityMap>(Region);
346 const NullabilityState *TrackedNullabPrev =
347 StatePrev->get<NullabilityMap>(Region);
351 if (TrackedNullabPrev &&
352 TrackedNullabPrev->getValue() == TrackedNullab->getValue())
356 const Stmt *S = TrackedNullab->getNullabilitySource();
364 std::string InfoText =
365 (llvm::Twine(
"Nullability '") +
366 getNullabilityString(TrackedNullab->getValue()) +
"' is inferred")
371 return std::make_shared<PathDiagnosticEventPiece>(Pos, InfoText,
true);
404 for (
const auto *ParamDecl : Params) {
405 if (ParamDecl->isParameterPack())
413 SVal LV = State->getLValue(ParamDecl, SF);
424 auto *MD = dyn_cast<ObjCMethodDecl>(SF->
getDecl());
425 if (!MD || !MD->isInstanceMethod())
432 SVal SelfVal = State->getSVal(State->getRegion(SelfDecl, SF));
435 dyn_cast<ObjCObjectPointerType>(SelfDecl->
getType());
443 auto HasInvariantViolation = [&](
const ObjCIvarDecl *IvarDecl) {
444 SVal LV = State->getLValue(IvarDecl, SelfVal);
448 return llvm::any_of(ID->ivars(), HasInvariantViolation);
453 if (State->get<InvariantViolated>())
462 if (
const auto *BD = dyn_cast<BlockDecl>(D))
463 Params = BD->parameters();
464 else if (
const auto *FD = dyn_cast<FunctionDecl>(D))
465 Params = FD->parameters();
466 else if (
const auto *MD = dyn_cast<ObjCMethodDecl>(D))
467 Params = MD->parameters();
474 C.addTransition(State->set<InvariantViolated>(
true), N);
480void NullabilityChecker::reportBugIfInvariantHolds(
481 StringRef Msg, ErrorKind
Error,
const BugType &BT, ExplodedNode *N,
482 const MemRegion *Region, CheckerContext &
C,
const Stmt *ValueExpr,
483 bool SuppressPath)
const {
491 OriginalState = OriginalState->set<InvariantViolated>(
true);
492 N =
C.addTransition(OriginalState, N);
497 reportBug(Msg,
Error, BT, N, Region,
C.getBugReporter(), ValueExpr);
501void NullabilityChecker::checkDeadSymbols(SymbolReaper &SR,
502 CheckerContext &
C)
const {
504 NullabilityMapTy Nullabilities = State->get<NullabilityMap>();
505 for (
const MemRegion *Reg : llvm::make_first_range(Nullabilities)) {
506 const auto *Region = Reg->
getAs<SymbolicRegion>();
507 assert(Region &&
"Non-symbolic region is tracked.");
508 if (SR.
isDead(Region->getSymbol())) {
509 State = State->remove<NullabilityMap>(Reg);
515 PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
516 for (
ObjectPropPair PropKey : llvm::make_first_range(PropertyAccesses)) {
517 const MemRegion *ReceiverRegion = PropKey.first;
519 State = State->remove<PropertyAccessesMap>(PropKey);
529 C.addTransition(State);
535void NullabilityChecker::checkEvent(ImplicitNullDerefEvent Event)
const {
539 const MemRegion *Region =
540 getTrackRegion(Event.
Location,
true);
545 const NullabilityState *TrackedNullability =
546 State->get<NullabilityMap>(Region);
548 if (!TrackedNullability)
551 if (NullableDereferenced.isEnabled() &&
552 TrackedNullability->getValue() == Nullability::Nullable) {
553 BugReporter &BR = *Event.
BR;
557 reportBug(
"Nullable pointer is dereferenced",
558 ErrorKind::NullableDereferenced, NullableDereferenced,
561 reportBug(
"Nullable pointer is passed to a callee that requires a "
563 ErrorKind::NullablePassedToNonnull, NullableDereferenced,
569void NullabilityChecker::checkBeginFunction(CheckerContext &
C)
const {
573 const StackFrame *SF =
C.getStackFrame();
575 if (!AbstractCall || AbstractCall->parameters().empty())
579 for (
const ParmVarDecl *Param : AbstractCall->parameters()) {
585 if (RequiredNullability != Nullability::Nullable)
588 const VarRegion *ParamRegion = State->getRegion(Param, SF);
589 const MemRegion *ParamPointeeRegion =
590 State->getSVal(ParamRegion).getAsRegion();
591 if (!ParamPointeeRegion)
594 State = State->set<NullabilityMap>(ParamPointeeRegion,
595 NullabilityState(RequiredNullability));
597 C.addTransition(State);
613void NullabilityChecker::checkLocation(SVal Location,
bool IsLoad,
615 CheckerContext &Context)
const {
624 dyn_cast_or_null<TypedValueRegion>(Location.
getAsRegion());
633 auto StoredVal = State->getSVal(Region).getAs<loc::MemRegionVal>();
640 Context.addTransition(NewState);
654void NullabilityChecker::checkPreStmt(
const ReturnStmt *S,
655 CheckerContext &
C)
const {
664 if (State->get<InvariantViolated>())
667 auto RetSVal =
C.getSVal(RetExpr).getAs<DefinedOrUnknownSVal>();
671 bool InSuppressedMethodFamily =
false;
673 QualType RequiredRetType;
674 AnalysisDeclContext *DeclCtxt =
C.getStackFrame()->getAnalysisDeclContext();
676 if (
auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
683 InSuppressedMethodFamily =
true;
685 RequiredRetType = MD->getReturnType();
686 }
else if (
auto *FD = dyn_cast<FunctionDecl>(D)) {
687 RequiredRetType = FD->getReturnType();
695 if (
const auto *FunDecl =
C.getStackFrame()->getDecl();
696 FunDecl && FunDecl->getAttr<ReturnsNonNullAttr>() &&
697 (RequiredNullability == Nullability::Unspecified ||
698 RequiredNullability == Nullability::Nullable)) {
701 RequiredNullability = Nullability::Nonnull;
712 if (RequiredNullability == Nullability::Nonnull &&
714 if (NullReturnedFromNonnull.
isEnabled() &&
715 RetExprTypeLevelNullability != Nullability::Nonnull &&
716 !InSuppressedMethodFamily) {
717 ExplodedNode *N =
C.addSink(State);
721 SmallString<256> SBuf;
722 llvm::raw_svector_ostream
OS(SBuf);
723 OS << (RetExpr->getType()->isObjCObjectPointerType() ?
"nil" :
"Null");
724 OS <<
" returned from a " <<
C.getDeclDescription(D)
725 <<
" that is expected to return a non-null value";
726 reportBugIfInvariantHolds(
OS.str(), ErrorKind::NilReturnedToNonnull,
727 NullReturnedFromNonnull, N,
nullptr,
C,
734 State = State->set<InvariantViolated>(
true);
735 C.addTransition(State);
739 const MemRegion *Region = getTrackRegion(*RetSVal);
743 const NullabilityState *TrackedNullability =
744 State->get<NullabilityMap>(Region);
745 if (TrackedNullability) {
746 Nullability TrackedNullabValue = TrackedNullability->getValue();
747 if (NullableReturnedFromNonnull.
isEnabled() &&
749 TrackedNullabValue == Nullability::Nullable &&
750 RequiredNullability == Nullability::Nonnull) {
751 ExplodedNode *N =
C.addTransition(State,
C.getPredecessor());
753 SmallString<256> SBuf;
754 llvm::raw_svector_ostream
OS(SBuf);
755 OS <<
"Nullable pointer is returned from a " <<
C.getDeclDescription(D) <<
756 " that is expected to return a non-null value";
758 reportBugIfInvariantHolds(
OS.str(), ErrorKind::NullableReturnedToNonnull,
759 NullableReturnedFromNonnull, N, Region,
C);
763 if (RequiredNullability == Nullability::Nullable) {
764 State = State->set<NullabilityMap>(Region,
765 NullabilityState(RequiredNullability,
767 C.addTransition(State);
773void NullabilityChecker::checkPreCall(
const CallEvent &
Call,
774 CheckerContext &
C)
const {
779 if (State->get<InvariantViolated>())
785 for (
const ParmVarDecl *Param :
Call.parameters()) {
786 if (Param->isParameterPack())
789 if (Idx >=
Call.getNumArgs())
792 const Expr *ArgExpr =
Call.getArgExpr(Idx);
793 auto ArgSVal =
Call.getArgSVal(Idx++).getAs<DefinedOrUnknownSVal>();
798 !Param->getType()->isReferenceType())
808 unsigned ParamIdx = Param->getFunctionScopeIndex() + 1;
811 ArgExprTypeLevelNullability != Nullability::Nonnull &&
812 RequiredNullability == Nullability::Nonnull &&
813 isDiagnosableCall(
Call)) {
814 ExplodedNode *N =
C.addSink(State);
818 SmallString<256> SBuf;
819 llvm::raw_svector_ostream
OS(SBuf);
820 OS << (Param->getType()->isObjCObjectPointerType() ?
"nil" :
"Null");
821 OS <<
" passed to a callee that requires a non-null " << ParamIdx
822 << llvm::getOrdinalSuffix(ParamIdx) <<
" parameter";
823 reportBugIfInvariantHolds(
OS.str(), ErrorKind::NilPassedToNonnull,
824 NullPassedToNonnull, N,
nullptr,
C, ArgExpr,
829 const MemRegion *Region = getTrackRegion(*ArgSVal);
833 const NullabilityState *TrackedNullability =
834 State->get<NullabilityMap>(Region);
836 if (TrackedNullability) {
838 TrackedNullability->getValue() != Nullability::Nullable)
841 if (NullablePassedToNonnull.isEnabled() &&
842 RequiredNullability == Nullability::Nonnull &&
843 isDiagnosableCall(
Call)) {
844 ExplodedNode *N =
C.addTransition(State);
845 SmallString<256> SBuf;
846 llvm::raw_svector_ostream
OS(SBuf);
847 OS <<
"Nullable pointer is passed to a callee that requires a non-null "
848 << ParamIdx << llvm::getOrdinalSuffix(ParamIdx) <<
" parameter";
849 reportBugIfInvariantHolds(
OS.str(), ErrorKind::NullablePassedToNonnull,
850 NullablePassedToNonnull, N, Region,
C,
854 if (NullableDereferenced.isEnabled() &&
855 Param->getType()->isReferenceType()) {
856 ExplodedNode *N =
C.addTransition(State);
857 reportBugIfInvariantHolds(
858 "Nullable pointer is dereferenced", ErrorKind::NullableDereferenced,
859 NullableDereferenced, N, Region,
C, ArgExpr,
true);
865 if (State != OrigState)
866 C.addTransition(State);
870void NullabilityChecker::checkPostCall(
const CallEvent &
Call,
871 CheckerContext &
C)
const {
878 const FunctionType *FuncType =
Decl->getFunctionType();
885 if (State->get<InvariantViolated>())
888 const MemRegion *Region = getTrackRegion(
Call.getReturnValue());
894 const SourceManager &SM =
C.getSourceManager();
896 if (llvm::sys::path::filename(FilePath).starts_with(
"CG")) {
897 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
898 C.addTransition(State);
902 const NullabilityState *TrackedNullability =
903 State->get<NullabilityMap>(Region);
910 if (
const Expr *E =
Call.getOriginExpr())
911 ReturnType = E->getType();
913 if (!TrackedNullability &&
915 State = State->set<NullabilityMap>(Region, Nullability::Nullable);
916 C.addTransition(State);
925 return Nullability::Nonnull;
934 return Nullability::Nonnull;
937 if (ValueRegionSVal) {
938 const MemRegion *SelfRegion = ValueRegionSVal->getRegion();
941 const NullabilityState *TrackedSelfNullability =
942 State->get<NullabilityMap>(SelfRegion);
943 if (TrackedSelfNullability)
944 return TrackedSelfNullability->getValue();
946 return Nullability::Unspecified;
954 bool Assumption)
const {
955 PropertyAccessesMapTy PropertyAccesses = State->get<PropertyAccessesMap>();
956 for (
auto [PropKey, PropVal] : PropertyAccesses) {
957 if (!PropVal.isConstrainedNonnull) {
958 ConditionTruthVal
IsNonNull = State->isNonNull(PropVal.Value);
960 ConstrainedPropertyVal Replacement = PropVal;
961 Replacement.isConstrainedNonnull =
true;
962 State = State->set<PropertyAccessesMap>(PropKey, Replacement);
963 }
else if (
IsNonNull.isConstrainedFalse()) {
965 State = State->remove<PropertyAccessesMap>(PropKey);
976void NullabilityChecker::checkPostObjCMessage(
const ObjCMethodCall &M,
977 CheckerContext &
C)
const {
981 QualType RetType =
Decl->getReturnType();
986 if (State->get<InvariantViolated>())
989 const MemRegion *ReturnRegion = getTrackRegion(M.
getReturnValue());
998 if (Name.starts_with(
"NS")) {
1009 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
1010 C.addTransition(State);
1015 if (Name.contains(
"Array") &&
1016 (FirstSelectorSlot ==
"firstObject" ||
1017 FirstSelectorSlot ==
"lastObject")) {
1019 State->set<NullabilityMap>(ReturnRegion, Nullability::Contradicted);
1020 C.addTransition(State);
1028 if (Name.contains(
"String")) {
1030 if (Param->getName() ==
"encoding") {
1031 State = State->set<NullabilityMap>(ReturnRegion,
1032 Nullability::Contradicted);
1033 C.addTransition(State);
1043 const NullabilityState *NullabilityOfReturn =
1044 State->get<NullabilityMap>(ReturnRegion);
1046 if (NullabilityOfReturn) {
1050 Nullability RetValTracked = NullabilityOfReturn->getValue();
1052 getMostNullable(RetValTracked, SelfNullability);
1053 if (ComputedNullab != RetValTracked &&
1054 ComputedNullab != Nullability::Unspecified) {
1055 const Stmt *NullabilitySource =
1056 ComputedNullab == RetValTracked
1057 ? NullabilityOfReturn->getNullabilitySource()
1058 :
Message->getInstanceReceiver();
1059 State = State->set<NullabilityMap>(
1060 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
1061 C.addTransition(State);
1084 if (RetNullability != Nullability::Nonnull &&
1086 bool LookupResolved =
false;
1087 if (
const MemRegion *ReceiverRegion = getTrackRegion(M.
getReceiverSVal())) {
1088 if (
const IdentifierInfo *Ident =
1090 LookupResolved =
true;
1092 const ConstrainedPropertyVal *PrevPropVal =
1093 State->get<PropertyAccessesMap>(Key);
1094 if (PrevPropVal && PrevPropVal->isConstrainedNonnull) {
1095 RetNullability = Nullability::Nonnull;
1103 if (
auto ReturnSVal =
1105 State = State->set<PropertyAccessesMap>(
1106 Key, ConstrainedPropertyVal(*ReturnSVal));
1112 if (!LookupResolved) {
1114 RetNullability = Nullability::Nonnull;
1118 Nullability ComputedNullab = getMostNullable(RetNullability, SelfNullability);
1119 if (ComputedNullab == Nullability::Nullable) {
1120 const Stmt *NullabilitySource = ComputedNullab == RetNullability
1122 :
Message->getInstanceReceiver();
1123 State = State->set<NullabilityMap>(
1124 ReturnRegion, NullabilityState(ComputedNullab, NullabilitySource));
1125 C.addTransition(State);
1133void NullabilityChecker::checkPostStmt(
const ExplicitCastExpr *CE,
1134 CheckerContext &
C)
const {
1136 QualType DestType = CE->
getType();
1143 if (State->get<InvariantViolated>())
1150 if (DestNullability == Nullability::Unspecified)
1153 auto RegionSVal =
C.getSVal(CE).getAs<DefinedOrUnknownSVal>();
1154 const MemRegion *Region = getTrackRegion(*RegionSVal);
1159 if (DestNullability == Nullability::Nonnull) {
1162 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1163 C.addTransition(State);
1168 const NullabilityState *TrackedNullability =
1169 State->get<NullabilityMap>(Region);
1171 if (!TrackedNullability) {
1172 if (DestNullability != Nullability::Nullable)
1174 State = State->set<NullabilityMap>(Region,
1175 NullabilityState(DestNullability, CE));
1176 C.addTransition(State);
1180 if (TrackedNullability->getValue() != DestNullability &&
1181 TrackedNullability->getValue() != Nullability::Contradicted) {
1182 State = State->set<NullabilityMap>(Region, Nullability::Contradicted);
1183 C.addTransition(State);
1191 if (
auto *BinOp = dyn_cast<BinaryOperator>(S)) {
1192 if (BinOp->getOpcode() == BO_Assign)
1193 return BinOp->getRHS();
1197 if (
auto *DS = dyn_cast<DeclStmt>(S)) {
1198 if (DS->isSingleDecl()) {
1199 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1203 if (
const Expr *
Init = VD->getInit())
1228 if (!
C.getASTContext().getLangOpts().ObjCAutoRefCount)
1231 auto *DS = dyn_cast<DeclStmt>(S);
1232 if (!DS || !DS->isSingleDecl())
1235 auto *VD = dyn_cast<VarDecl>(DS->getSingleDecl());
1240 if(!VD->getType().getQualifiers().hasObjCLifetime())
1244 assert(
Init &&
"ObjC local under ARC without initializer");
1255void NullabilityChecker::checkBind(SVal L, SVal
V,
const Stmt *S,
1256 bool AtDeclInit, CheckerContext &
C)
const {
1257 const TypedValueRegion *TVR =
1258 dyn_cast_or_null<TypedValueRegion>(L.
getAsRegion());
1267 if (State->get<InvariantViolated>())
1270 auto ValDefOrUnknown =
V.getAs<DefinedOrUnknownSVal>();
1271 if (!ValDefOrUnknown)
1276 Nullability ValNullability = Nullability::Unspecified;
1277 if (
SymbolRef Sym = ValDefOrUnknown->getAsSymbol())
1284 Nullability ValueExprTypeLevelNullability = Nullability::Unspecified;
1287 ValueExprTypeLevelNullability =
1291 bool NullAssignedToNonNull = (LocNullability == Nullability::Nonnull &&
1293 if (NullPassedToNonnull.
isEnabled() && NullAssignedToNonNull &&
1294 ValNullability != Nullability::Nonnull &&
1295 ValueExprTypeLevelNullability != Nullability::Nonnull &&
1297 ExplodedNode *N =
C.addSink(State);
1302 const Stmt *ValueStmt = S;
1304 ValueStmt = ValueExpr;
1306 SmallString<256> SBuf;
1307 llvm::raw_svector_ostream
OS(SBuf);
1309 OS <<
" assigned to a pointer which is expected to have non-null value";
1310 reportBugIfInvariantHolds(
OS.str(), ErrorKind::NilAssignedToNonnull,
1311 NullPassedToNonnull, N,
nullptr,
C, ValueStmt);
1317 if (NullAssignedToNonNull) {
1318 State = State->set<InvariantViolated>(
true);
1319 C.addTransition(State);
1326 const MemRegion *ValueRegion = getTrackRegion(*ValDefOrUnknown);
1330 const NullabilityState *TrackedNullability =
1331 State->get<NullabilityMap>(ValueRegion);
1333 if (TrackedNullability) {
1335 TrackedNullability->getValue() != Nullability::Nullable)
1337 if (NullablePassedToNonnull.isEnabled() &&
1338 LocNullability == Nullability::Nonnull) {
1339 ExplodedNode *N =
C.addTransition(State,
C.getPredecessor());
1340 reportBugIfInvariantHolds(
"Nullable pointer is assigned to a pointer "
1341 "which is expected to have non-null value",
1342 ErrorKind::NullableAssignedToNonnull,
1343 NullablePassedToNonnull, N, ValueRegion,
C);
1348 const auto *BinOp = dyn_cast<BinaryOperator>(S);
1350 if (ValNullability == Nullability::Nullable) {
1353 const Stmt *NullabilitySource = BinOp ? BinOp->getRHS() : S;
1354 State = State->set<NullabilityMap>(
1355 ValueRegion, NullabilityState(ValNullability, NullabilitySource));
1356 C.addTransition(State);
1360 if (LocNullability == Nullability::Nullable) {
1361 const Stmt *NullabilitySource = BinOp ? BinOp->getLHS() : S;
1362 State = State->set<NullabilityMap>(
1363 ValueRegion, NullabilityState(LocNullability, NullabilitySource));
1364 C.addTransition(State);
1368void NullabilityChecker::printState(raw_ostream &Out,
ProgramStateRef State,
1369 const char *NL,
const char *Sep)
const {
1371 NullabilityMapTy B = State->get<NullabilityMap>();
1373 if (State->get<InvariantViolated>())
1375 <<
"Nullability invariant was violated, warnings suppressed." << NL;
1380 if (!State->get<InvariantViolated>())
1383 for (
auto [Region, State] : B) {
1384 Out << Region <<
" : ";
1397constexpr llvm::StringLiteral
GroupOptName =
"NoDiagnoseCallsToSystemHeaders";
1399#define REGISTER_CHECKER(NAME, TRACKING_REQUIRED) \
1400 void ento::register##NAME##Checker(CheckerManager &Mgr) { \
1401 NullabilityChecker *Chk = Mgr.getChecker<NullabilityChecker>(); \
1402 Chk->NAME.enable(Mgr); \
1403 Chk->NeedTracking = Chk->NeedTracking || TRACKING_REQUIRED; \
1404 Chk->NoDiagnoseCallsToSystemHeaders = \
1405 Mgr.getAnalyzerOptions().getCheckerBooleanOption(GroupName, \
1406 GroupOptName, true); \
1409 bool ento::shouldRegister##NAME##Checker(const CheckerManager &) { \
1424#undef REGISTER_CHECKER
#define REGISTER_CHECKER(name)
static void print(llvm::raw_ostream &OS, const T &V, const Context &Ctx, QualType Ty)
static bool isValidPointerType(QualType T)
static NullConstraint getNullConstraint(DefinedOrUnknownSVal Val, ProgramStateRef State)
static bool isARCNilInitializedLocal(CheckerContext &C, const Stmt *S)
Returns true if.
constexpr llvm::StringLiteral GroupOptName
static bool checkValueAtLValForInvariantViolation(ProgramStateRef State, SVal LV, QualType T)
Returns true when the value stored at the given location has been constrained to null after being pas...
static const Expr * matchValueExprForBind(const Stmt *S)
For a given statement performing a bind, attempt to syntactically match the expression resulting in t...
static bool checkInvariantViolation(ProgramStateRef State, ExplodedNode *N, CheckerContext &C)
constexpr llvm::StringLiteral GroupName
static const Expr * lookThroughImplicitCasts(const Expr *E)
Find the outermost subexpression of E that is not an implicit cast.
static bool checkParamsForPreconditionViolation(ArrayRef< ParmVarDecl * > Params, ProgramStateRef State, const StackFrame *SF)
static bool checkSelfIvarsForInvariantViolation(ProgramStateRef State, const StackFrame *SF)
static Nullability getReceiverNullability(const ObjCMethodCall &M, ProgramStateRef State)
#define REGISTER_MAP_WITH_PROGRAMSTATE(Name, Key, Value)
Declares an immutable map of type NameTy, suitable for placement into the ProgramState.
#define REGISTER_TRAIT_WITH_PROGRAMSTATE(Name, Type)
Declares a program state trait for type Type called Name, and introduce a type named NameTy.
const Decl * getDecl() const
static std::optional< AnyCall > forDecl(const Decl *D)
If D is a callable (Objective-C method or a function), return a constructed AnyCall object.
Decl - This represents one declaration (or definition), e.g.
This represents one expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
QualType getReturnType() const
Represents an ObjC class declaration.
ObjCIvarDecl - Represents an ObjC instance variable.
Represents a pointer to an Objective C object.
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
A (possibly-)qualified type.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
It represents a stack frame of the call stack.
const Decl * getDecl() const
const ImplicitParamDecl * getSelfDecl() const
Stmt - This represents one statement.
SourceLocation getBeginLoc() const LLVM_READONLY
bool isObjCObjectPointerType() const
const SourceManager & getSourceManager() const
virtual void emitReport(std::unique_ptr< BugReport > R)
Add the given report to the set of reports tracked by BugReporter.
SVal getReturnValue() const
Returns the return value of the call.
Checker families (where a single backend class implements multiple related frontends) should derive f...
bool isConstrainedFalse() const
Return true if the constraint is perfectly constrained to 'false'.
bool isConstrainedTrue() const
Return true if the constraint is perfectly constrained to 'true'.
const ProgramStateRef & getState() const
const Stmt * getStmtForDiagnostics() const
If the node's program point corresponds to a statement, retrieve that statement.
ExplodedNode * getFirstPred()
const StackFrame * getStackFrame() const
MemRegion - The root abstract class for all memory regions.
const RegionTy * getAs() const
Represents any expression that calls an Objective-C method.
const ObjCMethodDecl * getDecl() const override
Returns the declaration of the function or method that will be called.
bool isInstanceMessage() const
ObjCMessageKind getMessageKind() const
Returns how the message was written in the source (property access, subscript, or explicit message se...
const ObjCMessageExpr * getOriginExpr() const override
Returns the expression whose value will be the result of this call.
ArrayRef< ParmVarDecl * > parameters() const override
Return call's formal parameters.
SVal getReceiverSVal() const
Returns the value of the receiver at the time of this call.
bool isReceiverSelfOrSuper() const
Checks if the receiver refers to 'self' or 'super'.
Selector getSelector() const
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
std::optional< T > getAs() const
Convert to the specified SVal type, returning std::nullopt if this SVal is not of the desired type.
QualType getType(const ASTContext &) const
Try to get a reasonable type for the given value.
const MemRegion * getAsRegion() const
bool isDead(SymbolRef sym)
Returns whether or not a symbol has been confirmed dead.
bool isLiveRegion(const MemRegion *region)
SymbolicRegion - A special, "non-concrete" region.
virtual QualType getValueType() const =0
bool trackExpressionValue(const ExplodedNode *N, const Expr *E, PathSensitiveBugReport &R, TrackingOptions Opts={})
Attempts to add visitors to track expression value back to its point of origin.
const char *const MemoryError
Nullability getNullabilityAnnotation(QualType Type)
Get nullability annotation for a given type.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
const SymExpr * SymbolRef
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
std::shared_ptr< PathDiagnosticPiece > PathDiagnosticPieceRef
bool IsNonNull(InterpState &S)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
ObjCMethodFamily
A family of Objective-C methods.
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.