DereferenceChecker.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. #include "ClangSACheckers.h"
  15. #include "clang/AST/ExprObjC.h"
  16. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.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 "llvm/ADT/SmallString.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace clang;
  23. using namespace ento;
  24. namespace {
  25. class DereferenceChecker
  26. : public Checker< check::Location,
  27. check::Bind,
  28. EventDispatcher<ImplicitNullDerefEvent> > {
  29. mutable std::unique_ptr<BuiltinBug> BT_null;
  30. mutable std::unique_ptr<BuiltinBug> BT_undef;
  31. void reportBug(ProgramStateRef State, const Stmt *S, CheckerContext &C,
  32. bool IsBind = false) const;
  33. public:
  34. void checkLocation(SVal location, bool isLoad, const Stmt* S,
  35. CheckerContext &C) const;
  36. void checkBind(SVal L, SVal V, const Stmt *S, CheckerContext &C) const;
  37. static void 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. void
  45. DereferenceChecker::AddDerefSource(raw_ostream &os,
  46. SmallVectorImpl<SourceRange> &Ranges,
  47. const Expr *Ex,
  48. const ProgramState *state,
  49. const LocationContext *LCtx,
  50. bool loadedFrom) {
  51. Ex = Ex->IgnoreParenLValueCasts();
  52. switch (Ex->getStmtClass()) {
  53. default:
  54. break;
  55. case Stmt::DeclRefExprClass: {
  56. const DeclRefExpr *DR = cast<DeclRefExpr>(Ex);
  57. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  58. os << " (" << (loadedFrom ? "loaded from" : "from")
  59. << " variable '" << VD->getName() << "')";
  60. Ranges.push_back(DR->getSourceRange());
  61. }
  62. break;
  63. }
  64. case Stmt::MemberExprClass: {
  65. const MemberExpr *ME = cast<MemberExpr>(Ex);
  66. os << " (" << (loadedFrom ? "loaded from" : "via")
  67. << " field '" << ME->getMemberNameInfo() << "')";
  68. SourceLocation L = ME->getMemberLoc();
  69. Ranges.push_back(SourceRange(L, L));
  70. break;
  71. }
  72. case Stmt::ObjCIvarRefExprClass: {
  73. const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(Ex);
  74. os << " (" << (loadedFrom ? "loaded from" : "via")
  75. << " ivar '" << IV->getDecl()->getName() << "')";
  76. SourceLocation L = IV->getLocation();
  77. Ranges.push_back(SourceRange(L, L));
  78. break;
  79. }
  80. }
  81. }
  82. void 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. // 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(this, "Dereference of null pointer"));
  92. SmallString<100> buf;
  93. llvm::raw_svector_ostream os(buf);
  94. SmallVector<SourceRange, 2> Ranges;
  95. // Walk through lvalue casts to get the original expression
  96. // that syntactically caused the load.
  97. if (const Expr *expr = dyn_cast<Expr>(S))
  98. S = expr->IgnoreParenLValueCasts();
  99. if (IsBind) {
  100. if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
  101. if (BO->isAssignmentOp())
  102. S = BO->getRHS();
  103. } else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  104. assert(DS->isSingleDecl() && "We process decls one by one");
  105. if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl()))
  106. if (const Expr *Init = VD->getAnyInitializer())
  107. S = Init;
  108. }
  109. }
  110. switch (S->getStmtClass()) {
  111. case Stmt::ArraySubscriptExprClass: {
  112. os << "Array access";
  113. const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(S);
  114. AddDerefSource(os, Ranges, AE->getBase()->IgnoreParenCasts(),
  115. State.get(), N->getLocationContext());
  116. os << " results in a null pointer dereference";
  117. break;
  118. }
  119. case Stmt::UnaryOperatorClass: {
  120. os << "Dereference of null pointer";
  121. const UnaryOperator *U = cast<UnaryOperator>(S);
  122. AddDerefSource(os, Ranges, U->getSubExpr()->IgnoreParens(),
  123. State.get(), N->getLocationContext(), true);
  124. break;
  125. }
  126. case Stmt::MemberExprClass: {
  127. const MemberExpr *M = cast<MemberExpr>(S);
  128. if (M->isArrow() || bugreporter::isDeclRefExprToReference(M->getBase())) {
  129. os << "Access to field '" << M->getMemberNameInfo()
  130. << "' results in a dereference of a null pointer";
  131. AddDerefSource(os, Ranges, M->getBase()->IgnoreParenCasts(),
  132. State.get(), N->getLocationContext(), true);
  133. }
  134. break;
  135. }
  136. case Stmt::ObjCIvarRefExprClass: {
  137. const ObjCIvarRefExpr *IV = cast<ObjCIvarRefExpr>(S);
  138. os << "Access to instance variable '" << *IV->getDecl()
  139. << "' results in a dereference of a null pointer";
  140. AddDerefSource(os, Ranges, IV->getBase()->IgnoreParenCasts(),
  141. State.get(), N->getLocationContext(), true);
  142. break;
  143. }
  144. default:
  145. break;
  146. }
  147. os.flush();
  148. auto report = llvm::make_unique<BugReport>(
  149. *BT_null, buf.empty() ? BT_null->getDescription() : StringRef(buf), N);
  150. bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S), *report);
  151. for (SmallVectorImpl<SourceRange>::iterator
  152. I = Ranges.begin(), E = Ranges.end(); I!=E; ++I)
  153. report->addRange(*I);
  154. C.emitReport(std::move(report));
  155. }
  156. void DereferenceChecker::checkLocation(SVal l, bool isLoad, const Stmt* S,
  157. CheckerContext &C) const {
  158. // Check for dereference of an undefined value.
  159. if (l.isUndef()) {
  160. if (ExplodedNode *N = C.generateSink()) {
  161. if (!BT_undef)
  162. BT_undef.reset(
  163. new BuiltinBug(this, "Dereference of undefined pointer value"));
  164. auto report =
  165. llvm::make_unique<BugReport>(*BT_undef, BT_undef->getDescription(), N);
  166. bugreporter::trackNullOrUndefValue(N, bugreporter::getDerefExpr(S),
  167. *report);
  168. C.emitReport(std::move(report));
  169. }
  170. return;
  171. }
  172. DefinedOrUnknownSVal location = l.castAs<DefinedOrUnknownSVal>();
  173. // Check for null dereferences.
  174. if (!location.getAs<Loc>())
  175. return;
  176. ProgramStateRef state = C.getState();
  177. ProgramStateRef notNullState, nullState;
  178. std::tie(notNullState, nullState) = state->assume(location);
  179. // The explicit NULL case.
  180. if (nullState) {
  181. if (!notNullState) {
  182. reportBug(nullState, S, C);
  183. return;
  184. }
  185. // Otherwise, we have the case where the location could either be
  186. // null or not-null. Record the error node as an "implicit" null
  187. // dereference.
  188. if (ExplodedNode *N = C.generateSink(nullState)) {
  189. ImplicitNullDerefEvent event = { l, isLoad, N, &C.getBugReporter() };
  190. dispatchEvent(event);
  191. }
  192. }
  193. // From this point forward, we know that the location is not null.
  194. C.addTransition(notNullState);
  195. }
  196. void DereferenceChecker::checkBind(SVal L, SVal V, const Stmt *S,
  197. CheckerContext &C) const {
  198. // If we're binding to a reference, check if the value is known to be null.
  199. if (V.isUndef())
  200. return;
  201. const MemRegion *MR = L.getAsRegion();
  202. const TypedValueRegion *TVR = dyn_cast_or_null<TypedValueRegion>(MR);
  203. if (!TVR)
  204. return;
  205. if (!TVR->getValueType()->isReferenceType())
  206. return;
  207. ProgramStateRef State = C.getState();
  208. ProgramStateRef StNonNull, StNull;
  209. std::tie(StNonNull, StNull) = State->assume(V.castAs<DefinedOrUnknownSVal>());
  210. if (StNull) {
  211. if (!StNonNull) {
  212. reportBug(StNull, S, C, /*isBind=*/true);
  213. return;
  214. }
  215. // At this point the value could be either null or non-null.
  216. // Record this as an "implicit" null dereference.
  217. if (ExplodedNode *N = C.generateSink(StNull)) {
  218. ImplicitNullDerefEvent event = { V, /*isLoad=*/true, N,
  219. &C.getBugReporter() };
  220. dispatchEvent(event);
  221. }
  222. }
  223. // Unlike a regular null dereference, initializing a reference with a
  224. // dereferenced null pointer does not actually cause a runtime exception in
  225. // Clang's implementation of references.
  226. //
  227. // int &r = *p; // safe??
  228. // if (p != NULL) return; // uh-oh
  229. // r = 5; // trap here
  230. //
  231. // The standard says this is invalid as soon as we try to create a "null
  232. // reference" (there is no such thing), but turning this into an assumption
  233. // that 'p' is never null will not match our actual runtime behavior.
  234. // So we do not record this assumption, allowing us to warn on the last line
  235. // of this example.
  236. //
  237. // We do need to add a transition because we may have generated a sink for
  238. // the "implicit" null dereference.
  239. C.addTransition(State, this);
  240. }
  241. void ento::registerDereferenceChecker(CheckerManager &mgr) {
  242. mgr.registerChecker<DereferenceChecker>();
  243. }