blob: 4fce45bd35e888b4337f663cb2cc22c1d9d91151 [file] [log] [blame]
Zhongxing Xub10a7c22009-11-09 06:52:44 +00001//=== 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
Zhongxing Xub10a7c22009-11-09 06:52:44 +000016#include "GRExprEngineInternalChecks.h"
Benjamin Kramer5e2d2c22010-03-27 21:19:47 +000017#include "clang/Checker/BugReporter/BugType.h"
18#include "clang/Checker/PathSensitive/CheckerVisitor.h"
Zhongxing Xub10a7c22009-11-09 06:52:44 +000019
20using namespace clang;
21
22namespace {
Kovarththanan Rajaratnamba5fb5a2009-11-28 06:07:30 +000023class FixedAddressChecker
Zhongxing Xub10a7c22009-11-09 06:52:44 +000024 : public CheckerVisitor<FixedAddressChecker> {
25 BuiltinBug *BT;
26public:
27 FixedAddressChecker() : BT(0) {}
28 static void *getTag();
29 void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
30};
31}
32
33void *FixedAddressChecker::getTag() {
34 static int x;
35 return &x;
36}
37
38void FixedAddressChecker::PreVisitBinaryOperator(CheckerContext &C,
39 const BinaryOperator *B) {
40 // Using a fixed address is not portable because that address will probably
41 // not be valid in all environments or platforms.
42
43 if (B->getOpcode() != BinaryOperator::Assign)
44 return;
45
46 QualType T = B->getType();
47 if (!T->isPointerType())
48 return;
49
50 const GRState *state = C.getState();
51
Ted Kremenek13976632010-02-08 16:18:51 +000052 SVal RV = state->getSVal(B->getRHS());
Zhongxing Xub10a7c22009-11-09 06:52:44 +000053
54 if (!RV.isConstant() || RV.isZeroConstant())
55 return;
56
Ted Kremenek19d67b52009-11-23 22:22:01 +000057 if (ExplodedNode *N = C.GenerateNode()) {
Zhongxing Xub10a7c22009-11-09 06:52:44 +000058 if (!BT)
59 BT = new BuiltinBug("Use fixed address",
Zhongxing Xudfed7a12009-11-09 07:29:39 +000060 "Using a fixed address is not portable because that "
61 "address will probably not be valid in all "
62 "environments or platforms.");
Benjamin Kramerd02e2322009-11-14 12:08:24 +000063 RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription(), N);
Zhongxing Xub10a7c22009-11-09 06:52:44 +000064 R->addRange(B->getRHS()->getSourceRange());
65 C.EmitReport(R);
66 }
67}
68
69void clang::RegisterFixedAddressChecker(GRExprEngine &Eng) {
70 Eng.registerCheck(new FixedAddressChecker());
71}