blob: 6ca7879c12f730ae777661066e659a33f0cfa33b [file] [log] [blame]
Ted Kremenekf613e892009-10-30 17:24:47 +00001//== NullDerefChecker.cpp - Null dereference checker ------------*- C++ -*--==//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Argyrios Kyrtzidis1696f502010-12-22 18:53:44 +000010// This defines NullDerefChecker, a builtin check in ExprEngine that performs
Ted Kremenekf613e892009-10-30 17:24:47 +000011// checks for null pointers at loads and stores.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000015#include "ClangSACheckers.h"
Benjamin Kramer11764ab2012-01-28 12:06:22 +000016#include "clang/AST/ExprObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000018#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000019#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000021#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000022#include "llvm/Support/raw_ostream.h"
Ted Kremenekf613e892009-10-30 17:24:47 +000023
24using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000025using namespace ento;
Ted Kremenekf613e892009-10-30 17:24:47 +000026
Ted Kremenek5e1f78a2009-11-11 03:26:34 +000027namespace {
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000028class DereferenceChecker
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000029 : public Checker< check::Location,
Jordan Rose9a2eec32012-08-02 21:33:42 +000030 check::Bind,
31 EventDispatcher<ImplicitNullDerefEvent> > {
Dylan Noblesmithe2778992012-02-05 02:12:40 +000032 mutable OwningPtr<BuiltinBug> BT_null;
33 mutable OwningPtr<BuiltinBug> BT_undef;
Ted Kremenekbb6f5af2010-03-23 01:11:38 +000034
Jordan Rose9a2eec32012-08-02 21:33:42 +000035 void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C,
36 bool IsBind = false) const;
37
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000038public:
Anna Zaks3e0f4152011-10-06 00:43:15 +000039 void checkLocation(SVal location, bool isLoad, const Stmt* S,
40 CheckerContext &C) const;
Jordan Rose9a2eec32012-08-02 21:33:42 +000041 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000042
Anna Zaks1e2a0dc2012-09-05 22:31:49 +000043 static void AddDerefSource(raw_ostream &os,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000044 SmallVectorImpl<SourceRange> &Ranges,
Ted Kremenek1e809b42012-03-09 01:13:14 +000045 const Expr *Ex, const ProgramState *state,
46 const LocationContext *LCtx,
47 bool loadedFrom = false);
Ted Kremenek5e1f78a2009-11-11 03:26:34 +000048};
49} // end anonymous namespace
50
Anna Zaks1e2a0dc2012-09-05 22:31:49 +000051void
Ted Kremenek1e809b42012-03-09 01:13:14 +000052DereferenceChecker::AddDerefSource(raw_ostream &os,
53 SmallVectorImpl<SourceRange> &Ranges,
54 const Expr *Ex,
55 const ProgramState *state,
56 const LocationContext *LCtx,
57 bool loadedFrom) {
John McCall34376a62010-12-04 03:47:34 +000058 Ex = Ex->IgnoreParenLValueCasts();
Ted Kremenek731310e2010-10-26 00:06:13 +000059 switch (Ex->getStmtClass()) {
60 default:
Ted Kremenek1e809b42012-03-09 01:13:14 +000061 break;
Ted Kremenek731310e2010-10-26 00:06:13 +000062 case Stmt::DeclRefExprClass: {
63 const DeclRefExpr *DR = cast<DeclRefExpr>(Ex);
64 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
65 os << " (" << (loadedFrom ? "loaded from" : "from")
66 << " variable '" << VD->getName() << "')";
67 Ranges.push_back(DR->getSourceRange());
68 }
Ted Kremenek1e809b42012-03-09 01:13:14 +000069 break;
Ted Kremenek731310e2010-10-26 00:06:13 +000070 }
71 case Stmt::MemberExprClass: {
72 const MemberExpr *ME = cast<MemberExpr>(Ex);
73 os << " (" << (loadedFrom ? "loaded from" : "via")
74 << " field '" << ME->getMemberNameInfo() << "')";
75 SourceLocation L = ME->getMemberLoc();
76 Ranges.push_back(SourceRange(L, L));
77 break;
78 }
Ted Kremenek96250482013-02-24 07:21:01 +000079 case Stmt::ObjCIvarRefExprClass: {
80 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(Ex);
81 os << " (" << (loadedFrom ? "loaded from" : "via")
82 << " ivar '" << IV->getDecl()->getName() << "')";
83 SourceLocation L = IV->getLocation();
84 Ranges.push_back(SourceRange(L, L));
85 break;
86 }
Ted Kremenek731310e2010-10-26 00:06:13 +000087 }
88}
89
Jordan Rose9a2eec32012-08-02 21:33:42 +000090void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
91 CheckerContext &C, bool IsBind) const {
92 // Generate an error node.
93 ExplodedNode *N = C.generateSink(State);
94 if (!N)
95 return;
96
97 // We know that 'location' cannot be non-null. This is what
98 // we call an "explicit" null dereference.
99 if (!BT_null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000100 BT_null.reset(new BuiltinBug(this, "Dereference of null pointer"));
Jordan Rose9a2eec32012-08-02 21:33:42 +0000101
102 SmallString<100> buf;
Jordan Rose1d64a492012-09-22 01:24:38 +0000103 llvm::raw_svector_ostream os(buf);
104
Jordan Rose9a2eec32012-08-02 21:33:42 +0000105 SmallVector<SourceRange, 2> Ranges;
106
107 // Walk through lvalue casts to get the original expression
108 // that syntactically caused the load.
109 if (const Expr *expr = dyn_cast<Expr>(S))
110 S = expr->IgnoreParenLValueCasts();
111
Jordan Rose9a2eec32012-08-02 21:33:42 +0000112 if (IsBind) {
113 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
114 if (BO->isAssignmentOp())
115 S = BO->getRHS();
116 } else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
117 assert(DS->isSingleDecl() && "We process decls one by one");
118 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
119 if (const Expr *Init = VD->getAnyInitializer())
120 S = Init;
121 }
122 }
123
124 switch (S->getStmtClass()) {
125 case Stmt::ArraySubscriptExprClass: {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000126 os << "Array access";
127 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000128 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
129 State.getPtr(), N->getLocationContext());
Jordan Rose9a2eec32012-08-02 21:33:42 +0000130 os << " results in a null pointer dereference";
131 break;
132 }
133 case Stmt::UnaryOperatorClass: {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000134 os << "Dereference of null pointer";
135 const UnaryOperator *U = cast<UnaryOperator>(S);
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000136 AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
137 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000138 break;
139 }
140 case Stmt::MemberExprClass: {
141 const MemberExpr *M = cast<MemberExpr>(S);
Anna Zaks3245e582012-09-05 23:41:54 +0000142 if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000143 os << "Access to field '" << M->getMemberNameInfo()
144 << "' results in a dereference of a null pointer";
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000145 AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
146 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000147 }
148 break;
149 }
150 case Stmt::ObjCIvarRefExprClass: {
151 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
Jordan Rose1d64a492012-09-22 01:24:38 +0000152 os << "Access to instance variable '" << *IV->getDecl()
153 << "' results in a dereference of a null pointer";
154 AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
155 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000156 break;
157 }
158 default:
159 break;
160 }
161
Jordan Rose1d64a492012-09-22 01:24:38 +0000162 os.flush();
Jordan Rose9a2eec32012-08-02 21:33:42 +0000163 BugReport *report =
164 new BugReport(*BT_null,
165 buf.empty() ? BT_null->getDescription() : buf.str(),
166 N);
167
Jordan Rosec362eda2013-01-26 01:28:19 +0000168 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S), *report);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000169
170 for (SmallVectorImpl<SourceRange>::iterator
171 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
172 report->addRange(*I);
173
Jordan Rosee10d5a72012-11-02 01:53:40 +0000174 C.emitReport(report);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000175}
176
Anna Zaks3e0f4152011-10-06 00:43:15 +0000177void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000178 CheckerContext &C) const {
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000179 // Check for dereference of an undefined value.
180 if (l.isUndef()) {
Ted Kremenek750b7ac2010-12-20 21:19:09 +0000181 if (ExplodedNode *N = C.generateSink()) {
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000182 if (!BT_undef)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000183 BT_undef.reset(
184 new BuiltinBug(this, "Dereference of undefined pointer value"));
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000185
Anna Zaks3a6bdf82011-08-17 23:00:25 +0000186 BugReport *report =
187 new BugReport(*BT_undef, BT_undef->getDescription(), N);
Jordan Rosec362eda2013-01-26 01:28:19 +0000188 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S),
Jordan Rosea0f7d352012-08-28 00:50:51 +0000189 *report);
Jordan Rosee10d5a72012-11-02 01:53:40 +0000190 C.emitReport(report);
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000191 }
192 return;
193 }
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000194
David Blaikie2fdacbc2013-02-20 05:52:05 +0000195 DefinedOrUnknownSVal location = l.castAs<DefinedOrUnknownSVal>();
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000196
197 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000198 if (!location.getAs<Loc>())
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000199 return;
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000200
Ted Kremenek49b1e382012-01-26 21:29:00 +0000201 ProgramStateRef state = C.getState();
Jordan Rose9a2eec32012-08-02 21:33:42 +0000202
Ted Kremenek49b1e382012-01-26 21:29:00 +0000203 ProgramStateRef notNullState, nullState;
Ted Kremenekc5bea1e2010-12-01 22:16:56 +0000204 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000205
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000206 // The explicit NULL case.
207 if (nullState) {
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000208 if (!notNullState) {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000209 reportBug(nullState, S, C);
Ted Kremenek9d6daf22009-11-21 01:50:48 +0000210 return;
211 }
Jordan Rose9a2eec32012-08-02 21:33:42 +0000212
213 // Otherwise, we have the case where the location could either be
214 // null or not-null. Record the error node as an "implicit" null
215 // dereference.
216 if (ExplodedNode *N = C.generateSink(nullState)) {
217 ImplicitNullDerefEvent event = { l, isLoad, N, &C.getBugReporter() };
218 dispatchEvent(event);
Ted Kremenekf613e892009-10-30 17:24:47 +0000219 }
220 }
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000221
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000222 // From this point forward, we know that the location is not null.
Anna Zaksda4c8d62011-10-26 21:06:34 +0000223 C.addTransition(notNullState);
Ted Kremenekf613e892009-10-30 17:24:47 +0000224}
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000225
Jordan Rose9a2eec32012-08-02 21:33:42 +0000226void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
227 CheckerContext &C) const {
Jordan Rose4aa80e12012-08-04 00:25:30 +0000228 // If we're binding to a reference, check if the value is known to be null.
Jordan Rose9a2eec32012-08-02 21:33:42 +0000229 if (V.isUndef())
230 return;
231
232 const MemRegion *MR = L.getAsRegion();
233 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
234 if (!TVR)
235 return;
236
237 if (!TVR->getValueType()->isReferenceType())
238 return;
239
240 ProgramStateRef State = C.getState();
241
242 ProgramStateRef StNonNull, StNull;
David Blaikie2fdacbc2013-02-20 05:52:05 +0000243 llvm::tie(StNonNull, StNull) =
244 State->assume(V.castAs<DefinedOrUnknownSVal>());
Jordan Rose9a2eec32012-08-02 21:33:42 +0000245
246 if (StNull) {
247 if (!StNonNull) {
248 reportBug(StNull, S, C, /*isBind=*/true);
249 return;
250 }
251
252 // At this point the value could be either null or non-null.
253 // Record this as an "implicit" null dereference.
254 if (ExplodedNode *N = C.generateSink(StNull)) {
255 ImplicitNullDerefEvent event = { V, /*isLoad=*/true, N,
256 &C.getBugReporter() };
257 dispatchEvent(event);
258 }
259 }
260
Jordan Rose4aa80e12012-08-04 00:25:30 +0000261 // Unlike a regular null dereference, initializing a reference with a
262 // dereferenced null pointer does not actually cause a runtime exception in
263 // Clang's implementation of references.
264 //
265 // int &r = *p; // safe??
266 // if (p != NULL) return; // uh-oh
267 // r = 5; // trap here
268 //
269 // The standard says this is invalid as soon as we try to create a "null
270 // reference" (there is no such thing), but turning this into an assumption
271 // that 'p' is never null will not match our actual runtime behavior.
272 // So we do not record this assumption, allowing us to warn on the last line
273 // of this example.
274 //
275 // We do need to add a transition because we may have generated a sink for
276 // the "implicit" null dereference.
277 C.addTransition(State, this);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000278}
279
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000280void ento::registerDereferenceChecker(CheckerManager &mgr) {
281 mgr.registerChecker<DereferenceChecker>();
282}