1 //== NullDerefChecker.cpp - Null dereference checker ------------*- C++ -*--==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines NullDerefChecker, a builtin check in ExprEngine that performs
11 // checks for null pointers at loads and stores.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/ExprOpenMP.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
21 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/Support/raw_ostream.h"
26 using namespace clang;
30 class DereferenceChecker
31 : public Checker< check::Location,
33 EventDispatcher<ImplicitNullDerefEvent> > {
34 mutable std::unique_ptr<BuiltinBug> BT_null;
35 mutable std::unique_ptr<BuiltinBug> BT_undef;
37 void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C) const;
40 void checkLocation(SVal location, bool isLoad, const Stmt* S,
41 CheckerContext &C) const;
42 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
44 static void AddDerefSource(raw_ostream &os,
45 SmallVectorImpl<SourceRange> &Ranges,
46 const Expr *Ex, const ProgramState *state,
47 const LocationContext *LCtx,
48 bool loadedFrom = false);
50 } // end anonymous namespace
53 DereferenceChecker::AddDerefSource(raw_ostream &os,
54 SmallVectorImpl<SourceRange> &Ranges,
56 const ProgramState *state,
57 const LocationContext *LCtx,
59 Ex = Ex->IgnoreParenLValueCasts();
60 switch (Ex->getStmtClass()) {
63 case Stmt::DeclRefExprClass: {
64 const DeclRefExpr *DR = cast<DeclRefExpr>(Ex);
65 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
66 os << " (" << (loadedFrom ? "loaded from" : "from")
67 << " variable '" << VD->getName() << "')";
68 Ranges.push_back(DR->getSourceRange());
72 case Stmt::MemberExprClass: {
73 const MemberExpr *ME = cast<MemberExpr>(Ex);
74 os << " (" << (loadedFrom ? "loaded from" : "via")
75 << " field '" << ME->getMemberNameInfo() << "')";
76 SourceLocation L = ME->getMemberLoc();
77 Ranges.push_back(SourceRange(L, L));
80 case Stmt::ObjCIvarRefExprClass: {
81 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(Ex);
82 os << " (" << (loadedFrom ? "loaded from" : "via")
83 << " ivar '" << IV->getDecl()->getName() << "')";
84 SourceLocation L = IV->getLocation();
85 Ranges.push_back(SourceRange(L, L));
91 static const Expr *getDereferenceExpr(const Stmt *S, bool IsBind=false){
92 const Expr *E = nullptr;
94 // Walk through lvalue casts to get the original expression
95 // that syntactically caused the load.
96 if (const Expr *expr = dyn_cast<Expr>(S))
97 E = expr->IgnoreParenLValueCasts();
102 std::tie(VD, Init) = parseAssignment(S);
109 static bool suppressReport(const Expr *E) {
110 // Do not report dereferences on memory in non-default address spaces.
111 return E->getType().getQualifiers().hasAddressSpace();
114 void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
115 CheckerContext &C) const {
116 // Generate an error node.
117 ExplodedNode *N = C.generateErrorNode(State);
121 // We know that 'location' cannot be non-null. This is what
122 // we call an "explicit" null dereference.
124 BT_null.reset(new BuiltinBug(this, "Dereference of null pointer"));
126 SmallString<100> buf;
127 llvm::raw_svector_ostream os(buf);
129 SmallVector<SourceRange, 2> Ranges;
131 switch (S->getStmtClass()) {
132 case Stmt::ArraySubscriptExprClass: {
133 os << "Array access";
134 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
135 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
136 State.get(), N->getLocationContext());
137 os << " results in a null pointer dereference";
140 case Stmt::OMPArraySectionExprClass: {
141 os << "Array access";
142 const OMPArraySectionExpr *AE = cast<OMPArraySectionExpr>(S);
143 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
144 State.get(), N->getLocationContext());
145 os << " results in a null pointer dereference";
148 case Stmt::UnaryOperatorClass: {
149 os << "Dereference of null pointer";
150 const UnaryOperator *U = cast<UnaryOperator>(S);
151 AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
152 State.get(), N->getLocationContext(), true);
155 case Stmt::MemberExprClass: {
156 const MemberExpr *M = cast<MemberExpr>(S);
157 if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
158 os << "Access to field '" << M->getMemberNameInfo()
159 << "' results in a dereference of a null pointer";
160 AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
161 State.get(), N->getLocationContext(), true);
165 case Stmt::ObjCIvarRefExprClass: {
166 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
167 os << "Access to instance variable '" << *IV->getDecl()
168 << "' results in a dereference of a null pointer";
169 AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
170 State.get(), N->getLocationContext(), true);
177 auto report = llvm::make_unique<BugReport>(
178 *BT_null, buf.empty() ? BT_null->getDescription() : StringRef(buf), N);
180 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S), *report);
182 for (SmallVectorImpl<SourceRange>::iterator
183 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
184 report->addRange(*I);
186 C.emitReport(std::move(report));
189 void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
190 CheckerContext &C) const {
191 // Check for dereference of an undefined value.
193 if (ExplodedNode *N = C.generateErrorNode()) {
196 new BuiltinBug(this, "Dereference of undefined pointer value"));
199 llvm::make_unique<BugReport>(*BT_undef, BT_undef->getDescription(), N);
200 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S),
202 C.emitReport(std::move(report));
207 DefinedOrUnknownSVal location = l.castAs<DefinedOrUnknownSVal>();
209 // Check for null dereferences.
210 if (!location.getAs<Loc>())
213 ProgramStateRef state = C.getState();
215 ProgramStateRef notNullState, nullState;
216 std::tie(notNullState, nullState) = state->assume(location);
218 // The explicit NULL case.
221 const Expr *expr = getDereferenceExpr(S);
222 if (!suppressReport(expr)) {
223 reportBug(nullState, expr, C);
228 // Otherwise, we have the case where the location could either be
229 // null or not-null. Record the error node as an "implicit" null
231 if (ExplodedNode *N = C.generateSink(nullState, C.getPredecessor())) {
232 ImplicitNullDerefEvent event = {l, isLoad, N, &C.getBugReporter(),
233 /*IsDirectDereference=*/false};
234 dispatchEvent(event);
238 // From this point forward, we know that the location is not null.
239 C.addTransition(notNullState);
242 void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
243 CheckerContext &C) const {
244 // If we're binding to a reference, check if the value is known to be null.
248 const MemRegion *MR = L.getAsRegion();
249 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
253 if (!TVR->getValueType()->isReferenceType())
256 ProgramStateRef State = C.getState();
258 ProgramStateRef StNonNull, StNull;
259 std::tie(StNonNull, StNull) = State->assume(V.castAs<DefinedOrUnknownSVal>());
263 const Expr *expr = getDereferenceExpr(S, /*IsBind=*/true);
264 if (!suppressReport(expr)) {
265 reportBug(StNull, expr, C);
270 // At this point the value could be either null or non-null.
271 // Record this as an "implicit" null dereference.
272 if (ExplodedNode *N = C.generateSink(StNull, C.getPredecessor())) {
273 ImplicitNullDerefEvent event = {V, /*isLoad=*/true, N,
275 /*IsDirectDereference=*/false};
276 dispatchEvent(event);
280 // Unlike a regular null dereference, initializing a reference with a
281 // dereferenced null pointer does not actually cause a runtime exception in
282 // Clang's implementation of references.
284 // int &r = *p; // safe??
285 // if (p != NULL) return; // uh-oh
286 // r = 5; // trap here
288 // The standard says this is invalid as soon as we try to create a "null
289 // reference" (there is no such thing), but turning this into an assumption
290 // that 'p' is never null will not match our actual runtime behavior.
291 // So we do not record this assumption, allowing us to warn on the last line
294 // We do need to add a transition because we may have generated a sink for
295 // the "implicit" null dereference.
296 C.addTransition(State, this);
299 void ento::registerDereferenceChecker(CheckerManager &mgr) {
300 mgr.registerChecker<DereferenceChecker>();