Clang Static Analyzer检查函数是否被调用两次

时间:2018-01-13 16:23:11

标签: c++ clang clang-static-analyzer

我有一个新的自定义检查程序(TransactionChecker.cpp)。

这是TransacationState:

struct TransactionState {
private:
  enum Kind { OpenedT, StartedT, FinalizedT, ClosedT } K;
  TransactionState(Kind InK) : K(InK) {}

public:
  bool isOpened() const { return K == OpenedT; }
  bool isClosed() const { return K == ClosedT; }
  bool isStarted() const { return K == StartedT; }
  bool isFinalized() const { return K == FinalizedT; }

  static TransactionState getOpened() { return TransactionState(OpenedT); }
  static TransactionState getClosed() { return TransactionState(ClosedT); }
  static TransactionState getStarted() { return TransactionState(StartedT); }
  static TransactionState getFinalized() {
    return TransactionState(FinalizedT);
  }

  bool operator==(const TransactionState &X) const { return K == X.K; }
  void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); }
};

我的头文件和test.c

void checkDoubleOpen(){
  TRANSACTION *T = open_transaction();
  T = open_transaction();  // expected-warning {{Open a previously open transaction}}


#pragma clang system_header


typedef struct __sTRANSACTION {
  unsigned char *_p;
  int value;
} TRANSACTION;

void startTransaction(TRANSACTION *T,int val);
int finalizeTransaction(TRANSACTION *T);
TRANSACTION* open_transaction();
int close_transaction(TRANSACTION*);

void fakeSystemHeaderCall(TRANSACTION *);

跑完后:

clang -cc1 -analyze -analyzer-checker=alpha.unix.Transaction test.c

我想打印那个警告。

我尝试了REGISTER_MAP_WITH_PROGRAMSTATE(MAPSymbolTS, SymbolRef, TransactionState)

void TransactionChecker::checkPostCall(const CallEvent &Call,
                                       CheckerContext &C) const {
  if (!Call.isGlobalCFunction())
    return;

  if (!Call.isCalled(OpenTran))
    return;

  ProgramStateRef State = C.getState();

  // Get the symbolic value corresponding to the file handle.
  FunctionDecl FileDesc = Call.getReturnValue().getAsSymbol();

  if (!FileDesc)
       return;

 const struct TransactionState *TState = State->get<MAPSymbolTS>(FileDesc);
  if (!TState) {
    // Generate the next transition (an edge in the exploded graph).
    State = State->set<MAPSymbolTS>(FileDesc, TransactionState::getOpened());
    C.addTransition(State);
  } else {
    reportOpenAfterOpen(Call, C);
  }
}

但没有成功。

我想我需要一张新地图:key = unknown(功能&#39; s名称+ id配置文件)和值TransactionState但不知道如何创建它。

1 个答案:

答案 0 :(得分:1)

问题解释

只要有一条路径两次调用open_transaction而没有中间的close_transaction,您要报告。

概述

如评论中所述,有点像教程检查器SimpleStreamChecker.cpp。但是,该检查程序正在跟踪多个对象的状态,而这里的状态是程序的全局状态。这使其更类似于BlockInCriticalSectionChecker.cpp,因此我们将模仿它。

尽管教程检查器使用地图,但这里我们只需要跟踪单个值。我将使用一个unsigned计数器:

REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledTwiceCounter, unsigned)

当我们看到对open_transaction的呼叫时,请增加计数器:

  if (FD->getIdentifier() == II_open) {
    // Update the abstract state to reflect the number of calls.
    unsigned counter = state->get<CalledTwiceCounter>();
    counter++;
    state = state->set<CalledTwiceCounter>(counter);
    C.addTransition(state);

然后如果计数器超过2,则报告缺陷。

类似地,当我们看到close_transaction时将其递减。

完整示例

CalledTwiceChecker.cpp:

// CalledTwiceChecker.cpp
// https://stackoverflow.com/questions/48241792/clang-static-analyzer-check-if-a-function-was-called-twice

#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"

using namespace clang;
using namespace ento;

namespace {

class CalledTwiceChecker : public Checker< eval::Call > {
  mutable IdentifierInfo *II_open, *II_close;
  mutable std::unique_ptr<BuiltinBug> BT_calledTwice;

public:
  CalledTwiceChecker()
    : II_open(nullptr), II_close(nullptr) {}

  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
};

} // end anonymous namespace

// Number of times the function of interest has been called on the
// current path.  Automatically initialized to zero.
//
// Based on similar code in BlockInCriticalSectionChecker.cpp.
REGISTER_TRAIT_WITH_PROGRAMSTATE(CalledTwiceCounter, unsigned)

bool CalledTwiceChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
  const FunctionDecl *FD = C.getCalleeDecl(CE);
  if (!FD || FD->getKind() != Decl::Function) {
    return false;
  }

  ASTContext &Ctx = C.getASTContext();
  if (!II_open) {
    II_open = &Ctx.Idents.get("open_transaction");
  }
  if (!II_close) {
    II_close = &Ctx.Idents.get("close_transaction");
  }

  ProgramStateRef state = C.getState();

  if (FD->getIdentifier() == II_open) {
    // Update the abstract state to reflect the number of calls.
    unsigned counter = state->get<CalledTwiceCounter>();
    counter++;
    state = state->set<CalledTwiceCounter>(counter);
    C.addTransition(state);
    //llvm::errs() << "incremented counter to " << counter << "\n";

    // Note: It is questionable to allow the counter to increase without
    // bound in a static analysis, but the Clang SA engine seems to cap
    // the number of loop iterations at 4, so this is evidently not
    // immediately catastrophic.

    // Possibly report a defect.
    if (counter >= 2) {
      ExplodedNode *N = C.generateErrorNode();
      if (N) {
        if (!BT_calledTwice) {
          BT_calledTwice.reset(new BuiltinBug(
              this, "Called twice", "open_transaction called twice."));
        }
        C.emitReport(llvm::make_unique<BugReport>(
            *BT_calledTwice, BT_calledTwice->getDescription(), N));
      }
    }
    return true;
  }

  if (FD->getIdentifier() == II_close) {
    unsigned counter = state->get<CalledTwiceCounter>();
    if (counter > 0) {
      counter--;
      state = state->set<CalledTwiceCounter>(counter);
      C.addTransition(state);
      return true;
    }
    else {
      return false;
    }
  }

  return false;
}

void ento::registerCalledTwiceChecker(CheckerManager &mgr) {
  mgr.registerChecker<CalledTwiceChecker>();
}

bool ento::shouldRegisterCalledTwiceChecker(const LangOptions &LO) {
  return true;
}

要将其连接到Clang的其余部分,请在以下项中添加条目:

  • clang/include/clang/StaticAnalyzer/Checkers/Checkers.td
  • clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt

示例输入进行测试:

// calltwice.c
// Tests for CalledTwiceChecker.

void open_transaction();
void close_transaction();

void open_once()
{
  open_transaction();        // not reported
}

void open_twice()
{
  open_transaction();
  open_transaction();        // reported
}

void open_one_each_path(int x)
{
  if (x) {
    open_transaction();
  }
  else {
    open_transaction();      // not reported
  }
}

void open_close_open()
{
  open_transaction();
  close_transaction();
  open_transaction();        // not reported
}

void open_close_open_open()
{
  open_transaction();
  close_transaction();
  open_transaction();
  open_transaction();        // reported
}

int something();

void open_loop()
{
  while (something()) {
    open_transaction();      // reported
  }
}

对该输入进行分析:

$ gcc -E -o calltwice.i calltwice.c
$ ~/bld/llvm-project/build/bin/clang -cc1 -analyze -analyzer-checker=alpha.core.CalledTwice calltwice.i
calltwice.c:15:3: warning: open_transaction called twice
  open_transaction();
  ^~~~~~~~~~~~~~~~~~
calltwice.c:40:3: warning: open_transaction called twice
  open_transaction();
  ^~~~~~~~~~~~~~~~~~
calltwice.c:48:5: warning: open_transaction called twice
    open_transaction();
    ^~~~~~~~~~~~~~~~~~
3 warnings generated.