簡體   English   中英

Clang Static Analyzer檢查某個函數是否被兩次調用

[英]Clang Static Analyzer check if a function was called twice

我有一個新的自定義檢查器(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);
  }
}

但沒有成功。

我想我需要一個新的映射:鍵=未知(函數的名稱+ ID配置文件)和值TransactionState,但不知道如何創建它。

問題的解釋

您希望在存在兩次調用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時,將其遞減。

完整的例子

稱為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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM