Skip to content

[interp] DynamicMethod with a CALL of a P/Invoke throws "BadImageFormatException: Method has no body" #38897

Closed
mono/mono
#20199

Description

Description

The following program correctly calls the P/Invoke when runnign with the JIT, but throws a BadImageFormatException: Method has no body under the interpreter.

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;


namespace HelloWorld
{
	public delegate void NativeMethodInvoker ();

	class Program
	{
		static void Main(string[] args)
		{
			Test1 ();
		}

		public static void Test1 ()
		{
			Console.WriteLine($"Running {nameof(Test1)}...");

			DynamicMethod testUnmanagedCallersOnly = new DynamicMethod("UnmanagedCallersOnly", null, null, typeof(Program).Module);
			ILGenerator il = testUnmanagedCallersOnly.GetILGenerator();
			il.Emit(OpCodes.Nop);
		    
			il.Emit (OpCodes.Ldc_I4_0);
			il.Emit (OpCodes.Conv_I);

			il.Emit(OpCodes.Call, typeof(Program).GetMethod(nameof (CallThing)));
			il.Emit(OpCodes.Nop);
			il.Emit(OpCodes.Ret);
			var testNativeMethod = (NativeMethodInvoker)testUnmanagedCallersOnly.CreateDelegate(typeof(NativeMethodInvoker));

			testNativeMethod ();
		}

		[DllImport ("Foo", EntryPoint="call_thing")]
		public static extern void CallThing (IntPtr pFn);
	}
}

and clang -o libFoo.dylib -shared foo.c where foo.c is:

#include <stdio.h>

void
call_thing (void *p)
{
	printf ("in call_thing %p\n", p);
}

Configuration

Mono on OSX. Both net5 and mono/mono master.

Regression?

not sure

Other information

Expected output:

Running Test1...
in call_thing 0x0

Actual output:

Running Test1...

Unhandled Exception:
System.BadImageFormatException: Method has no body
File name: 'Program'
  at (wrapper dynamic-method) System.Object.UnmanagedCallersOnly()
  at (wrapper delegate-invoke) <Module>.invoke_void()
  at HelloWorld.Program.Test1 () <0x7ff17605d808 + 0x00124> in <2250f8cc19ca4afc839a8fabb2d1d0b4>:0
  at HelloWorld.Program.Main (System.String[] args) <0x7ff17700c170 + 0x00000> in <2250f8cc19ca4afc839a8fabb2d1d0b4>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.BadImageFormatException: Method has no body
File name: 'Program'
  at (wrapper dynamic-method) System.Object.UnmanagedCallersOnly()
  at (wrapper delegate-invoke) <Module>.invoke_void()
  at HelloWorld.Program.Test1 () <0x7ff17605d808 + 0x00124> in <2250f8cc19ca4afc839a8fabb2d1d0b4>:0
  at HelloWorld.Program.Main (System.String[] args) <0x7ff17700c170 + 0x00000> in <2250f8cc19ca4afc839a8fabb2d1d0b4>:0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions