blob: a0022541f98ee366e0bb9687eb99f285b3b0a488 [file] [log] [blame]
Ted Kremenekbc3a0212009-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 Kyrtzidisd2592a32010-12-22 18:53:44 +000010// This defines NullDerefChecker, a builtin check in ExprEngine that performs
Ted Kremenekbc3a0212009-10-30 17:24:47 +000011// checks for null pointers at loads and stores.
12//
13//===----------------------------------------------------------------------===//
14
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000015#include "ClangSACheckers.h"
Benjamin Kramerc35fb7d2012-01-28 12:06:22 +000016#include "clang/AST/ExprObjC.h"
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000017#include "clang/StaticAnalyzer/Core/Checker.h"
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000018#include "clang/StaticAnalyzer/Core/CheckerManager.h"
19#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
Ted Kremenek9b663712011-02-10 01:03:03 +000020#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000021#include "llvm/ADT/SmallString.h"
Ted Kremenekbc3a0212009-10-30 17:24:47 +000022
23using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000024using namespace ento;
Ted Kremenekbc3a0212009-10-30 17:24:47 +000025
Ted Kremenekb4b817d2009-11-11 03:26:34 +000026namespace {
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000027class DereferenceChecker
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000028 : public Checker< check::Location,
Jordan Rose9f3b9d52012-08-02 21:33:42 +000029 check::Bind,
30 EventDispatcher<ImplicitNullDerefEvent> > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000031 mutable OwningPtr<BuiltinBug> BT_null;
32 mutable OwningPtr<BuiltinBug> BT_undef;
Ted Kremenek452b84d2010-03-23 01:11:38 +000033
Jordan Rose9f3b9d52012-08-02 21:33:42 +000034 void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C,
35 bool IsBind = false) const;
36
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000037public:
Anna Zaks390909c2011-10-06 00:43:15 +000038 void checkLocation(SVal location, bool isLoad, const Stmt* S,
39 CheckerContext &C) const;
Jordan Rose9f3b9d52012-08-02 21:33:42 +000040 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000041
Ted Kremenek76aadc32012-03-09 01:13:14 +000042 static const MemRegion *AddDerefSource(raw_ostream &os,
Chris Lattner5f9e2722011-07-23 10:55:15 +000043 SmallVectorImpl<SourceRange> &Ranges,
Ted Kremenek76aadc32012-03-09 01:13:14 +000044 const Expr *Ex, const ProgramState *state,
45 const LocationContext *LCtx,
46 bool loadedFrom = false);
Ted Kremenekb4b817d2009-11-11 03:26:34 +000047};
48} // end anonymous namespace
49
Ted Kremenek76aadc32012-03-09 01:13:14 +000050const MemRegion *
51DereferenceChecker::AddDerefSource(raw_ostream &os,
52 SmallVectorImpl<SourceRange> &Ranges,
53 const Expr *Ex,
54 const ProgramState *state,
55 const LocationContext *LCtx,
56 bool loadedFrom) {
John McCallf6a16482010-12-04 03:47:34 +000057 Ex = Ex->IgnoreParenLValueCasts();
Ted Kremenek76aadc32012-03-09 01:13:14 +000058 const MemRegion *sourceR = 0;
Ted Kremenek646c3c32010-10-26 00:06:13 +000059 switch (Ex->getStmtClass()) {
60 default:
Ted Kremenek76aadc32012-03-09 01:13:14 +000061 break;
Ted Kremenek646c3c32010-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());
Ted Kremenek76aadc32012-03-09 01:13:14 +000068 sourceR = state->getLValue(VD, LCtx).getAsRegion();
Ted Kremenek646c3c32010-10-26 00:06:13 +000069 }
Ted Kremenek76aadc32012-03-09 01:13:14 +000070 break;
Ted Kremenek646c3c32010-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 }
80 }
Ted Kremenek76aadc32012-03-09 01:13:14 +000081 return sourceR;
Ted Kremenek646c3c32010-10-26 00:06:13 +000082}
83
Jordan Rose9f3b9d52012-08-02 21:33:42 +000084void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
85 CheckerContext &C, bool IsBind) const {
86 // Generate an error node.
87 ExplodedNode *N = C.generateSink(State);
88 if (!N)
89 return;
90
91 // We know that 'location' cannot be non-null. This is what
92 // we call an "explicit" null dereference.
93 if (!BT_null)
94 BT_null.reset(new BuiltinBug("Dereference of null pointer"));
95
96 SmallString<100> buf;
97 SmallVector<SourceRange, 2> Ranges;
98
99 // Walk through lvalue casts to get the original expression
100 // that syntactically caused the load.
101 if (const Expr *expr = dyn_cast<Expr>(S))
102 S = expr->IgnoreParenLValueCasts();
103
104 const MemRegion *sourceR = 0;
105
106 if (IsBind) {
107 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
108 if (BO->isAssignmentOp())
109 S = BO->getRHS();
110 } else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
111 assert(DS->isSingleDecl() && "We process decls one by one");
112 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
113 if (const Expr *Init = VD->getAnyInitializer())
114 S = Init;
115 }
116 }
117
118 switch (S->getStmtClass()) {
119 case Stmt::ArraySubscriptExprClass: {
120 llvm::raw_svector_ostream os(buf);
121 os << "Array access";
122 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
123 sourceR = AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
124 State.getPtr(), N->getLocationContext());
125 os << " results in a null pointer dereference";
126 break;
127 }
128 case Stmt::UnaryOperatorClass: {
129 llvm::raw_svector_ostream os(buf);
130 os << "Dereference of null pointer";
131 const UnaryOperator *U = cast<UnaryOperator>(S);
132 sourceR = AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
133 State.getPtr(), N->getLocationContext(), true);
134 break;
135 }
136 case Stmt::MemberExprClass: {
137 const MemberExpr *M = cast<MemberExpr>(S);
138 if (M->isArrow()) {
139 llvm::raw_svector_ostream os(buf);
140 os << "Access to field '" << M->getMemberNameInfo()
141 << "' results in a dereference of a null pointer";
142 sourceR = AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
143 State.getPtr(), N->getLocationContext(), true);
144 }
145 break;
146 }
147 case Stmt::ObjCIvarRefExprClass: {
148 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
149 if (const DeclRefExpr *DR =
150 dyn_cast<DeclRefExpr>(IV->getBase()->IgnoreParenCasts())) {
151 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
152 llvm::raw_svector_ostream os(buf);
153 os << "Instance variable access (via '" << VD->getName()
154 << "') results in a null pointer dereference";
155 }
156 }
157 Ranges.push_back(IV->getSourceRange());
158 break;
159 }
160 default:
161 break;
162 }
163
164 BugReport *report =
165 new BugReport(*BT_null,
166 buf.empty() ? BT_null->getDescription() : buf.str(),
167 N);
168
169 report->addVisitor(
170 bugreporter::getTrackNullOrUndefValueVisitor(N,
171 bugreporter::GetDerefExpr(N),
172 report));
173
174 for (SmallVectorImpl<SourceRange>::iterator
175 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
176 report->addRange(*I);
177
178 if (sourceR) {
179 report->markInteresting(sourceR);
180 report->markInteresting(State->getRawSVal(loc::MemRegionVal(sourceR)));
181 }
182
183 C.EmitReport(report);
184}
185
Anna Zaks390909c2011-10-06 00:43:15 +0000186void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000187 CheckerContext &C) const {
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000188 // Check for dereference of an undefined value.
189 if (l.isUndef()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000190 if (ExplodedNode *N = C.generateSink()) {
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000191 if (!BT_undef)
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000192 BT_undef.reset(new BuiltinBug("Dereference of undefined pointer value"));
Ted Kremenek452b84d2010-03-23 01:11:38 +0000193
Anna Zakse172e8b2011-08-17 23:00:25 +0000194 BugReport *report =
195 new BugReport(*BT_undef, BT_undef->getDescription(), N);
Anna Zaks50bbc162011-08-19 22:33:38 +0000196 report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
Ted Kremenek76aadc32012-03-09 01:13:14 +0000197 bugreporter::GetDerefExpr(N), report));
Ted Kremeneked7948b2012-05-31 06:03:17 +0000198 report->disablePathPruning();
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000199 C.EmitReport(report);
200 }
201 return;
202 }
Ted Kremenek452b84d2010-03-23 01:11:38 +0000203
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000204 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(l);
Ted Kremenek452b84d2010-03-23 01:11:38 +0000205
206 // Check for null dereferences.
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000207 if (!isa<Loc>(location))
208 return;
Ted Kremenek452b84d2010-03-23 01:11:38 +0000209
Ted Kremenek8bef8232012-01-26 21:29:00 +0000210 ProgramStateRef state = C.getState();
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000211
Ted Kremenek8bef8232012-01-26 21:29:00 +0000212 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000213 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenek452b84d2010-03-23 01:11:38 +0000214
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000215 // The explicit NULL case.
216 if (nullState) {
Ted Kremenek452b84d2010-03-23 01:11:38 +0000217 if (!notNullState) {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000218 reportBug(nullState, S, C);
Ted Kremenek78d722f2009-11-21 01:50:48 +0000219 return;
220 }
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000221
222 // Otherwise, we have the case where the location could either be
223 // null or not-null. Record the error node as an "implicit" null
224 // dereference.
225 if (ExplodedNode *N = C.generateSink(nullState)) {
226 ImplicitNullDerefEvent event = { l, isLoad, N, &C.getBugReporter() };
227 dispatchEvent(event);
Ted Kremenekbc3a0212009-10-30 17:24:47 +0000228 }
229 }
Ted Kremenek452b84d2010-03-23 01:11:38 +0000230
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000231 // From this point forward, we know that the location is not null.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000232 C.addTransition(notNullState);
Ted Kremenekbc3a0212009-10-30 17:24:47 +0000233}
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000234
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000235void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
236 CheckerContext &C) const {
237 // If we're binding to a reference, check if the value is potentially null.
238 if (V.isUndef())
239 return;
240
241 const MemRegion *MR = L.getAsRegion();
242 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
243 if (!TVR)
244 return;
245
246 if (!TVR->getValueType()->isReferenceType())
247 return;
248
249 ProgramStateRef State = C.getState();
250
251 ProgramStateRef StNonNull, StNull;
252 llvm::tie(StNonNull, StNull) = State->assume(cast<DefinedOrUnknownSVal>(V));
253
254 if (StNull) {
255 if (!StNonNull) {
256 reportBug(StNull, S, C, /*isBind=*/true);
257 return;
258 }
259
260 // At this point the value could be either null or non-null.
261 // Record this as an "implicit" null dereference.
262 if (ExplodedNode *N = C.generateSink(StNull)) {
263 ImplicitNullDerefEvent event = { V, /*isLoad=*/true, N,
264 &C.getBugReporter() };
265 dispatchEvent(event);
266 }
267 }
268
269 // From here on out, assume the value is non-null.
270 C.addTransition(StNonNull);
271}
272
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000273void ento::registerDereferenceChecker(CheckerManager &mgr) {
274 mgr.registerChecker<DereferenceChecker>();
275}