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"
18 #include "clang/Analysis/AnyCall.h"
19 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21 #include "clang/StaticAnalyzer/Core/BugReporter/CommonBugCategories.h"
22 #include "clang/StaticAnalyzer/Core/Checker.h"
23 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
24 #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
25 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
26 #include "llvm/ADT/StringExtras.h"
27
28 using namespace clang;
29 using namespace ento;
30
31 namespace {
32 class NonNullParamChecker
33 : public Checker<check::PreCall, check::BeginFunction,
34 EventDispatcher<ImplicitNullDerefEvent>> {
35 const BugType BTAttrNonNull{
36 this, "Argument with 'nonnull' attribute passed null", "API"};
37 const BugType BTNullRefArg{this, "Dereference of null pointer"};
38
39 public:
40 void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
41 void checkBeginFunction(CheckerContext &C) const;
42
43 std::unique_ptr<PathSensitiveBugReport>
44 genReportNullAttrNonNull(const ExplodedNode *ErrorN, const Expr *ArgE,
45 unsigned IdxOfArg) const;
46 std::unique_ptr<PathSensitiveBugReport>
47 genReportReferenceToNullPointer(const ExplodedNode *ErrorN,
48 const Expr *ArgE) const;
49 };
50
51 template <class CallType>
setBitsAccordingToFunctionAttributes(const CallType & Call,llvm::SmallBitVector & AttrNonNull)52 void setBitsAccordingToFunctionAttributes(const CallType &Call,
53 llvm::SmallBitVector &AttrNonNull) {
54 const Decl *FD = Call.getDecl();
55
56 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
57 if (!NonNull->args_size()) {
58 // Lack of attribute parameters means that all of the parameters are
59 // implicitly marked as non-null.
60 AttrNonNull.set();
61 break;
62 }
63
64 for (const ParamIdx &Idx : NonNull->args()) {
65 // 'nonnull' attribute's parameters are 1-based and should be adjusted to
66 // match actual AST parameter/argument indices.
67 unsigned IdxAST = Idx.getASTIndex();
68 if (IdxAST >= AttrNonNull.size())
69 continue;
70 AttrNonNull.set(IdxAST);
71 }
72 }
73 }
74
75 template <class CallType>
setBitsAccordingToParameterAttributes(const CallType & Call,llvm::SmallBitVector & AttrNonNull)76 void setBitsAccordingToParameterAttributes(const CallType &Call,
77 llvm::SmallBitVector &AttrNonNull) {
78 for (const ParmVarDecl *Parameter : Call.parameters()) {
79 unsigned ParameterIndex = Parameter->getFunctionScopeIndex();
80 if (ParameterIndex == AttrNonNull.size())
81 break;
82
83 if (Parameter->hasAttr<NonNullAttr>())
84 AttrNonNull.set(ParameterIndex);
85 }
86 }
87
88 template <class CallType>
getNonNullAttrsImpl(const CallType & Call,unsigned ExpectedSize)89 llvm::SmallBitVector getNonNullAttrsImpl(const CallType &Call,
90 unsigned ExpectedSize) {
91 llvm::SmallBitVector AttrNonNull(ExpectedSize);
92
93 setBitsAccordingToFunctionAttributes(Call, AttrNonNull);
94 setBitsAccordingToParameterAttributes(Call, AttrNonNull);
95
96 return AttrNonNull;
97 }
98
99 /// \return Bitvector marking non-null attributes.
getNonNullAttrs(const CallEvent & Call)100 llvm::SmallBitVector getNonNullAttrs(const CallEvent &Call) {
101 return getNonNullAttrsImpl(Call, Call.getNumArgs());
102 }
103
104 /// \return Bitvector marking non-null attributes.
getNonNullAttrs(const AnyCall & Call)105 llvm::SmallBitVector getNonNullAttrs(const AnyCall &Call) {
106 return getNonNullAttrsImpl(Call, Call.param_size());
107 }
108 } // end anonymous namespace
109
checkPreCall(const CallEvent & Call,CheckerContext & C) const110 void NonNullParamChecker::checkPreCall(const CallEvent &Call,
111 CheckerContext &C) const {
112 if (!Call.getDecl())
113 return;
114
115 llvm::SmallBitVector AttrNonNull = getNonNullAttrs(Call);
116 unsigned NumArgs = Call.getNumArgs();
117
118 ProgramStateRef state = C.getState();
119 ArrayRef<ParmVarDecl *> parms = Call.parameters();
120
121 for (unsigned idx = 0; idx < NumArgs; ++idx) {
122 // For vararg functions, a corresponding parameter decl may not exist.
123 bool HasParam = idx < parms.size();
124
125 // Check if the parameter is a reference. We want to report when reference
126 // to a null pointer is passed as a parameter.
127 bool HasRefTypeParam =
128 HasParam ? parms[idx]->getType()->isReferenceType() : false;
129 bool ExpectedToBeNonNull = AttrNonNull.test(idx);
130
131 if (!ExpectedToBeNonNull && !HasRefTypeParam)
132 continue;
133
134 // If the value is unknown or undefined, we can't perform this check.
135 const Expr *ArgE = Call.getArgExpr(idx);
136 SVal V = Call.getArgSVal(idx);
137 auto DV = V.getAs<DefinedSVal>();
138 if (!DV)
139 continue;
140
141 assert(!HasRefTypeParam || isa<Loc>(*DV));
142
143 // Process the case when the argument is not a location.
144 if (ExpectedToBeNonNull && !isa<Loc>(*DV)) {
145 // If the argument is a union type, we want to handle a potential
146 // transparent_union GCC extension.
147 if (!ArgE)
148 continue;
149
150 QualType T = ArgE->getType();
151 const RecordType *UT = T->getAsUnionType();
152 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
153 continue;
154
155 auto CSV = DV->getAs<nonloc::CompoundVal>();
156
157 // FIXME: Handle LazyCompoundVals?
158 if (!CSV)
159 continue;
160
161 V = *(CSV->begin());
162 DV = V.getAs<DefinedSVal>();
163 assert(++CSV->begin() == CSV->end());
164 // FIXME: Handle (some_union){ some_other_union_val }, which turns into
165 // a LazyCompoundVal inside a CompoundVal.
166 if (!isa<Loc>(V))
167 continue;
168
169 // Retrieve the corresponding expression.
170 if (const auto *CE = dyn_cast<CompoundLiteralExpr>(ArgE))
171 if (const auto *IE = dyn_cast<InitListExpr>(CE->getInitializer()))
172 ArgE = dyn_cast<Expr>(*(IE->begin()));
173 }
174
175 ConstraintManager &CM = C.getConstraintManager();
176 ProgramStateRef stateNotNull, stateNull;
177 std::tie(stateNotNull, stateNull) = CM.assumeDual(state, *DV);
178
179 // Generate an error node. Check for a null node in case
180 // we cache out.
181 if (stateNull && !stateNotNull) {
182 if (ExplodedNode *errorNode = C.generateErrorNode(stateNull)) {
183
184 std::unique_ptr<BugReport> R;
185 if (ExpectedToBeNonNull)
186 R = genReportNullAttrNonNull(errorNode, ArgE, idx + 1);
187 else if (HasRefTypeParam)
188 R = genReportReferenceToNullPointer(errorNode, ArgE);
189
190 // Highlight the range of the argument that was null.
191 R->addRange(Call.getArgSourceRange(idx));
192
193 // Emit the bug report.
194 C.emitReport(std::move(R));
195 }
196
197 // Always return. Either we cached out or we just emitted an error.
198 return;
199 }
200
201 if (stateNull) {
202 if (ExplodedNode *N = C.generateSink(stateNull, C.getPredecessor())) {
203 ImplicitNullDerefEvent event = {
204 V, false, N, &C.getBugReporter(),
205 /*IsDirectDereference=*/HasRefTypeParam};
206 dispatchEvent(event);
207 }
208 }
209
210 // If a pointer value passed the check we should assume that it is
211 // indeed not null from this point forward.
212 state = stateNotNull;
213 }
214
215 // If we reach here all of the arguments passed the nonnull check.
216 // If 'state' has been updated generated a new node.
217 C.addTransition(state);
218 }
219
220 /// We want to trust developer annotations and consider all 'nonnull' parameters
221 /// as non-null indeed. Each marked parameter will get a corresponding
222 /// constraint.
223 ///
224 /// This approach will not only help us to get rid of some false positives, but
225 /// remove duplicates and shorten warning traces as well.
226 ///
227 /// \code
228 /// void foo(int *x) [[gnu::nonnull]] {
229 /// // . . .
230 /// *x = 42; // we don't want to consider this as an error...
231 /// // . . .
232 /// }
233 ///
234 /// foo(nullptr); // ...and report here instead
235 /// \endcode
checkBeginFunction(CheckerContext & Context) const236 void NonNullParamChecker::checkBeginFunction(CheckerContext &Context) const {
237 // Planned assumption makes sense only for top-level functions.
238 // Inlined functions will get similar constraints as part of 'checkPreCall'.
239 if (!Context.inTopFrame())
240 return;
241
242 const LocationContext *LocContext = Context.getLocationContext();
243
244 const Decl *FD = LocContext->getDecl();
245 // AnyCall helps us here to avoid checking for FunctionDecl and ObjCMethodDecl
246 // separately and aggregates interfaces of these classes.
247 auto AbstractCall = AnyCall::forDecl(FD);
248 if (!AbstractCall)
249 return;
250
251 ProgramStateRef State = Context.getState();
252 llvm::SmallBitVector ParameterNonNullMarks = getNonNullAttrs(*AbstractCall);
253
254 for (const ParmVarDecl *Parameter : AbstractCall->parameters()) {
255 // 1. Check parameter if it is annotated as non-null
256 if (!ParameterNonNullMarks.test(Parameter->getFunctionScopeIndex()))
257 continue;
258
259 // 2. Check that parameter is a pointer.
260 // Nonnull attribute can be applied to non-pointers (by default
261 // __attribute__(nonnull) implies "all parameters").
262 if (!Parameter->getType()->isPointerType())
263 continue;
264
265 Loc ParameterLoc = State->getLValue(Parameter, LocContext);
266 // We never consider top-level function parameters undefined.
267 auto StoredVal =
268 State->getSVal(ParameterLoc).castAs<DefinedOrUnknownSVal>();
269
270 // 3. Assume that it is indeed non-null
271 if (ProgramStateRef NewState = State->assume(StoredVal, true)) {
272 State = NewState;
273 }
274 }
275
276 Context.addTransition(State);
277 }
278
279 std::unique_ptr<PathSensitiveBugReport>
genReportNullAttrNonNull(const ExplodedNode * ErrorNode,const Expr * ArgE,unsigned IdxOfArg) const280 NonNullParamChecker::genReportNullAttrNonNull(const ExplodedNode *ErrorNode,
281 const Expr *ArgE,
282 unsigned IdxOfArg) const {
283 llvm::SmallString<256> SBuf;
284 llvm::raw_svector_ostream OS(SBuf);
285 OS << "Null pointer passed to "
286 << IdxOfArg << llvm::getOrdinalSuffix(IdxOfArg)
287 << " parameter expecting 'nonnull'";
288
289 auto R =
290 std::make_unique<PathSensitiveBugReport>(BTAttrNonNull, SBuf, ErrorNode);
291 if (ArgE)
292 bugreporter::trackExpressionValue(ErrorNode, ArgE, *R);
293
294 return R;
295 }
296
297 std::unique_ptr<PathSensitiveBugReport>
genReportReferenceToNullPointer(const ExplodedNode * ErrorNode,const Expr * ArgE) const298 NonNullParamChecker::genReportReferenceToNullPointer(
299 const ExplodedNode *ErrorNode, const Expr *ArgE) const {
300 auto R = std::make_unique<PathSensitiveBugReport>(
301 BTNullRefArg, "Forming reference to null pointer", ErrorNode);
302 if (ArgE) {
303 const Expr *ArgEDeref = bugreporter::getDerefExpr(ArgE);
304 if (!ArgEDeref)
305 ArgEDeref = ArgE;
306 bugreporter::trackExpressionValue(ErrorNode, ArgEDeref, *R);
307 }
308 return R;
309 }
310
registerNonNullParamChecker(CheckerManager & mgr)311 void ento::registerNonNullParamChecker(CheckerManager &mgr) {
312 mgr.registerChecker<NonNullParamChecker>();
313 }
314
shouldRegisterNonNullParamChecker(const CheckerManager & mgr)315 bool ento::shouldRegisterNonNullParamChecker(const CheckerManager &mgr) {
316 return true;
317 }
318