Skip to content

Unable to break on callback from unmanaged thread #89292

@mayuki

Description

@mayuki

Description

If a managed callback function is called from an unmanaged thread, the debugger cannot break at the beginning of the callback.

The behavior is unstable, as it can break after the second line, or it may break after many calls. In complex scenarios, stepping through the debugger using mixed mode may cause AccessViolationException or ExecutionEngineException to be thrown.

This problem only occurs when using the traditional Delegate (GetFunctionPointerForDelegate) method and not when using the function pointer (delegate*).

Reproduction Steps

Managed

NativeMethods.mylib_callback(Callback);

static void Callback()
{
    Console.WriteLine("Callback"); // <-- Set a breakpoint on this line.
}

unsafe static class NativeMethods
{
    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    public delegate void mylib_callback_callback();

    [DllImport("Dll1", EntryPoint = "mylib_callback", CallingConvention = CallingConvention.Cdecl)]
    public static extern void mylib_callback(mylib_callback_callback callback);
}

Native

typedef void (cdecl* MYLIB_CALLBACK)();
extern "C" __declspec(dllexport) cdecl void mylib_callback(MYLIB_CALLBACK callback);

DWORD WINAPI MyLibCallbackThread(LPVOID lpParameter)
{
	((MYLIB_CALLBACK)lpParameter)();
	return 0;
}

void mylib_callback(MYLIB_CALLBACK callback) {
	DWORD threadId;
	HANDLE hThread = CreateThread(nullptr, NULL, &MyLibCallbackThread, (LPVOID)callback, NULL, &threadId);
	WaitForSingleObject(hThread, INFINITE);
}

Expected behavior

The debugger breaks at the breakpoint

Actual behavior

The debugger passes breakpoint

Regression?

If the codes are running on .NET Framework 4.x, the debugger breaks as expected.

Known Workarounds

No response

Configuration

  • Build configuration: Debug
  • .NET 7.0.306 (x64)
  • Microsoft Visual Studio 2022 Version 17.6.5
  • Microsoft Windows 10 Pro 22H2

Other information

No response

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions