Interop (.NET 1.1) Performance Guidelines - Code Access Security (CAS)

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, and Alex Mackman


Consider Using SuppressUnmanagedCode for Performance-Critical Trusted Scenarios

When designing APIs that do not expose sensitive resources or do not perform security-sensitive operations based on user input, use the SuppressUnmanagedCode attribute to eliminate the stack walk associated with the method call. For example:


  // in C#
  [DllImport("kernel32.dll"), SuppressUnmanagedCodeSecurity]
 public static extern bool Beep(int frequency, int duration);


Use this technique only for performance-critical code in trusted scenarios. Perform thorough code reviews of such APIs to ensure that they are not susceptible to luring attacks.


Consider Using TLBIMP /unsafe for Performance-Critical Trusted Scenarios

You can disable the full CAS stack walk for the unmanaged code permission by building interop assemblies with the TLBIMP /unsafe switch. This switch instructs TLBIMP to generate RCW code that performs link demands, rather than full demands for the unmanaged code permission. The /unsafe switch causes native method declarations to be decorated with SuppressUnmanagedCodeSecurityAttribute, which checks only the immediate caller when an interop call is made.

This technique results in faster calls between managed code and the COM objects created from the associated COM DLL. Use of this command-line switch is shown here.


  C:\>tlbimp mycomponent.dll /out:UnSafe_MyComponent.dll /unsafe


Note If your assembly causes stack walks for other types of permission, such stack walks are not suppressed by using the /unsafe switch. Using this switch only suppresses the full stack walk for the unmanaged code permission. Perform thorough code reviews of such APIs to ensure that they are not susceptible to luring attacks.

Personal tools