Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can OpCodes.Jmp be called to transfer control to a method that resides on a different assembly? [closed]

Can Method1 that resides in AssemblyA issue a OpCodes.Jmp to Method1 that resides in AssemblyB? Both methods have same exact signature.

I can't seem to make this work, always getting System.InvalidProgramException : Common Language Runtime detected an invalid program.

If the redirection is inside the same Assembly, it works.

If possible, please provide example using Reflection.Emit.

like image 692
Ricardo Barbosa Avatar asked Feb 03 '26 17:02

Ricardo Barbosa


1 Answers

You must have missed something. Are both methods static? Do they have the same calling convention?

The following code doesn't reproduce your issue:

static void Main(string[] args)
{
    var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly
                    (new AssemblyName("TestAssembly"), AssemblyBuilderAccess.Run);
    var module = assembly.DefineDynamicModule("Main");
    var type = module.DefineType("Test");

    var method = type.DefineMethod
                  (
                    "Test", MethodAttributes.Public | MethodAttributes.Static, 
                    typeof(int), new[] { typeof(string) }
                  );
    var gen = method.GetILGenerator();
    gen.Emit(OpCodes.Jmp, typeof(Class1).GetMethod("Test"));

    var obj = Activator.CreateInstance(type.CreateType());

    var func = (Func<string, int>)
                obj.GetType().GetMethod("Test").CreateDelegate(typeof(Func<string, int>));
    var result = func("Banana");

    Console.WriteLine(result);
    Console.ReadLine();
}

And in a different assembly, the Test class:

public static class Class1
{
    public static int Test(string hi)
    {
        return 42;
    }
}

Did you make sure you're not violating any of the restrictions?

  • The evaluation stack must be empty when this instruction is executed.
  • The calling convention, number and type of arguments at the destination address must match that of the current method.
  • The jmp instruction cannot be used to transferred control out of a try, filter, catch, or finally block.
like image 102
Luaan Avatar answered Feb 05 '26 07:02

Luaan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!