c++ - Clang 静态分析器检查一个函数是否被调用了两次

标签 c++ clang clang-static-analyzer

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

这是交易状态:

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);
  }
}

但没有成功。

我想我需要一张新 map :key = unknown(函数名称 + id 配置文件)和 value TransactionState 但不知道如何创建它。

最佳答案

问题解读

只要存在调用 open_transaction 两次且中间没有 close_transaction 的路径,您就需要报告。

概览

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

虽然教程检查器使用 map ,但在这里我们只需要跟踪单个值。我将使用一个 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 时将其递减。

完整示例

调用的TwiceChecker.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.

关于c++ - Clang 静态分析器检查一个函数是否被调用了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48241792/

相关文章:

c++ - 如何用给定数量的元素初始化 boost::python::list?

c++ - 在 ubuntu 12.04 上设置 Xerces 以与 cmake 和 clang 一起使用

Clang 静态分析器意外的 NULL 指针警告

c++ - 如何使 Clang 静态分析器从命令行输出其工作?

iphone - iPhone 应用程序上的 Clang 静态分析器显示最新版本的错误

c++ - OpenCV 数据类型错误

c++ - 有没有办法在 Dyalog APL 中⎕NA 导入一个 dll 导出的 C++ 类?

gdb - clang 3.1 在 Ubuntu 12.04 上构建的二进制文件无法使用 gdb 进行调试

c++ - 带有MinGW STL的Clang(错误: no member named 'fgetws' in the global namespace)

c++ - 将异常类与主类放在同一个文件中是一种不好的形式吗