Skip to content

Fix: eliminate TOCTOU race condition in AutoPurchaserMainTask.Stop()#37

Open
HashidaTKS wants to merge 1 commit intomasterfrom
fix/auto-purchaser-toctou-race-condition
Open

Fix: eliminate TOCTOU race condition in AutoPurchaserMainTask.Stop()#37
HashidaTKS wants to merge 1 commit intomasterfrom
fix/auto-purchaser-toctou-race-condition

Conversation

@HashidaTKS
Copy link
Copy Markdown
Owner

問題点

AutoPurchaserMainTask.Stop() に TOCTOU(Time-of-check-time-of-use)競合状態があった(line 86-91)。

public void Stop()
{
    if (!Running)          // ① CancellationTokenSource != null をチェック
        return;
    CancellationTokenSource.Cancel();  // ② ここで CancellationTokenSource が null になる可能性
}

バックグラウンドタスクの finally ブロックで CancellationTokenSource = null が設定されるため、①と②の間に別スレッドが null を書き込むと NullReferenceException が発生する。

改善内容

  • CancellationTokenSource をローカル変数 cts にキャプチャしてから使用
  • cts?.Cancel() で null 安全に Cancel を呼び出す
  • Running の別途チェックが不要になる

Test plan

  • バックグラウンドタスク実行中に Stop() を呼び出しても NullReferenceException が発生しないことを確認
  • 既に停止済みの状態で Stop() を呼び出しても安全に動作することを確認

🤖 Generated with Claude Code

Stop() checked Running (CancellationTokenSource != null) then called
CancellationTokenSource.Cancel(). The background task sets
CancellationTokenSource = null in its finally block, so between the null
check and .Cancel() another thread could null out the field, causing
NullReferenceException.

Capture the field reference into a local variable first and use the
null-conditional operator (?.) to call Cancel atomically on that snapshot,
eliminating the race window.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant