0

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;
}
svick
  • 236,525
  • 50
  • 385
  • 514
m93a
  • 8,866
  • 9
  • 40
  • 58
  • Possible duplicate of [How to add Custom Attributes to a DynamicMethod-generated method?](https://stackoverflow.com/questions/1145123/how-to-add-custom-attributes-to-a-dynamicmethod-generated-method) – Jeroen Mostert Aug 25 '17 at 22:30
  • The question you link claims that there's no solution. However there is [another related one](https://stackoverflow.com/questions/3247471/how-can-i-make-my-dynamicmethod-security-critical), which seems to be resolved. However it is too vague and abstract for me – m93a Aug 25 '17 at 22:41
  • You're right, that's a much better duplicate. Both answers say the same thing but slightly differently -- use the [overload of the `DynamicMethod` constructor](https://msdn.microsoft.com/library/xc6e708b) that allows attaching the method to a specific type (note also the tantalizing `skipVisibility`). One does this with a type in `mscorlib`, the other with a custom assembly that's explicitly marked `[SecurityCritical]`. The former's less work, but I'm not sure you can just go around attaching dynamic methods to any `mscorlib` type (like `String`). You could try, though. – Jeroen Mostert Aug 25 '17 at 22:51

1 Answers1

0

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.

Yennefer
  • 5,704
  • 7
  • 31
  • 44