2009-11-09 21:23:31 +08:00
|
|
|
//=== PointerArithChecker.cpp - Pointer arithmetic checker -----*- C++ -*--===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This files defines PointerArithChecker, a builtin checker that checks for
|
|
|
|
// pointer arithmetic on locations other than array elements.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "GRExprEngineInternalChecks.h"
|
2010-03-28 05:19:47 +08:00
|
|
|
#include "clang/Checker/BugReporter/BugType.h"
|
|
|
|
#include "clang/Checker/PathSensitive/CheckerVisitor.h"
|
2009-11-09 21:23:31 +08:00
|
|
|
|
|
|
|
using namespace clang;
|
|
|
|
|
|
|
|
namespace {
|
2009-11-28 14:07:30 +08:00
|
|
|
class PointerArithChecker
|
2009-11-09 21:23:31 +08:00
|
|
|
: public CheckerVisitor<PointerArithChecker> {
|
|
|
|
BuiltinBug *BT;
|
|
|
|
public:
|
|
|
|
PointerArithChecker() : BT(0) {}
|
|
|
|
static void *getTag();
|
|
|
|
void PreVisitBinaryOperator(CheckerContext &C, const BinaryOperator *B);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
void *PointerArithChecker::getTag() {
|
|
|
|
static int x;
|
|
|
|
return &x;
|
|
|
|
}
|
|
|
|
|
|
|
|
void PointerArithChecker::PreVisitBinaryOperator(CheckerContext &C,
|
|
|
|
const BinaryOperator *B) {
|
|
|
|
if (B->getOpcode() != BinaryOperator::Sub &&
|
|
|
|
B->getOpcode() != BinaryOperator::Add)
|
|
|
|
return;
|
|
|
|
|
|
|
|
const GRState *state = C.getState();
|
2010-02-09 00:18:51 +08:00
|
|
|
SVal LV = state->getSVal(B->getLHS());
|
|
|
|
SVal RV = state->getSVal(B->getRHS());
|
2009-11-09 21:23:31 +08:00
|
|
|
|
|
|
|
const MemRegion *LR = LV.getAsRegion();
|
|
|
|
|
|
|
|
if (!LR || !RV.isConstant())
|
|
|
|
return;
|
|
|
|
|
|
|
|
// If pointer arithmetic is done on variables of non-array type, this often
|
|
|
|
// means behavior rely on memory organization, which is dangerous.
|
|
|
|
if (isa<VarRegion>(LR) || isa<CodeTextRegion>(LR) ||
|
|
|
|
isa<CompoundLiteralRegion>(LR)) {
|
|
|
|
|
2009-11-24 06:22:01 +08:00
|
|
|
if (ExplodedNode *N = C.GenerateNode()) {
|
2009-11-09 21:23:31 +08:00
|
|
|
if (!BT)
|
|
|
|
BT = new BuiltinBug("Dangerous pointer arithmetic",
|
|
|
|
"Pointer arithmetic done on non-array variables "
|
|
|
|
"means reliance on memory layout, which is "
|
|
|
|
"dangerous.");
|
2009-11-14 20:08:24 +08:00
|
|
|
RangedBugReport *R = new RangedBugReport(*BT, BT->getDescription(), N);
|
2009-11-09 21:23:31 +08:00
|
|
|
R->addRange(B->getSourceRange());
|
|
|
|
C.EmitReport(R);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void clang::RegisterPointerArithChecker(GRExprEngine &Eng) {
|
|
|
|
Eng.registerCheck(new PointerArithChecker());
|
|
|
|
}
|