blob: 5dd28320f88fa15e8820427c70ae73ff810081fc [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"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000017#include "clang/AST/ExprOpenMP.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000019#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000020#include "clang/StaticAnalyzer/Core/CheckerManager.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Yury Gribov22b41642015-11-06 11:16:31 +000022#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000023#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000024#include "llvm/Support/raw_ostream.h"
Ted Kremenekf613e892009-10-30 17:24:47 +000025
26using namespace clang;
Ted Kremenek98857c92010-12-23 07:20:52 +000027using namespace ento;
Ted Kremenekf613e892009-10-30 17:24:47 +000028
Ted Kremenek5e1f78a2009-11-11 03:26:34 +000029namespace {
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000030class DereferenceChecker
Argyrios Kyrtzidis6a5674f2011-03-01 01:16:21 +000031 : public Checker< check::Location,
Jordan Rose9a2eec32012-08-02 21:33:42 +000032 check::Bind,
33 EventDispatcher<ImplicitNullDerefEvent> > {
Ahmed Charlesb8984322014-03-07 20:03:18 +000034 mutable std::unique_ptr<BuiltinBug> BT_null;
35 mutable std::unique_ptr<BuiltinBug> BT_undef;
Ted Kremenekbb6f5af2010-03-23 01:11:38 +000036
Jordan Rose9a2eec32012-08-02 21:33:42 +000037 void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C,
38 bool IsBind = false) const;
39
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000040public:
Anna Zaks3e0f4152011-10-06 00:43:15 +000041 void checkLocation(SVal location, bool isLoad, const Stmt* S,
42 CheckerContext &C) const;
Jordan Rose9a2eec32012-08-02 21:33:42 +000043 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000044
Anna Zaks1e2a0dc2012-09-05 22:31:49 +000045 static void AddDerefSource(raw_ostream &os,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000046 SmallVectorImpl<SourceRange> &Ranges,
Ted Kremenek1e809b42012-03-09 01:13:14 +000047 const Expr *Ex, const ProgramState *state,
48 const LocationContext *LCtx,
49 bool loadedFrom = false);
Ted Kremenek5e1f78a2009-11-11 03:26:34 +000050};
51} // end anonymous namespace
52
Anna Zaks1e2a0dc2012-09-05 22:31:49 +000053void
Ted Kremenek1e809b42012-03-09 01:13:14 +000054DereferenceChecker::AddDerefSource(raw_ostream &os,
55 SmallVectorImpl<SourceRange> &Ranges,
56 const Expr *Ex,
57 const ProgramState *state,
58 const LocationContext *LCtx,
59 bool loadedFrom) {
John McCall34376a62010-12-04 03:47:34 +000060 Ex = Ex->IgnoreParenLValueCasts();
Ted Kremenek731310e2010-10-26 00:06:13 +000061 switch (Ex->getStmtClass()) {
62 default:
Ted Kremenek1e809b42012-03-09 01:13:14 +000063 break;
Ted Kremenek731310e2010-10-26 00:06:13 +000064 case Stmt::DeclRefExprClass: {
65 const DeclRefExpr *DR = cast<DeclRefExpr>(Ex);
66 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
67 os << " (" << (loadedFrom ? "loaded from" : "from")
68 << " variable '" << VD->getName() << "')";
69 Ranges.push_back(DR->getSourceRange());
70 }
Ted Kremenek1e809b42012-03-09 01:13:14 +000071 break;
Ted Kremenek731310e2010-10-26 00:06:13 +000072 }
73 case Stmt::MemberExprClass: {
74 const MemberExpr *ME = cast<MemberExpr>(Ex);
75 os << " (" << (loadedFrom ? "loaded from" : "via")
76 << " field '" << ME->getMemberNameInfo() << "')";
77 SourceLocation L = ME->getMemberLoc();
78 Ranges.push_back(SourceRange(L, L));
79 break;
80 }
Ted Kremenek96250482013-02-24 07:21:01 +000081 case Stmt::ObjCIvarRefExprClass: {
82 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(Ex);
83 os << " (" << (loadedFrom ? "loaded from" : "via")
84 << " ivar '" << IV->getDecl()->getName() << "')";
85 SourceLocation L = IV->getLocation();
86 Ranges.push_back(SourceRange(L, L));
87 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +000088 }
Ted Kremenek731310e2010-10-26 00:06:13 +000089 }
90}
91
Jordan Rose9a2eec32012-08-02 21:33:42 +000092void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
93 CheckerContext &C, bool IsBind) const {
94 // Generate an error node.
Devin Coughline39bd402015-09-16 22:03:05 +000095 ExplodedNode *N = C.generateErrorNode(State);
Jordan Rose9a2eec32012-08-02 21:33:42 +000096 if (!N)
97 return;
98
99 // We know that 'location' cannot be non-null. This is what
100 // we call an "explicit" null dereference.
101 if (!BT_null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000102 BT_null.reset(new BuiltinBug(this, "Dereference of null pointer"));
Jordan Rose9a2eec32012-08-02 21:33:42 +0000103
104 SmallString<100> buf;
Jordan Rose1d64a492012-09-22 01:24:38 +0000105 llvm::raw_svector_ostream os(buf);
106
Jordan Rose9a2eec32012-08-02 21:33:42 +0000107 SmallVector<SourceRange, 2> Ranges;
108
109 // Walk through lvalue casts to get the original expression
110 // that syntactically caused the load.
111 if (const Expr *expr = dyn_cast<Expr>(S))
112 S = expr->IgnoreParenLValueCasts();
113
Jordan Rose9a2eec32012-08-02 21:33:42 +0000114 if (IsBind) {
Yury Gribov22b41642015-11-06 11:16:31 +0000115 const VarDecl *VD;
116 const Expr *Init;
117 std::tie(VD, Init) = parseAssignment(S);
118 if (VD && Init)
119 S = Init;
Jordan Rose9a2eec32012-08-02 21:33:42 +0000120 }
121
122 switch (S->getStmtClass()) {
123 case Stmt::ArraySubscriptExprClass: {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000124 os << "Array access";
125 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000126 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000127 State.get(), N->getLocationContext());
Jordan Rose9a2eec32012-08-02 21:33:42 +0000128 os << " results in a null pointer dereference";
129 break;
130 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +0000131 case Stmt::OMPArraySectionExprClass: {
132 os << "Array access";
133 const OMPArraySectionExpr *AE = cast<OMPArraySectionExpr>(S);
134 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
135 State.get(), N->getLocationContext());
136 os << " results in a null pointer dereference";
137 break;
138 }
Jordan Rose9a2eec32012-08-02 21:33:42 +0000139 case Stmt::UnaryOperatorClass: {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000140 os << "Dereference of null pointer";
141 const UnaryOperator *U = cast<UnaryOperator>(S);
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000142 AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000143 State.get(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000144 break;
145 }
146 case Stmt::MemberExprClass: {
147 const MemberExpr *M = cast<MemberExpr>(S);
Anna Zaks3245e582012-09-05 23:41:54 +0000148 if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000149 os << "Access to field '" << M->getMemberNameInfo()
150 << "' results in a dereference of a null pointer";
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000151 AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000152 State.get(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000153 }
154 break;
155 }
156 case Stmt::ObjCIvarRefExprClass: {
157 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
Jordan Rose1d64a492012-09-22 01:24:38 +0000158 os << "Access to instance variable '" << *IV->getDecl()
159 << "' results in a dereference of a null pointer";
160 AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000161 State.get(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000162 break;
163 }
164 default:
165 break;
166 }
167
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000168 auto report = llvm::make_unique<BugReport>(
169 *BT_null, buf.empty() ? BT_null->getDescription() : StringRef(buf), N);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000170
Jordan Rosec362eda2013-01-26 01:28:19 +0000171 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S), *report);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000172
173 for (SmallVectorImpl<SourceRange>::iterator
174 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
175 report->addRange(*I);
176
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000177 C.emitReport(std::move(report));
Jordan Rose9a2eec32012-08-02 21:33:42 +0000178}
179
Anna Zaks3e0f4152011-10-06 00:43:15 +0000180void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000181 CheckerContext &C) const {
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000182 // Check for dereference of an undefined value.
183 if (l.isUndef()) {
Devin Coughline39bd402015-09-16 22:03:05 +0000184 if (ExplodedNode *N = C.generateErrorNode()) {
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000185 if (!BT_undef)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000186 BT_undef.reset(
187 new BuiltinBug(this, "Dereference of undefined pointer value"));
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000188
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000189 auto report =
190 llvm::make_unique<BugReport>(*BT_undef, BT_undef->getDescription(), N);
Jordan Rosec362eda2013-01-26 01:28:19 +0000191 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S),
Jordan Rosea0f7d352012-08-28 00:50:51 +0000192 *report);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000193 C.emitReport(std::move(report));
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000194 }
195 return;
196 }
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000197
David Blaikie2fdacbc2013-02-20 05:52:05 +0000198 DefinedOrUnknownSVal location = l.castAs<DefinedOrUnknownSVal>();
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000199
200 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000201 if (!location.getAs<Loc>())
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000202 return;
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000203
Ted Kremenek49b1e382012-01-26 21:29:00 +0000204 ProgramStateRef state = C.getState();
Jordan Rose9a2eec32012-08-02 21:33:42 +0000205
Ted Kremenek49b1e382012-01-26 21:29:00 +0000206 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000207 std::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000208
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000209 // The explicit NULL case.
210 if (nullState) {
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000211 if (!notNullState) {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000212 reportBug(nullState, S, C);
Ted Kremenek9d6daf22009-11-21 01:50:48 +0000213 return;
214 }
Jordan Rose9a2eec32012-08-02 21:33:42 +0000215
216 // Otherwise, we have the case where the location could either be
217 // null or not-null. Record the error node as an "implicit" null
218 // dereference.
Devin Coughline39bd402015-09-16 22:03:05 +0000219 if (ExplodedNode *N = C.generateSink(nullState, C.getPredecessor())) {
Gabor Horvath8d3ad6b2015-08-27 18:49:07 +0000220 ImplicitNullDerefEvent event = {l, isLoad, N, &C.getBugReporter(),
221 /*IsDirectDereference=*/false};
Jordan Rose9a2eec32012-08-02 21:33:42 +0000222 dispatchEvent(event);
Ted Kremenekf613e892009-10-30 17:24:47 +0000223 }
224 }
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000225
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000226 // From this point forward, we know that the location is not null.
Anna Zaksda4c8d62011-10-26 21:06:34 +0000227 C.addTransition(notNullState);
Ted Kremenekf613e892009-10-30 17:24:47 +0000228}
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000229
Jordan Rose9a2eec32012-08-02 21:33:42 +0000230void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
231 CheckerContext &C) const {
Jordan Rose4aa80e12012-08-04 00:25:30 +0000232 // If we're binding to a reference, check if the value is known to be null.
Jordan Rose9a2eec32012-08-02 21:33:42 +0000233 if (V.isUndef())
234 return;
235
236 const MemRegion *MR = L.getAsRegion();
237 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
238 if (!TVR)
239 return;
240
241 if (!TVR->getValueType()->isReferenceType())
242 return;
243
244 ProgramStateRef State = C.getState();
245
246 ProgramStateRef StNonNull, StNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000247 std::tie(StNonNull, StNull) = State->assume(V.castAs<DefinedOrUnknownSVal>());
Jordan Rose9a2eec32012-08-02 21:33:42 +0000248
249 if (StNull) {
250 if (!StNonNull) {
251 reportBug(StNull, S, C, /*isBind=*/true);
252 return;
253 }
254
255 // At this point the value could be either null or non-null.
256 // Record this as an "implicit" null dereference.
Devin Coughline39bd402015-09-16 22:03:05 +0000257 if (ExplodedNode *N = C.generateSink(StNull, C.getPredecessor())) {
Gabor Horvath8d3ad6b2015-08-27 18:49:07 +0000258 ImplicitNullDerefEvent event = {V, /*isLoad=*/true, N,
259 &C.getBugReporter(),
260 /*IsDirectDereference=*/false};
Jordan Rose9a2eec32012-08-02 21:33:42 +0000261 dispatchEvent(event);
262 }
263 }
264
Jordan Rose4aa80e12012-08-04 00:25:30 +0000265 // Unlike a regular null dereference, initializing a reference with a
266 // dereferenced null pointer does not actually cause a runtime exception in
267 // Clang's implementation of references.
268 //
269 // int &r = *p; // safe??
270 // if (p != NULL) return; // uh-oh
271 // r = 5; // trap here
272 //
273 // The standard says this is invalid as soon as we try to create a "null
274 // reference" (there is no such thing), but turning this into an assumption
275 // that 'p' is never null will not match our actual runtime behavior.
276 // So we do not record this assumption, allowing us to warn on the last line
277 // of this example.
278 //
279 // We do need to add a transition because we may have generated a sink for
280 // the "implicit" null dereference.
281 C.addTransition(State, this);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000282}
283
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000284void ento::registerDereferenceChecker(CheckerManager &mgr) {
285 mgr.registerChecker<DereferenceChecker>();
286}