C and C++ Binaries


IO.DC : 二重クローズ

要旨

既にクローズされているファイルやソケットを再度クローズしようとしています。

プロパティ

クラス名 Double Close
日本語クラス名 二重クローズ
クラス分類 信頼性 (reliability)
ニーモニック IO.DC
カテゴリー
MisraC2023 MisraC2023:D.4.1 Run-time failures shall be minimized
Misra2012 Misra2012:D.4.1 Run-time failures shall be minimized
CWE CWE:672 Operation on a Resource after Expiration or Release
  CWE:1341 Multiple Releases of Same Resource or Handle
CERT-CPP CERT-CPP:OOP54-CPP Gracefully handle self-copy assignment
JSF++ JSF++:81 The assignment operator shall handle self-assignment correctly.
対応言語 C および C++ で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Double Close"

同じファイルディスクリプタに対し2回 close() (もしくは同等の関数)が呼ばれた場合、クローズされたファイルのディスクリプタを再利用し、予期しない悪い結果を引き起こします。

#include <fcntl.h>
#include <unistd.h>

int double_close(const void *databuf, size_t datasize){
    int mydesc;
    int yourdesc;
    ssize_t s;
    int rv;

    mydesc = open("myfile.txt", O_CREAT|O_RDONLY);
    if (mydesc < 0){return -1;}
    close(mydesc);         

    /* system may recycle the descriptor of the closed file
     * giving yourdesc == mydesc */
    yourdesc = open("yourfile.txt", O_CREAT|O_RDWR);
    if (yourdesc < 0){return -2;}

    /* if yourdesc == mydesc, equivalent to close(yourdesc) */
    close(mydesc);      /* 'Double Close' warning issued here */   

    /* if yourdesc == mydesc, may  fail unexpectedly */
    s = write(yourdesc, databuf, datasize);
    close(yourdesc);
    if (s < 0){return -3;}
    return 0;
}

注釈

同じファイルポインタに対し2回 fclose() (もしくは同等の関数)が呼ばれた場合、ポインタを2回解放したことによる結果と同様のメモリの破壊の可能性を含め、予期しない振る舞いを起こします。

ワーニングを引き起こす関数

CodeSonar ships with library models that allow it to functions such as libc close() and Win32 FlsFree() that close a file or socket. If one of these functions is called on a file or socket that is already closed, a warning will be issued.

If you have created a custom library model for some function f() in terms of one of these existing models, calls to f() will also be capable of triggering Double Close warnings.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。