FixedAddressChecker.cpp revision 9b663716449b618ba0390b1dbebc54fa8e971124
1//=== FixedAddressChecker.cpp - Fixed address usage 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 files defines FixedAddressChecker, a builtin checker that checks for
11// assignment of a fixed address to a pointer.
12// This check corresponds to CWE-587.
13//
14//===----------------------------------------------------------------------===//
15
16#include "InternalChecks.h"
17#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
18#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerVisitor.h"
19
20using namespace clang;
21using namespace ento;
22
23namespace {
24class FixedAddressChecker
25  : public CheckerVisitor<FixedAddressChecker> {
26  BuiltinBug *BT;
27public:
28  FixedAddressChecker() : BT(0) {}
29  static void *getTag();
30  void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
31};
32}
33
34void *FixedAddressChecker::getTag() {
35  static int x;
36  return &x;
37}
38
39void FixedAddressChecker::PreVisitBinaryOperator(CheckerContext &C,
40                                                 const BinaryOperator *B) {
41  // Using a fixed address is not portable because that address will probably
42  // not be valid in all environments or platforms.
43
44  if (B->getOpcode() != BO_Assign)
45    return;
46
47  QualType T = B->getType();
48  if (!T->isPointerType())
49    return;
50
51  const GRState *state = C.getState();
52
53  SVal RV = state->getSVal(B->getRHS());
54
55  if (!RV.isConstant() || RV.isZeroConstant())
56    return;
57
58  if (ExplodedNode *N = C.generateNode()) {
59    if (!BT)
60      BT = new BuiltinBug("Use fixed address",
61                          "Using a fixed address is not portable because that "
62                          "address will probably not be valid in all "
63                          "environments or platforms.");
64    RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription(), N);
65    R->addRange(B->getRHS()->getSourceRange());
66    C.EmitReport(R);
67  }
68}
69
70void ento::RegisterFixedAddressChecker(ExprEngine &Eng) {
71  Eng.registerCheck(new FixedAddressChecker());
72}
73