ReturnUndefChecker.cpp revision 55fc873017f10f6f566b182b70f6fc22aefa3464
1//== ReturnUndefChecker.cpp -------------------------------------*- 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 file defines ReturnUndefChecker, which is a path-sensitive
11// check which looks for undefined or garbage values being returned to the
12// caller.
13//
14//===----------------------------------------------------------------------===//
15
16#include "ClangSACheckers.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18#include "clang/StaticAnalyzer/Core/Checker.h"
19#include "clang/StaticAnalyzer/Core/CheckerManager.h"
20#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
21#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
22
23using namespace clang;
24using namespace ento;
25
26namespace {
27class ReturnUndefChecker :
28    public Checker< check::PreStmt<ReturnStmt> > {
29  mutable OwningPtr<BuiltinBug> BT;
30public:
31  void checkPreStmt(const ReturnStmt *RS, CheckerContext &C) const;
32};
33}
34
35void ReturnUndefChecker::checkPreStmt(const ReturnStmt *RS,
36                                      CheckerContext &C) const {
37
38  const Expr *RetE = RS->getRetValue();
39  if (!RetE)
40    return;
41
42  if (!C.getState()->getSVal(RetE, C.getLocationContext()).isUndef())
43    return;
44
45  // "return;" is modeled to evaluate to an UndefinedValue. Allow UndefinedValue
46  // to be returned in functions returning void to support the following pattern:
47  // void foo() {
48  //  return;
49  // }
50  // void test() {
51  //   return foo();
52  // }
53  const StackFrameContext *SFC = C.getStackFrame();
54  QualType RT = CallEvent::getDeclaredResultType(SFC->getDecl());
55  if (!RT.isNull() && RT->isSpecificBuiltinType(BuiltinType::Void))
56    return;
57
58  ExplodedNode *N = C.generateSink();
59
60  if (!N)
61    return;
62
63  if (!BT)
64    BT.reset(new BuiltinBug("Garbage return value",
65                            "Undefined or garbage value returned to caller"));
66
67  BugReport *report =
68    new BugReport(*BT, BT->getDescription(), N);
69
70  report->addRange(RetE->getSourceRange());
71  bugreporter::trackNullOrUndefValue(N, RetE, *report);
72
73  C.emitReport(report);
74}
75
76void ento::registerReturnUndefChecker(CheckerManager &mgr) {
77  mgr.registerChecker<ReturnUndefChecker>();
78}
79