blob: 8ca4aabe3e12ca6e31d595c07bc35e3266cad9d5 [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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000022#include "llvm/Support/raw_ostream.h"
Ted Kremenekbc3a0212009-10-30 17:24:47 +000023
24using namespace clang;
Ted Kremenek9ef65372010-12-23 07:20:52 +000025using namespace ento;
Ted Kremenekbc3a0212009-10-30 17:24:47 +000026
Ted Kremenekb4b817d2009-11-11 03:26:34 +000027namespace {
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000028class DereferenceChecker
Argyrios Kyrtzidisec8605f2011-03-01 01:16:21 +000029 : public Checker< check::Location,
Jordan Rose9f3b9d52012-08-02 21:33:42 +000030 check::Bind,
31 EventDispatcher<ImplicitNullDerefEvent> > {
Dylan Noblesmith6f42b622012-02-05 02:12:40 +000032 mutable OwningPtr<BuiltinBug> BT_null;
33 mutable OwningPtr<BuiltinBug> BT_undef;
Ted Kremenek452b84d2010-03-23 01:11:38 +000034
Jordan Rose9f3b9d52012-08-02 21:33:42 +000035 void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C,
36 bool IsBind = false) const;
37
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000038public:
Anna Zaks390909c2011-10-06 00:43:15 +000039 void checkLocation(SVal location, bool isLoad, const Stmt* S,
40 CheckerContext &C) const;
Jordan Rose9f3b9d52012-08-02 21:33:42 +000041 void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +000042
Anna Zaks9bc1e6d2012-09-05 22:31:49 +000043 static void AddDerefSource(raw_ostream &os,
Chris Lattner5f9e2722011-07-23 10:55:15 +000044 SmallVectorImpl<SourceRange> &Ranges,
Ted Kremenek76aadc32012-03-09 01:13:14 +000045 const Expr *Ex, const ProgramState *state,
46 const LocationContext *LCtx,
47 bool loadedFrom = false);
Ted Kremenekb4b817d2009-11-11 03:26:34 +000048};
49} // end anonymous namespace
50
Anna Zaks9bc1e6d2012-09-05 22:31:49 +000051void
Ted Kremenek76aadc32012-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 McCallf6a16482010-12-04 03:47:34 +000058 Ex = Ex->IgnoreParenLValueCasts();
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());
68 }
Ted Kremenek76aadc32012-03-09 01:13:14 +000069 break;
Ted Kremenek646c3c32010-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 }
79 }
80}
81
Jordan Rose9f3b9d52012-08-02 21:33:42 +000082void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
83 CheckerContext &C, bool IsBind) const {
84 // Generate an error node.
85 ExplodedNode *N = C.generateSink(State);
86 if (!N)
87 return;
88
89 // We know that 'location' cannot be non-null. This is what
90 // we call an "explicit" null dereference.
91 if (!BT_null)
92 BT_null.reset(new BuiltinBug("Dereference of null pointer"));
93
94 SmallString<100> buf;
Jordan Rose991bcb42012-09-22 01:24:38 +000095 llvm::raw_svector_ostream os(buf);
96
Jordan Rose9f3b9d52012-08-02 21:33:42 +000097 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
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000104 if (IsBind) {
105 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
106 if (BO->isAssignmentOp())
107 S = BO->getRHS();
108 } else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
109 assert(DS->isSingleDecl() && "We process decls one by one");
110 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
111 if (const Expr *Init = VD->getAnyInitializer())
112 S = Init;
113 }
114 }
115
116 switch (S->getStmtClass()) {
117 case Stmt::ArraySubscriptExprClass: {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000118 os << "Array access";
119 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
Anna Zaks9bc1e6d2012-09-05 22:31:49 +0000120 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
121 State.getPtr(), N->getLocationContext());
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000122 os << " results in a null pointer dereference";
123 break;
124 }
125 case Stmt::UnaryOperatorClass: {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000126 os << "Dereference of null pointer";
127 const UnaryOperator *U = cast<UnaryOperator>(S);
Anna Zaks9bc1e6d2012-09-05 22:31:49 +0000128 AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
129 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000130 break;
131 }
132 case Stmt::MemberExprClass: {
133 const MemberExpr *M = cast<MemberExpr>(S);
Anna Zaks9b925ac2012-09-05 23:41:54 +0000134 if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000135 os << "Access to field '" << M->getMemberNameInfo()
136 << "' results in a dereference of a null pointer";
Anna Zaks9bc1e6d2012-09-05 22:31:49 +0000137 AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
138 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000139 }
140 break;
141 }
142 case Stmt::ObjCIvarRefExprClass: {
143 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
Jordan Rose991bcb42012-09-22 01:24:38 +0000144 os << "Access to instance variable '" << *IV->getDecl()
145 << "' results in a dereference of a null pointer";
146 AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
147 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000148 break;
149 }
150 default:
151 break;
152 }
153
Jordan Rose991bcb42012-09-22 01:24:38 +0000154 os.flush();
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000155 BugReport *report =
156 new BugReport(*BT_null,
157 buf.empty() ? BT_null->getDescription() : buf.str(),
158 N);
159
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000160 bugreporter::trackNullOrUndefValue(N, bugreporter::GetDerefExpr(N), *report);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000161
162 for (SmallVectorImpl<SourceRange>::iterator
163 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
164 report->addRange(*I);
165
Jordan Rose785950e2012-11-02 01:53:40 +0000166 C.emitReport(report);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000167}
168
Anna Zaks390909c2011-10-06 00:43:15 +0000169void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000170 CheckerContext &C) const {
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000171 // Check for dereference of an undefined value.
172 if (l.isUndef()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000173 if (ExplodedNode *N = C.generateSink()) {
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000174 if (!BT_undef)
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000175 BT_undef.reset(new BuiltinBug("Dereference of undefined pointer value"));
Ted Kremenek452b84d2010-03-23 01:11:38 +0000176
Anna Zakse172e8b2011-08-17 23:00:25 +0000177 BugReport *report =
178 new BugReport(*BT_undef, BT_undef->getDescription(), N);
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000179 bugreporter::trackNullOrUndefValue(N, bugreporter::GetDerefExpr(N),
180 *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000181 C.emitReport(report);
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000182 }
183 return;
184 }
Ted Kremenek452b84d2010-03-23 01:11:38 +0000185
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000186 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(l);
Ted Kremenek452b84d2010-03-23 01:11:38 +0000187
188 // Check for null dereferences.
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000189 if (!isa<Loc>(location))
190 return;
Ted Kremenek452b84d2010-03-23 01:11:38 +0000191
Ted Kremenek8bef8232012-01-26 21:29:00 +0000192 ProgramStateRef state = C.getState();
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000193
Ted Kremenek8bef8232012-01-26 21:29:00 +0000194 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000195 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenek452b84d2010-03-23 01:11:38 +0000196
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000197 // The explicit NULL case.
198 if (nullState) {
Ted Kremenek452b84d2010-03-23 01:11:38 +0000199 if (!notNullState) {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000200 reportBug(nullState, S, C);
Ted Kremenek78d722f2009-11-21 01:50:48 +0000201 return;
202 }
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000203
204 // Otherwise, we have the case where the location could either be
205 // null or not-null. Record the error node as an "implicit" null
206 // dereference.
207 if (ExplodedNode *N = C.generateSink(nullState)) {
208 ImplicitNullDerefEvent event = { l, isLoad, N, &C.getBugReporter() };
209 dispatchEvent(event);
Ted Kremenekbc3a0212009-10-30 17:24:47 +0000210 }
211 }
Ted Kremenek452b84d2010-03-23 01:11:38 +0000212
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000213 // From this point forward, we know that the location is not null.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000214 C.addTransition(notNullState);
Ted Kremenekbc3a0212009-10-30 17:24:47 +0000215}
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000216
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000217void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
218 CheckerContext &C) const {
Jordan Rose522f46f2012-08-04 00:25:30 +0000219 // If we're binding to a reference, check if the value is known to be null.
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000220 if (V.isUndef())
221 return;
222
223 const MemRegion *MR = L.getAsRegion();
224 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
225 if (!TVR)
226 return;
227
228 if (!TVR->getValueType()->isReferenceType())
229 return;
230
231 ProgramStateRef State = C.getState();
232
233 ProgramStateRef StNonNull, StNull;
234 llvm::tie(StNonNull, StNull) = State->assume(cast<DefinedOrUnknownSVal>(V));
235
236 if (StNull) {
237 if (!StNonNull) {
238 reportBug(StNull, S, C, /*isBind=*/true);
239 return;
240 }
241
242 // At this point the value could be either null or non-null.
243 // Record this as an "implicit" null dereference.
244 if (ExplodedNode *N = C.generateSink(StNull)) {
245 ImplicitNullDerefEvent event = { V, /*isLoad=*/true, N,
246 &C.getBugReporter() };
247 dispatchEvent(event);
248 }
249 }
250
Jordan Rose522f46f2012-08-04 00:25:30 +0000251 // Unlike a regular null dereference, initializing a reference with a
252 // dereferenced null pointer does not actually cause a runtime exception in
253 // Clang's implementation of references.
254 //
255 // int &r = *p; // safe??
256 // if (p != NULL) return; // uh-oh
257 // r = 5; // trap here
258 //
259 // The standard says this is invalid as soon as we try to create a "null
260 // reference" (there is no such thing), but turning this into an assumption
261 // that 'p' is never null will not match our actual runtime behavior.
262 // So we do not record this assumption, allowing us to warn on the last line
263 // of this example.
264 //
265 // We do need to add a transition because we may have generated a sink for
266 // the "implicit" null dereference.
267 C.addTransition(State, this);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000268}
269
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000270void ento::registerDereferenceChecker(CheckerManager &mgr) {
271 mgr.registerChecker<DereferenceChecker>();
272}