clang 23.0.0git
NonNullParamChecker.cpp
Go to the documentation of this file.
1//===--- NonNullParamChecker.cpp - Undefined arguments checker -*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This defines NonNullParamChecker, which checks for arguments expected not to
10// be null due to:
11// - the corresponding parameters being declared to have nonnull attribute
12// - the corresponding parameters being references; since the call would form
13// a reference to a null pointer
14//
15//===----------------------------------------------------------------------===//
16
17#include "clang/AST/Attr.h"
25
26using namespace clang;
27using namespace ento;
28
29namespace {
30class NonNullParamChecker
31 : public Checker<check::PreCall, check::BeginFunction,
32 EventDispatcher<ImplicitNullDerefEvent>> {
33 const BugType BTAttrNonNull{
34 this, "Argument with 'nonnull' attribute passed null", "API"};
35 const BugType BTNullRefArg{this, "Dereference of null pointer"};
36
37public:
38 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
39 void checkBeginFunction(CheckerContext &C) const;
40
41 std::unique_ptr<PathSensitiveBugReport>
42 genReportNullAttrNonNull(const ExplodedNode *ErrorN, const Expr *ArgE,
43 unsigned IdxOfArg) const;
44 std::unique_ptr<PathSensitiveBugReport>
45 genReportReferenceToNullPointer(const ExplodedNode *ErrorN,
46 const Expr *ArgE) const;
47};
48
49template <class CallType>
50void setBitsAccordingToFunctionAttributes(const CallType &Call,
51 llvm::SmallBitVector &AttrNonNull) {
52 const Decl *FD = Call.getDecl();
53
54 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
55 if (!NonNull->args_size()) {
56 // Lack of attribute parameters means that all of the parameters are
57 // implicitly marked as non-null.
58 AttrNonNull.set();
59 break;
60 }
61
62 for (const ParamIdx &Idx : NonNull->args()) {
63 // 'nonnull' attribute's parameters are 1-based and should be adjusted to
64 // match actual AST parameter/argument indices.
65 unsigned IdxAST = Idx.getASTIndex();
66 if (IdxAST >= AttrNonNull.size())
67 continue;
68 AttrNonNull.set(IdxAST);
69 }
70 }
71}
72
73template <class CallType>
74void setBitsAccordingToParameterAttributes(const CallType &Call,
75 llvm::SmallBitVector &AttrNonNull) {
76 for (const ParmVarDecl *Parameter : Call.parameters()) {
77 unsigned ParameterIndex = Parameter->getFunctionScopeIndex();
78 if (ParameterIndex == AttrNonNull.size())
79 break;
80
81 if (Parameter->hasAttr<NonNullAttr>())
82 AttrNonNull.set(ParameterIndex);
83 }
84}
85
86template <class CallType>
87llvm::SmallBitVector getNonNullAttrsImpl(const CallType &Call,
88 unsigned ExpectedSize) {
89 llvm::SmallBitVector AttrNonNull(ExpectedSize);
90
91 setBitsAccordingToFunctionAttributes(Call, AttrNonNull);
92 setBitsAccordingToParameterAttributes(Call, AttrNonNull);
93
94 return AttrNonNull;
95}
96
97/// \return Bitvector marking non-null attributes.
98llvm::SmallBitVector getNonNullAttrs(const CallEvent &Call) {
99 return getNonNullAttrsImpl(Call, Call.getNumArgs());
100}
101
102/// \return Bitvector marking non-null attributes.
103llvm::SmallBitVector getNonNullAttrs(const AnyCall &Call) {
104 return getNonNullAttrsImpl(Call, Call.param_size());
105}
106} // end anonymous namespace
107
108void NonNullParamChecker::checkPreCall(const CallEvent &Call,
109 CheckerContext &C) const {
110 if (!Call.getDecl())
111 return;
112
113 llvm::SmallBitVector AttrNonNull = getNonNullAttrs(Call);
114 unsigned NumArgs = Call.getNumArgs();
115
116 ProgramStateRef state = C.getState();
117 ArrayRef<ParmVarDecl *> parms = Call.parameters();
118
119 for (unsigned idx = 0; idx < NumArgs; ++idx) {
120 // For vararg functions, a corresponding parameter decl may not exist.
121 bool HasParam = idx < parms.size();
122
123 // Check if the parameter is a reference. We want to report when reference
124 // to a null pointer is passed as a parameter.
125 bool HasRefTypeParam =
126 HasParam ? parms[idx]->getType()->isReferenceType() : false;
127 bool ExpectedToBeNonNull = AttrNonNull.test(idx);
128
129 if (!ExpectedToBeNonNull && !HasRefTypeParam)
130 continue;
131
132 // If the value is unknown or undefined, we can't perform this check.
133 const Expr *ArgE = Call.getArgExpr(idx);
134 SVal V = Call.getArgSVal(idx);
135 auto DV = V.getAs<DefinedSVal>();
136 if (!DV)
137 continue;
138
139 assert(!HasRefTypeParam || isa<Loc>(*DV));
140
141 // Process the case when the argument is not a location.
142 if (ExpectedToBeNonNull && !isa<Loc>(*DV)) {
143 // If the argument is a union type, we want to handle a potential
144 // transparent_union GCC extension.
145 if (!ArgE)
146 continue;
147
148 QualType T = ArgE->getType();
149 const RecordType *UT = T->getAsUnionType();
150 if (!UT ||
151 !UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>())
152 continue;
153
154 auto CSV = DV->getAs<nonloc::CompoundVal>();
155
156 // FIXME: Handle LazyCompoundVals?
157 if (!CSV)
158 continue;
159
160 V = *(CSV->begin());
161 DV = V.getAs<DefinedSVal>();
162 assert(++CSV->begin() == CSV->end());
163 // FIXME: Handle (some_union){ some_other_union_val }, which turns into
164 // a LazyCompoundVal inside a CompoundVal.
165 if (!isa<Loc>(V))
166 continue;
167
168 // Retrieve the corresponding expression.
169 if (const auto *CE = dyn_cast<CompoundLiteralExpr>(ArgE))
170 if (const auto *IE = dyn_cast<InitListExpr>(CE->getInitializer()))
171 ArgE = dyn_cast<Expr>(*(IE->begin()));
172 }
173
174 ConstraintManager &CM = C.getConstraintManager();
175 ProgramStateRef stateNotNull, stateNull;
176 std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
177
178 // Generate an error node. Check for a null node in case
179 // we cache out.
180 if (stateNull && !stateNotNull) {
181 if (ExplodedNode *errorNode = C.generateErrorNode(stateNull)) {
182
183 std::unique_ptr<BugReport> R;
184 if (ExpectedToBeNonNull)
185 R = genReportNullAttrNonNull(errorNode, ArgE, idx + 1);
186 else if (HasRefTypeParam)
187 R = genReportReferenceToNullPointer(errorNode, ArgE);
188
189 // Highlight the range of the argument that was null.
190 R->addRange(Call.getArgSourceRange(idx));
191
192 // Emit the bug report.
193 C.emitReport(std::move(R));
194 }
195
196 // Always return. Either we cached out or we just emitted an error.
197 return;
198 }
199
200 if (stateNull) {
201 if (ExplodedNode *N = C.generateSink(stateNull, C.getPredecessor())) {
202 ImplicitNullDerefEvent event = {
203 V, false, N, &C.getBugReporter(),
204 /*IsDirectDereference=*/HasRefTypeParam};
205 dispatchEvent(event);
206 }
207 }
208
209 // If a pointer value passed the check we should assume that it is
210 // indeed not null from this point forward.
211 state = stateNotNull;
212 }
213
214 // If we reach here all of the arguments passed the nonnull check.
215 // If 'state' has been updated generated a new node.
216 C.addTransition(state);
217}
218
219/// We want to trust developer annotations and consider all 'nonnull' parameters
220/// as non-null indeed. Each marked parameter will get a corresponding
221/// constraint.
222///
223/// This approach will not only help us to get rid of some false positives, but
224/// remove duplicates and shorten warning traces as well.
225///
226/// \code
227/// void foo(int *x) [[gnu::nonnull]] {
228/// // . . .
229/// *x = 42; // we don't want to consider this as an error...
230/// // . . .
231/// }
232///
233/// foo(nullptr); // ...and report here instead
234/// \endcode
235void NonNullParamChecker::checkBeginFunction(CheckerContext &Context) const {
236 // Planned assumption makes sense only for top-level functions.
237 // Inlined functions will get similar constraints as part of 'checkPreCall'.
238 if (!Context.inTopFrame())
239 return;
240
241 const StackFrame *SF = Context.getStackFrame();
242
243 const Decl *FD = SF->getDecl();
244 // AnyCall helps us here to avoid checking for FunctionDecl and ObjCMethodDecl
245 // separately and aggregates interfaces of these classes.
246 auto AbstractCall = AnyCall::forDecl(FD);
247 if (!AbstractCall)
248 return;
249
250 ProgramStateRef State = Context.getState();
251 llvm::SmallBitVector ParameterNonNullMarks = getNonNullAttrs(*AbstractCall);
252
253 for (const ParmVarDecl *Parameter : AbstractCall->parameters()) {
254 // 1. Check parameter if it is annotated as non-null
255 if (!ParameterNonNullMarks.test(Parameter->getFunctionScopeIndex()))
256 continue;
257
258 // 2. Check that parameter is a pointer.
259 // Nonnull attribute can be applied to non-pointers (by default
260 // __attribute__(nonnull) implies "all parameters").
261 if (!Parameter->getType()->isPointerType())
262 continue;
263
264 Loc ParameterLoc = State->getLValue(Parameter, SF);
265 // We never consider top-level function parameters undefined.
266 auto StoredVal =
267 State->getSVal(ParameterLoc).castAs<DefinedOrUnknownSVal>();
268
269 // 3. Assume that it is indeed non-null
270 if (ProgramStateRef NewState = State->assume(StoredVal, true)) {
271 State = NewState;
272 }
273 }
274
275 Context.addTransition(State);
276}
277
278std::unique_ptr<PathSensitiveBugReport>
279NonNullParamChecker::genReportNullAttrNonNull(const ExplodedNode *ErrorNode,
280 const Expr *ArgE,
281 unsigned IdxOfArg) const {
282 auto R = std::make_unique<PathSensitiveBugReport>(
283 BTAttrNonNull,
284 "Null pointer passed to " + Twine(IdxOfArg) +
285 llvm::getOrdinalSuffix(IdxOfArg) + " parameter expecting 'nonnull'",
286 ErrorNode);
287 if (ArgE)
288 bugreporter::trackExpressionValue(ErrorNode, ArgE, *R);
289
290 return R;
291}
292
293std::unique_ptr<PathSensitiveBugReport>
294NonNullParamChecker::genReportReferenceToNullPointer(
295 const ExplodedNode *ErrorNode, const Expr *ArgE) const {
296 auto R = std::make_unique<PathSensitiveBugReport>(
297 BTNullRefArg, "Forming reference to null pointer", ErrorNode);
298 if (ArgE) {
299 const Expr *ArgEDeref = bugreporter::getDerefExpr(ArgE);
300 if (!ArgEDeref)
301 ArgEDeref = ArgE;
302 bugreporter::trackExpressionValue(ErrorNode, ArgEDeref, *R);
303 }
304 return R;
305}
306
307void ento::registerNonNullParamChecker(CheckerManager &mgr) {
308 mgr.registerChecker<NonNullParamChecker>();
309}
310
311bool ento::shouldRegisterNonNullParamChecker(const CheckerManager &mgr) {
312 return true;
313}
#define V(N, I)
unsigned ParameterIndex
The 0-based index of the parameter/argument.
An instance of this class corresponds to a call.
Definition AnyCall.h:26
static std::optional< AnyCall > forDecl(const Decl *D)
If D is a callable (Objective-C method or a function), return a constructed AnyCall object.
Definition AnyCall.h:134
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
QualType getType() const
Definition Expr.h:144
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
Represents a parameter to a function.
Definition Decl.h:1817
const Decl * getDecl() const
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
Represents an abstract call to a function or method along a particular path.
Definition CallEvent.h:152
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
ProgramStatePair assumeDual(ProgramStateRef State, DefinedSVal Cond)
Returns a pair of states (StTrue, StFalse) where the given condition is assumed to be true or false,...
const Expr * getDerefExpr(const Stmt *S)
Given that expression S represents a pointer that would be dereferenced, try to find a sub-expression...
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.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
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.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
@ Parameter
The parameter type of a method or function.
Definition TypeBase.h:908