Question

I need to pre-JIT some emitted delegates ahead of time and tried using the RuntimeHelpers.PrepareDelegate for this, but this method is marked with the SecurityCritical attribute. My assembly is marked with the AllowPartiallyTrustedCallers attribute and can therefore not call any security critical code.

Why are PrepareDelegate and PrepareMethod security critical and what alternatives are their that alternatives do I have in pre-JITting those delegates?

Was it helpful?

Solution

As referenced in the MSDN article CA2140: Transparent code must not reference security critical items:

How to Fix Violations

To fix a violation of this rule, do one of the following:

  • Mark the code element that uses the security critical code with the SecurityCriticalAttribute attribute

    - or -

  • Remove the SecurityCriticalAttribute attribute from the code elements that are marked as security critical and instead mark them with the SecuritySafeCriticalAttribute or SecurityTransparentAttribute attribute.

You have to mark the method that does the pre-JITing with the [SecuritySafeCriticalAttribute]. Here it is in action:

using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Security;

[assembly: AllowPartiallyTrustedCallers]
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            PreJIT();
        }

        [SecuritySafeCritical]
        static void PreJIT()
        {
            RuntimeHelpers.PrepareMethod(
                System.Reflection.Emit.DynamicMethod.GetCurrentMethod()
                .MethodHandle);
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top