blob: 152b937bb03f4061f578f5a6b2b544f991adab85 [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
Anna Zaksc9f16fe42016-01-06 00:32:49 +000037 void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C) const;
Jordan Rose9a2eec32012-08-02 21:33:42 +000038
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000039public:
Anna Zaks3e0f4152011-10-06 00:43:15 +000040 void checkLocation(SVal location, bool isLoad, const Stmt* S,
41 CheckerContext &C) const;
Jordan Rose9a2eec32012-08-02 21:33:42 +000042 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +000043
Anna Zaks1e2a0dc2012-09-05 22:31:49 +000044 static void AddDerefSource(raw_ostream &os,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000045 SmallVectorImpl<SourceRange> &Ranges,
Ted Kremenek1e809b42012-03-09 01:13:14 +000046 const Expr *Ex, const ProgramState *state,
47 const LocationContext *LCtx,
48 bool loadedFrom = false);
Ted Kremenek5e1f78a2009-11-11 03:26:34 +000049};
50} // end anonymous namespace
51
Anna Zaks1e2a0dc2012-09-05 22:31:49 +000052void
Ted Kremenek1e809b42012-03-09 01:13:14 +000053DereferenceChecker::AddDerefSource(raw_ostream &os,
54 SmallVectorImpl<SourceRange> &Ranges,
55 const Expr *Ex,
56 const ProgramState *state,
57 const LocationContext *LCtx,
58 bool loadedFrom) {
John McCall34376a62010-12-04 03:47:34 +000059 Ex = Ex->IgnoreParenLValueCasts();
Ted Kremenek731310e2010-10-26 00:06:13 +000060 switch (Ex->getStmtClass()) {
61 default:
Ted Kremenek1e809b42012-03-09 01:13:14 +000062 break;
Ted Kremenek731310e2010-10-26 00:06:13 +000063 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());
69 }
Ted Kremenek1e809b42012-03-09 01:13:14 +000070 break;
Ted Kremenek731310e2010-10-26 00:06:13 +000071 }
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));
78 break;
79 }
Ted Kremenek96250482013-02-24 07:21:01 +000080 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));
86 break;
Ted Kremenek3a0678e2015-09-08 03:50:52 +000087 }
Ted Kremenek731310e2010-10-26 00:06:13 +000088 }
89}
90
Anna Zaksc9f16fe42016-01-06 00:32:49 +000091static const Expr *getDereferenceExpr(const Stmt *S, bool IsBind=false){
92 const Expr *E = nullptr;
93
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();
98
99 if (IsBind) {
100 const VarDecl *VD;
101 const Expr *Init;
102 std::tie(VD, Init) = parseAssignment(S);
103 if (VD && Init)
104 E = Init;
105 }
106 return E;
107}
108
109static bool suppressReport(const Expr *E) {
110 // Do not report dereferences on memory in non-default address spaces.
111 return E->getType().getQualifiers().hasAddressSpace();
112}
113
Jordan Rose9a2eec32012-08-02 21:33:42 +0000114void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
Anna Zaksc9f16fe42016-01-06 00:32:49 +0000115 CheckerContext &C) const {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000116 // Generate an error node.
Devin Coughline39bd402015-09-16 22:03:05 +0000117 ExplodedNode *N = C.generateErrorNode(State);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000118 if (!N)
119 return;
120
121 // We know that 'location' cannot be non-null. This is what
122 // we call an "explicit" null dereference.
123 if (!BT_null)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000124 BT_null.reset(new BuiltinBug(this, "Dereference of null pointer"));
Jordan Rose9a2eec32012-08-02 21:33:42 +0000125
126 SmallString<100> buf;
Jordan Rose1d64a492012-09-22 01:24:38 +0000127 llvm::raw_svector_ostream os(buf);
128
Jordan Rose9a2eec32012-08-02 21:33:42 +0000129 SmallVector<SourceRange, 2> Ranges;
130
Jordan Rose9a2eec32012-08-02 21:33:42 +0000131 switch (S->getStmtClass()) {
132 case Stmt::ArraySubscriptExprClass: {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000133 os << "Array access";
134 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000135 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000136 State.get(), N->getLocationContext());
Jordan Rose9a2eec32012-08-02 21:33:42 +0000137 os << " results in a null pointer dereference";
138 break;
139 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +0000140 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";
146 break;
147 }
Jordan Rose9a2eec32012-08-02 21:33:42 +0000148 case Stmt::UnaryOperatorClass: {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000149 os << "Dereference of null pointer";
150 const UnaryOperator *U = cast<UnaryOperator>(S);
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000151 AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000152 State.get(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000153 break;
154 }
155 case Stmt::MemberExprClass: {
156 const MemberExpr *M = cast<MemberExpr>(S);
Anna Zaks3245e582012-09-05 23:41:54 +0000157 if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
Jordan Rose9a2eec32012-08-02 21:33:42 +0000158 os << "Access to field '" << M->getMemberNameInfo()
159 << "' results in a dereference of a null pointer";
Anna Zaks1e2a0dc2012-09-05 22:31:49 +0000160 AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000161 State.get(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000162 }
163 break;
164 }
165 case Stmt::ObjCIvarRefExprClass: {
166 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
Jordan Rose1d64a492012-09-22 01:24:38 +0000167 os << "Access to instance variable '" << *IV->getDecl()
168 << "' results in a dereference of a null pointer";
169 AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
Alp Tokerf994cef2014-07-05 03:08:06 +0000170 State.get(), N->getLocationContext(), true);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000171 break;
172 }
173 default:
174 break;
175 }
176
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000177 auto report = llvm::make_unique<BugReport>(
178 *BT_null, buf.empty() ? BT_null->getDescription() : StringRef(buf), N);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000179
Jordan Rosec362eda2013-01-26 01:28:19 +0000180 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S), *report);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000181
182 for (SmallVectorImpl<SourceRange>::iterator
183 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
184 report->addRange(*I);
185
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000186 C.emitReport(std::move(report));
Jordan Rose9a2eec32012-08-02 21:33:42 +0000187}
188
Anna Zaks3e0f4152011-10-06 00:43:15 +0000189void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000190 CheckerContext &C) const {
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000191 // Check for dereference of an undefined value.
192 if (l.isUndef()) {
Devin Coughline39bd402015-09-16 22:03:05 +0000193 if (ExplodedNode *N = C.generateErrorNode()) {
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000194 if (!BT_undef)
Alexander Kornienko4aca9b12014-02-11 21:49:21 +0000195 BT_undef.reset(
196 new BuiltinBug(this, "Dereference of undefined pointer value"));
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000197
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000198 auto report =
199 llvm::make_unique<BugReport>(*BT_undef, BT_undef->getDescription(), N);
Jordan Rosec362eda2013-01-26 01:28:19 +0000200 bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S),
Jordan Rosea0f7d352012-08-28 00:50:51 +0000201 *report);
Aaron Ballman8d3a7a52015-06-23 13:15:32 +0000202 C.emitReport(std::move(report));
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000203 }
204 return;
205 }
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000206
David Blaikie2fdacbc2013-02-20 05:52:05 +0000207 DefinedOrUnknownSVal location = l.castAs<DefinedOrUnknownSVal>();
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000208
209 // Check for null dereferences.
David Blaikie2fdacbc2013-02-20 05:52:05 +0000210 if (!location.getAs<Loc>())
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000211 return;
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000212
Ted Kremenek49b1e382012-01-26 21:29:00 +0000213 ProgramStateRef state = C.getState();
Jordan Rose9a2eec32012-08-02 21:33:42 +0000214
Ted Kremenek49b1e382012-01-26 21:29:00 +0000215 ProgramStateRef notNullState, nullState;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000216 std::tie(notNullState, nullState) = state->assume(location);
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000217
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000218 // The explicit NULL case.
219 if (nullState) {
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000220 if (!notNullState) {
Anna Zaksc9f16fe42016-01-06 00:32:49 +0000221 const Expr *expr = getDereferenceExpr(S);
222 if (!suppressReport(expr)) {
223 reportBug(nullState, expr, C);
224 return;
225 }
Ted Kremenek9d6daf22009-11-21 01:50:48 +0000226 }
Jordan Rose9a2eec32012-08-02 21:33:42 +0000227
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
230 // dereference.
Devin Coughline39bd402015-09-16 22:03:05 +0000231 if (ExplodedNode *N = C.generateSink(nullState, C.getPredecessor())) {
Gabor Horvath8d3ad6b2015-08-27 18:49:07 +0000232 ImplicitNullDerefEvent event = {l, isLoad, N, &C.getBugReporter(),
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000233 /*IsDirectDereference=*/true};
Jordan Rose9a2eec32012-08-02 21:33:42 +0000234 dispatchEvent(event);
Ted Kremenekf613e892009-10-30 17:24:47 +0000235 }
236 }
Ted Kremenekbb6f5af2010-03-23 01:11:38 +0000237
Ted Kremenek5e1f78a2009-11-11 03:26:34 +0000238 // From this point forward, we know that the location is not null.
Anna Zaksda4c8d62011-10-26 21:06:34 +0000239 C.addTransition(notNullState);
Ted Kremenekf613e892009-10-30 17:24:47 +0000240}
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000241
Jordan Rose9a2eec32012-08-02 21:33:42 +0000242void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
243 CheckerContext &C) const {
Jordan Rose4aa80e12012-08-04 00:25:30 +0000244 // If we're binding to a reference, check if the value is known to be null.
Jordan Rose9a2eec32012-08-02 21:33:42 +0000245 if (V.isUndef())
246 return;
247
248 const MemRegion *MR = L.getAsRegion();
249 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
250 if (!TVR)
251 return;
252
253 if (!TVR->getValueType()->isReferenceType())
254 return;
255
256 ProgramStateRef State = C.getState();
257
258 ProgramStateRef StNonNull, StNull;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000259 std::tie(StNonNull, StNull) = State->assume(V.castAs<DefinedOrUnknownSVal>());
Jordan Rose9a2eec32012-08-02 21:33:42 +0000260
261 if (StNull) {
262 if (!StNonNull) {
Anna Zaksc9f16fe42016-01-06 00:32:49 +0000263 const Expr *expr = getDereferenceExpr(S, /*IsBind=*/true);
264 if (!suppressReport(expr)) {
265 reportBug(StNull, expr, C);
266 return;
267 }
Jordan Rose9a2eec32012-08-02 21:33:42 +0000268 }
269
270 // At this point the value could be either null or non-null.
271 // Record this as an "implicit" null dereference.
Devin Coughline39bd402015-09-16 22:03:05 +0000272 if (ExplodedNode *N = C.generateSink(StNull, C.getPredecessor())) {
Gabor Horvath8d3ad6b2015-08-27 18:49:07 +0000273 ImplicitNullDerefEvent event = {V, /*isLoad=*/true, N,
274 &C.getBugReporter(),
Anna Zaksad9e7ea2016-01-29 18:43:15 +0000275 /*IsDirectDereference=*/true};
Jordan Rose9a2eec32012-08-02 21:33:42 +0000276 dispatchEvent(event);
277 }
278 }
279
Jordan Rose4aa80e12012-08-04 00:25:30 +0000280 // 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.
283 //
284 // int &r = *p; // safe??
285 // if (p != NULL) return; // uh-oh
286 // r = 5; // trap here
287 //
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
292 // of this example.
293 //
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);
Jordan Rose9a2eec32012-08-02 21:33:42 +0000297}
298
Argyrios Kyrtzidis2c49ec72011-02-28 17:36:18 +0000299void ento::registerDereferenceChecker(CheckerManager &mgr) {
300 mgr.registerChecker<DereferenceChecker>();
301}