CA2139:透明方法不能使用 HandleProcessCorruptingExceptions 屬性

型別名稱

TransparentMethodsMustNotHandleProcessCorruptingExceptions

CheckId

CA2139

分類

Microsoft.Security

中斷變更

中斷

原因

透明方法會標記 HandleProcessCorruptedStateExceptionsAttribute 屬性。

規則描述

此規則會引發任何透明的方法,並且嘗試使用 HandleProcessCorruptedStateExceptionsAttribute 屬性處理損毀例外狀況的處理序。損毀例外狀況的處理序是 AccessViolationException 這類例外狀況的 CLR 版本 4.0 例外狀況分類。HandleProcessCorruptedStateExceptionsAttribute 屬性只能供安全性關鍵方法使用,若套用至透明方法則會被忽略。若要處理損毀例外狀況的處理序,這個方法必須具備安全性關鍵或安全性安全關鍵。

如何修正違規

若要修正此規則的違規情形,請移除 HandleProcessCorruptedStateExceptionsAttribute 屬性,或在方法標記 SecurityCriticalAttributeSecuritySafeCriticalAttribute 屬性。

隱藏警告的時機

請勿隱藏此規則的警告。

範例

在這個範例中,透明方法會標記 HandleProcessCorruptedStateExceptionsAttribute 屬性,並且會使該規則失敗。方法也應該標記 SecurityCriticalAttributeSecuritySafeCriticalAttribute 屬性。

using System;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
using System.Security;

namespace TransparencyWarningsDemo
{

    public class HandleProcessCorruptedStateExceptionClass
    {
        [DllImport("SomeModule.dll")]
        private static extern void NativeCode();

        // CA2139 violation - transparent method attempting to handle a process corrupting exception
        [HandleProcessCorruptedStateExceptions]
        public void HandleCorruptingExceptions()
        {
            try
            {
                NativeCode();
            }
            catch (AccessViolationException) { }
        }
    }

}