Search code examples
.netcil

.Net CIL jmp opcode and generic methods


I'm trying to see how to use the jmp opcode and so far I didn’t manage to call generic methods yet. For my tests, I'm having one method which just returns its argument and another whose body is only the jmp opcode jumping to the first method. My problem is that when I jump to a non-generic method (e.g. jmp int32 Program::Id2(int32) with the following signature for Id2: static int Id2(int x)) there's no error at runtime, while if I do so for a generic method (e.g. jmp !!0 Program::Id<int32>(!!0) with the following signature for Id: static T Id<T>(T x)) I get a “Common Language Runtime detects an invalid program” exception. What could be the cause of that problem?

P.S. : Here’s a gist with the CIL I was using for my tests. Commenting the line jumping to Id2 and uncommenting the one jumping to Id in IdInt makes it fail at runtime with the aforementioned exception. Making IdInt and Id2 return a reference type like StringBuilder doesn’t make it fail though.


Solution

  • ECMA-335 partition III section 3.37 - jmp, says:

    Transfer control to the method specified by method, which is a metadata token (either a methodref or methoddef (See Partition II). The current arguments are transferred to the destination method.

    Both MemberRef and MethodDef tokens are able to reference non-generic methods and open generic methods, but to reference a closed generic method requires a MethodSpec token which is not listed as acceptable.

    I suspect that jmp might not support generic methods because it would interfere with the jits ability to reuse native code for different instantiations of the same generic method.