blob: 3ace4be448047ac2368c2086011b865d862ae22f [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
Anna Zaks9bc1e6d2012-09-05 22:31:49 +000042 static void 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
Anna Zaks9bc1e6d2012-09-05 22:31:49 +000050void
Ted Kremenek76aadc32012-03-09 01:13:14 +000051DereferenceChecker::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 Kremenek646c3c32010-10-26 00:06:13 +000058 switch (Ex->getStmtClass()) {
59 default:
Ted Kremenek76aadc32012-03-09 01:13:14 +000060 break;
Ted Kremenek646c3c32010-10-26 00:06:13 +000061 case Stmt::DeclRefExprClass: {
62 const DeclRefExpr *DR = cast<DeclRefExpr>(Ex);
63 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
64 os << " (" << (loadedFrom ? "loaded from" : "from")
65 << " variable '" << VD->getName() << "')";
66 Ranges.push_back(DR->getSourceRange());
67 }
Ted Kremenek76aadc32012-03-09 01:13:14 +000068 break;
Ted Kremenek646c3c32010-10-26 00:06:13 +000069 }
70 case Stmt::MemberExprClass: {
71 const MemberExpr *ME = cast<MemberExpr>(Ex);
72 os << " (" << (loadedFrom ? "loaded from" : "via")
73 << " field '" << ME->getMemberNameInfo() << "')";
74 SourceLocation L = ME->getMemberLoc();
75 Ranges.push_back(SourceRange(L, L));
76 break;
77 }
78 }
79}
80
Jordan Rose9f3b9d52012-08-02 21:33:42 +000081void DereferenceChecker::reportBug(ProgramStateRef State, const Stmt *S,
82 CheckerContext &C, bool IsBind) const {
83 // Generate an error node.
84 ExplodedNode *N = C.generateSink(State);
85 if (!N)
86 return;
87
88 // We know that 'location' cannot be non-null. This is what
89 // we call an "explicit" null dereference.
90 if (!BT_null)
91 BT_null.reset(new BuiltinBug("Dereference of null pointer"));
92
93 SmallString<100> buf;
Jordan Rose991bcb42012-09-22 01:24:38 +000094 llvm::raw_svector_ostream os(buf);
95
Jordan Rose9f3b9d52012-08-02 21:33:42 +000096 SmallVector<SourceRange, 2> Ranges;
97
98 // Walk through lvalue casts to get the original expression
99 // that syntactically caused the load.
100 if (const Expr *expr = dyn_cast<Expr>(S))
101 S = expr->IgnoreParenLValueCasts();
102
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000103 if (IsBind) {
104 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
105 if (BO->isAssignmentOp())
106 S = BO->getRHS();
107 } else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
108 assert(DS->isSingleDecl() && "We process decls one by one");
109 if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
110 if (const Expr *Init = VD->getAnyInitializer())
111 S = Init;
112 }
113 }
114
115 switch (S->getStmtClass()) {
116 case Stmt::ArraySubscriptExprClass: {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000117 os << "Array access";
118 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
Anna Zaks9bc1e6d2012-09-05 22:31:49 +0000119 AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
120 State.getPtr(), N->getLocationContext());
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000121 os << " results in a null pointer dereference";
122 break;
123 }
124 case Stmt::UnaryOperatorClass: {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000125 os << "Dereference of null pointer";
126 const UnaryOperator *U = cast<UnaryOperator>(S);
Anna Zaks9bc1e6d2012-09-05 22:31:49 +0000127 AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
128 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000129 break;
130 }
131 case Stmt::MemberExprClass: {
132 const MemberExpr *M = cast<MemberExpr>(S);
Anna Zaks9b925ac2012-09-05 23:41:54 +0000133 if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000134 os << "Access to field '" << M->getMemberNameInfo()
135 << "' results in a dereference of a null pointer";
Anna Zaks9bc1e6d2012-09-05 22:31:49 +0000136 AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
137 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000138 }
139 break;
140 }
141 case Stmt::ObjCIvarRefExprClass: {
142 const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
Jordan Rose991bcb42012-09-22 01:24:38 +0000143 os << "Access to instance variable '" << *IV->getDecl()
144 << "' results in a dereference of a null pointer";
145 AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
146 State.getPtr(), N->getLocationContext(), true);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000147 break;
148 }
149 default:
150 break;
151 }
152
Jordan Rose991bcb42012-09-22 01:24:38 +0000153 os.flush();
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000154 BugReport *report =
155 new BugReport(*BT_null,
156 buf.empty() ? BT_null->getDescription() : buf.str(),
157 N);
158
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000159 bugreporter::trackNullOrUndefValue(N, bugreporter::GetDerefExpr(N), *report);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000160
161 for (SmallVectorImpl<SourceRange>::iterator
162 I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
163 report->addRange(*I);
164
Jordan Rose785950e2012-11-02 01:53:40 +0000165 C.emitReport(report);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000166}
167
Anna Zaks390909c2011-10-06 00:43:15 +0000168void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000169 CheckerContext &C) const {
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000170 // Check for dereference of an undefined value.
171 if (l.isUndef()) {
Ted Kremenekd048c6e2010-12-20 21:19:09 +0000172 if (ExplodedNode *N = C.generateSink()) {
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000173 if (!BT_undef)
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000174 BT_undef.reset(new BuiltinBug("Dereference of undefined pointer value"));
Ted Kremenek452b84d2010-03-23 01:11:38 +0000175
Anna Zakse172e8b2011-08-17 23:00:25 +0000176 BugReport *report =
177 new BugReport(*BT_undef, BT_undef->getDescription(), N);
Jordan Rosea1f81bb2012-08-28 00:50:51 +0000178 bugreporter::trackNullOrUndefValue(N, bugreporter::GetDerefExpr(N),
179 *report);
Jordan Rose785950e2012-11-02 01:53:40 +0000180 C.emitReport(report);
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000181 }
182 return;
183 }
Ted Kremenek452b84d2010-03-23 01:11:38 +0000184
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000185 DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(l);
Ted Kremenek452b84d2010-03-23 01:11:38 +0000186
187 // Check for null dereferences.
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000188 if (!isa<Loc>(location))
189 return;
Ted Kremenek452b84d2010-03-23 01:11:38 +0000190
Ted Kremenek8bef8232012-01-26 21:29:00 +0000191 ProgramStateRef state = C.getState();
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000192
Ted Kremenek8bef8232012-01-26 21:29:00 +0000193 ProgramStateRef notNullState, nullState;
Ted Kremenek28f47b92010-12-01 22:16:56 +0000194 llvm::tie(notNullState, nullState) = state->assume(location);
Ted Kremenek452b84d2010-03-23 01:11:38 +0000195
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000196 // The explicit NULL case.
197 if (nullState) {
Ted Kremenek452b84d2010-03-23 01:11:38 +0000198 if (!notNullState) {
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000199 reportBug(nullState, S, C);
Ted Kremenek78d722f2009-11-21 01:50:48 +0000200 return;
201 }
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000202
203 // Otherwise, we have the case where the location could either be
204 // null or not-null. Record the error node as an "implicit" null
205 // dereference.
206 if (ExplodedNode *N = C.generateSink(nullState)) {
207 ImplicitNullDerefEvent event = { l, isLoad, N, &C.getBugReporter() };
208 dispatchEvent(event);
Ted Kremenekbc3a0212009-10-30 17:24:47 +0000209 }
210 }
Ted Kremenek452b84d2010-03-23 01:11:38 +0000211
Ted Kremenekb4b817d2009-11-11 03:26:34 +0000212 // From this point forward, we know that the location is not null.
Anna Zaks0bd6b112011-10-26 21:06:34 +0000213 C.addTransition(notNullState);
Ted Kremenekbc3a0212009-10-30 17:24:47 +0000214}
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000215
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000216void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
217 CheckerContext &C) const {
Jordan Rose522f46f2012-08-04 00:25:30 +0000218 // If we're binding to a reference, check if the value is known to be null.
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000219 if (V.isUndef())
220 return;
221
222 const MemRegion *MR = L.getAsRegion();
223 const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
224 if (!TVR)
225 return;
226
227 if (!TVR->getValueType()->isReferenceType())
228 return;
229
230 ProgramStateRef State = C.getState();
231
232 ProgramStateRef StNonNull, StNull;
233 llvm::tie(StNonNull, StNull) = State->assume(cast<DefinedOrUnknownSVal>(V));
234
235 if (StNull) {
236 if (!StNonNull) {
237 reportBug(StNull, S, C, /*isBind=*/true);
238 return;
239 }
240
241 // At this point the value could be either null or non-null.
242 // Record this as an "implicit" null dereference.
243 if (ExplodedNode *N = C.generateSink(StNull)) {
244 ImplicitNullDerefEvent event = { V, /*isLoad=*/true, N,
245 &C.getBugReporter() };
246 dispatchEvent(event);
247 }
248 }
249
Jordan Rose522f46f2012-08-04 00:25:30 +0000250 // Unlike a regular null dereference, initializing a reference with a
251 // dereferenced null pointer does not actually cause a runtime exception in
252 // Clang's implementation of references.
253 //
254 // int &r = *p; // safe??
255 // if (p != NULL) return; // uh-oh
256 // r = 5; // trap here
257 //
258 // The standard says this is invalid as soon as we try to create a "null
259 // reference" (there is no such thing), but turning this into an assumption
260 // that 'p' is never null will not match our actual runtime behavior.
261 // So we do not record this assumption, allowing us to warn on the last line
262 // of this example.
263 //
264 // We do need to add a transition because we may have generated a sink for
265 // the "implicit" null dereference.
266 C.addTransition(State, this);
Jordan Rose9f3b9d52012-08-02 21:33:42 +0000267}
268
Argyrios Kyrtzidisb3d74da2011-02-28 17:36:18 +0000269void ento::registerDereferenceChecker(CheckerManager &mgr) {
270 mgr.registerChecker<DereferenceChecker>();
271}