Search code examples
c#cilcode-access-securitydynamicmethod

How to mark DynamicMethod as SecurityCritical?


I'm using a slightly modified version of this TaskFromEvent method. It basically creates a Task that completes when the Event fires. This is made possible by using DynamicMethod and emitting IL code. When I do some simple tests in dummy environment, everything works fine. But then I need to use it in more complicated environment¹ and it crashes with Attempt of transparent method DynamicClass.unnamed to access a critical type RenamedEventArgs was denied. I understand the concepts of IL and CAS only vaguely, but from what I've read I assume this could be fixed by aplying [SecuritySafeCriticalAttribute] to the DynamicMethod, but how do I do this? How can I apply this attribute to a dynamic method?


¹: specifically I need to await a task that is created from an event which is triggered by JavaScript inside CefSharp

.

This is an extract from my code which I think is the most relevant (whole code here):

public static async Task<object> Once<T>(this T obj, string eventName)
{
  var tcs = new TaskCompletionSource<object[]>();

  // ... some code omitted ...

  handler = new DynamicMethod("unnamed",
    returnType, parameterTypesArray, tcsType);

  ILGenerator ilgen = handler.GetILGenerator();

  // ... generating the IL ...

  ilgen.Emit(OpCodes.Ret);

  Delegate deleg = handler.CreateDelegate(delegateType, tcs);

  eventInfo.AddEventHandler(target, deleg);
  var args = await tcs.Task;
  eventInfo.RemoveEventHandler(target, deleg);

  return args;
}

Solution

  • Unfortunately, emitting custom attributes to dynamic method is not supported by the runtime as stated by the DynamicMethod class documentation:

    Custom attributes are not supported on dynamic methods or their parameters.