xref: /llvm-project/clang/lib/StaticAnalyzer/Checkers/DereferenceChecker.cpp (revision 16704bb15b3ac16b517866d8a7f761defe707e2b)
1 //== 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 //
10 // This defines NullDerefChecker, a builtin check in ExprEngine that performs
11 // checks for null pointers at loads and stores.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ClangSACheckers.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/StaticAnalyzer/Core/Checker.h"
18 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
19 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
20 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
21 #include "llvm/ADT/SmallString.h"
22 
23 using namespace clang;
24 using namespace ento;
25 
26 namespace {
27 class DereferenceChecker
28     : public Checker< check::Location,
29                         EventDispatcher<ImplicitNullDerefEvent> > {
30   mutable OwningPtr<BuiltinBug> BT_null;
31   mutable OwningPtr<BuiltinBug> BT_undef;
32 
33 public:
34   void checkLocation(SVal location, bool isLoad, const Stmt* S,
35                      CheckerContext &C) const;
36 
37   static const MemRegion *AddDerefSource(raw_ostream &os,
38                              SmallVectorImpl<SourceRange> &Ranges,
39                              const Expr *Ex, const ProgramState *state,
40                              const LocationContext *LCtx,
41                              bool loadedFrom = false);
42 };
43 } // end anonymous namespace
44 
45 const MemRegion *
46 DereferenceChecker::AddDerefSource(raw_ostream &os,
47                                    SmallVectorImpl<SourceRange> &Ranges,
48                                    const Expr *Ex,
49                                    const ProgramState *state,
50                                    const LocationContext *LCtx,
51                                    bool loadedFrom) {
52   Ex = Ex->IgnoreParenLValueCasts();
53   const MemRegion *sourceR = 0;
54   switch (Ex->getStmtClass()) {
55     default:
56       break;
57     case Stmt::DeclRefExprClass: {
58       const DeclRefExpr *DR = cast<DeclRefExpr>(Ex);
59       if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
60         os << " (" << (loadedFrom ? "loaded from" : "from")
61            << " variable '" <<  VD->getName() << "')";
62         Ranges.push_back(DR->getSourceRange());
63         sourceR = state->getLValue(VD, LCtx).getAsRegion();
64       }
65       break;
66     }
67     case Stmt::MemberExprClass: {
68       const MemberExpr *ME = cast<MemberExpr>(Ex);
69       os << " (" << (loadedFrom ? "loaded from" : "via")
70          << " field '" << ME->getMemberNameInfo() << "')";
71       SourceLocation L = ME->getMemberLoc();
72       Ranges.push_back(SourceRange(L, L));
73       break;
74     }
75   }
76   return sourceR;
77 }
78 
79 void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
80                                        CheckerContext &C) const {
81   // Check for dereference of an undefined value.
82   if (l.isUndef()) {
83     if (ExplodedNode *N = C.generateSink()) {
84       if (!BT_undef)
85         BT_undef.reset(new BuiltinBug("Dereference of undefined pointer value"));
86 
87       BugReport *report =
88         new BugReport(*BT_undef, BT_undef->getDescription(), N);
89       report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
90                                         bugreporter::GetDerefExpr(N), report));
91       report->disablePathPruning();
92       C.EmitReport(report);
93     }
94     return;
95   }
96 
97   DefinedOrUnknownSVal location = cast<DefinedOrUnknownSVal>(l);
98 
99   // Check for null dereferences.
100   if (!isa<Loc>(location))
101     return;
102 
103   ProgramStateRef state = C.getState();
104   const LocationContext *LCtx = C.getLocationContext();
105   ProgramStateRef notNullState, nullState;
106   llvm::tie(notNullState, nullState) = state->assume(location);
107 
108   // The explicit NULL case.
109   if (nullState) {
110     if (!notNullState) {
111       // Generate an error node.
112       ExplodedNode *N = C.generateSink(nullState);
113       if (!N)
114         return;
115 
116       // We know that 'location' cannot be non-null.  This is what
117       // we call an "explicit" null dereference.
118       if (!BT_null)
119         BT_null.reset(new BuiltinBug("Dereference of null pointer"));
120 
121       SmallString<100> buf;
122       SmallVector<SourceRange, 2> Ranges;
123 
124       // Walk through lvalue casts to get the original expression
125       // that syntactically caused the load.
126       if (const Expr *expr = dyn_cast<Expr>(S))
127         S = expr->IgnoreParenLValueCasts();
128 
129       const MemRegion *sourceR = 0;
130 
131       switch (S->getStmtClass()) {
132         case Stmt::ArraySubscriptExprClass: {
133           llvm::raw_svector_ostream os(buf);
134           os << "Array access";
135           const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
136           sourceR =
137             AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
138                            state.getPtr(), LCtx);
139           os << " results in a null pointer dereference";
140           break;
141         }
142         case Stmt::UnaryOperatorClass: {
143           llvm::raw_svector_ostream os(buf);
144           os << "Dereference of null pointer";
145           const UnaryOperator *U = cast<UnaryOperator>(S);
146           sourceR =
147             AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
148                            state.getPtr(), LCtx, true);
149           break;
150         }
151         case Stmt::MemberExprClass: {
152           const MemberExpr *M = cast<MemberExpr>(S);
153           if (M->isArrow()) {
154             llvm::raw_svector_ostream os(buf);
155             os << "Access to field '" << M->getMemberNameInfo()
156                << "' results in a dereference of a null pointer";
157             sourceR =
158               AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
159                              state.getPtr(), LCtx, true);
160           }
161           break;
162         }
163         case Stmt::ObjCIvarRefExprClass: {
164           const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
165           if (const DeclRefExpr *DR =
166               dyn_cast<DeclRefExpr>(IV->getBase()->IgnoreParenCasts())) {
167             if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
168               llvm::raw_svector_ostream os(buf);
169               os << "Instance variable access (via '" << VD->getName()
170                  << "') results in a null pointer dereference";
171             }
172           }
173           Ranges.push_back(IV->getSourceRange());
174           break;
175         }
176         default:
177           break;
178       }
179 
180       BugReport *report =
181         new BugReport(*BT_null,
182                               buf.empty() ? BT_null->getDescription():buf.str(),
183                               N);
184 
185       report->addVisitor(bugreporter::getTrackNullOrUndefValueVisitor(N,
186                                         bugreporter::GetDerefExpr(N), report));
187 
188       for (SmallVectorImpl<SourceRange>::iterator
189             I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
190         report->addRange(*I);
191 
192       if (sourceR) {
193         report->markInteresting(sourceR);
194         report->markInteresting(state->getRawSVal(loc::MemRegionVal(sourceR)));
195       }
196 
197       C.EmitReport(report);
198       return;
199     }
200     else {
201       // Otherwise, we have the case where the location could either be
202       // null or not-null.  Record the error node as an "implicit" null
203       // dereference.
204       if (ExplodedNode *N = C.generateSink(nullState)) {
205         ImplicitNullDerefEvent event = { l, isLoad, N, &C.getBugReporter() };
206         dispatchEvent(event);
207       }
208     }
209   }
210 
211   // From this point forward, we know that the location is not null.
212   C.addTransition(notNullState);
213 }
214 
215 void ento::registerDereferenceChecker(CheckerManager &mgr) {
216   mgr.registerChecker<DereferenceChecker>();
217 }
218