CA5122 P/Invoke declarations should not be safe critical
Collapse the table of content
Expand the table of content

CA5122 P/Invoke declarations should not be safe critical








Breaking Change


A P/Invoke declaration has been marked with a SecuritySafeCriticalAttribute:

[assembly: AllowPartiallyTrustedCallers]

// ...
public class C
    public static extern bool Beep(int frequency, int duration); // CA5122 – safe critical p/invoke

In this example, C.Beep(...) has been marked as a security safe critical method.

Methods are marked as SecuritySafeCritical when they perform a security sensitive operation, but are also safe to be used by transparent code. One of the fundamental rules of the security transparency model is that transparent code may never directly call native code through a P/Invoke. Therefore, marking a P/Invoke as security safe critical will not enable transparent code to call it, and is misleading for security analysis.

To make a P/Invoke available to transparent code, expose a security safe critical wrapper method for it:

[assembly: AllowPartiallyTrustedCallers

class C
   [DllImport(“kernel32.dll”, EntryPoint=”Beep”)]
   private static extern bool BeepPinvoke(int frequency, int duration); // Security Critical P/Invoke

   public static bool Beep(int frequency, int duration)
      return BeepPInvoke(frequency, duration);

Do not suppress a warning from this rule.

© 2015 Microsoft