CsWin32: COM interfaces returning structs use wrong calling convention

Some COM interfaces return structs instead of HRESULTs, for example the Direct2D and Direct3D12 APIs have this, some examples:

  • DXGI_RGBA ID2D1SolidColorBrush::GetColor()
  • D2D_SIZE_U ID2D1RenderTarget::GetPixelSize()
  • D3D12_RESOURCE_DESC ID3D12Resource::GetDesc()

Historically .NET only implements the stdcall calling convention which is what is used for P/Invoke methods but is not the calling convention used by COM interfaces, which instead uses a stdcall+thiscall combination. This is (probably?) mostly identical to stdcall but (at least) differs in how structs are returned, stdcall seems to return them in a register while stdcall+thiscall returns them on the stack. See dotnet/coreclr#23974 for a technical discussion.

When you are doing the projection from the metadata you can only return structs using [NativeTypedef] over primitive types (like integers) from a COM interface. If you need to return a “real” struct then you need to actually return it via ref or out to simulate what the calling convention does.

There’s been desire to add the proper calling convention to the dotnet runtime (dotnet/runtime#46775) but its not finished and not available on older versions, so unless you want to reject access to these APIs you’ll have to work around the shortcomings of the runtime. (Also when this calling convention gets in, I don’t know how it will handle HRESULT structs, which aren’t actually structs. If you have no way to signify its to be treated differently you have the reverse problem, returning HRESULT on the stack instead of via register.)

PS: I’m no expert on calling conventions and only aware of this because I got broken by it, so you may want to talk to some of the runtime guys who (hopefully) know the details of this calling convention better.

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Comments: 47 (37 by maintainers)

Commits related to this issue

Most upvoted comments

That being said, if the runtime opted to support [TransparentStruct] attribute I’ve proposed/discussed in various issues (basically extending the support it already has for CLong, CULong, and NFloat to user-defined types wrapping a single field), this would become infinitely simpler.

Dev’s would not be forced to define such wrapper methods for trivial (and super common) helper types like this, allowing them to do the more optimal thing and allowing the runtime to handle the blittable unwrapping correctly (rust has this via [repr(transparent)]).

– CC. @jkoritzinsky (I know I’ve bugged you on this a lot 😄)

I greatly appreciate CsWin32 making P/Invoke substantially easier in C#, but this is an extremely frustrating gap to have to find out through crashes. Regardless of whether this issue is metadata, coreclr, cswin32, implementation, or documentation, it needs to be improved.

If CsWin32 is not expected to generate valid clients for these interfaces, then please don’t produce them (produce an error, a vtbl_gap, or hide them behind a flag).

If CsWin32 is expected to generate valid clients, then please fix them (even if a better or more complete fix is coming long-term).

The worst scenario is what we have today: subtle issues that cause memory corruption and crashes. TerraFX is great, I’m sure, but CsWin32 has become the default for all things Windows interop for our team.

After 1 month of trying to figure out why my program crashes 50% of the time, turns out [PreserveSig()] is required whenever a COM function does not return an HRESULT. Otherwise whenever the pointer returned by GetCPUDescriptorHandleForHeapStart (which is also the same as the pointer passed in) has its 32nd bit set, a System.Runtime.InteropServices.COMException will be returned, because the return value is interpreted as a failing HRESULT value, SUCCEEDED(hr) fails, and thus an exception is thrown.

@jeremykuhne yes, using [Stdcall, MemberFunction] is always correct for COM APIs.

For people (like me) that are searching for a performant workaround for the issue, you can disable COM mashaling and manually use new MemberFunction calling convention which resolves the issue:

private unsafe D3D12_CPU_DESCRIPTOR_HANDLE GetDescriptorHandle(ID3D12DescriptorHeap* heap)
{
    var vtable = *(nint**)heap;
    var getDescriptor = (delegate* unmanaged[Stdcall, MemberFunction]<ID3D12DescriptorHeap*, D3D12_CPU_DESCRIPTOR_HANDLE>)(vtable[9]); // index in vtable needs to be found by inspecting code generated by cswin32
    var getDescriptorResult = getDescriptor(heap);
    return getDescriptorResult;
}

@jkoritzinsky, it’s worth noting that this is compatible but also not quite right either:

change the method to return void

The underlying ABI also returns a pointer to the return buffer parameter and so for a method such as:

virtual D3D12_RESOURCE_ALLOCATION_INFO STDMETHODCALLTYPE GetResourceAllocationInfo( 
    _In_  UINT visibleMask,
    _In_  UINT numResourceDescs,
    _In_reads_(numResourceDescs)  const D3D12_RESOURCE_DESC *pResourceDescs) = 0;

The fixup on C# should/can be:

public D3D12_RESOURCE_ALLOCATION_INFO GetResourceAllocationInfo(uint visibleMask, uint numResourceDescs, D3D12_RESOURCE_DESC* pResourceDescs)
{
    D3D12_RESOURCE_ALLOCATION_INFO result;
    return *((delegate* unmanaged<ID3D12Device*, D3D12_RESOURCE_ALLOCATION_INFO*, uint, uint, D3D12_RESOURCE_DESC*, D3D12_RESOURCE_ALLOCATION_INFO*>)(lpVtbl[25]))((ID3D12Device*)Unsafe.AsPointer(ref this), &result, visibleMask, numResourceDescs, pResourceDescs);
}

This is also slightly more convenient than having an additional return statement that is effectively return result. You can see an example of this behavior here: https://godbolt.org/z/4EofM4 (and can also go browse the MSVC source if needed).

@AffluentOwl You can play with the _VTblGap prefix for those functions if you’d like to remove them. This is how Embedded PIAs are implemented. In this case, you could redefine this to be:

    [Guid("8EFB471D-616C-4F49-90F7-127BB763FA51"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport()]
    internal interface ID3D12DescriptorHeapExtended : ID3D12DescriptorHeap
    {
      void _VTblGap_6(); // Represents 6 vtable slots

      unsafe D3D12_CPU_DESCRIPTOR_HANDLE* GetCPUDescriptorHandleForHeapStart(D3D12_CPU_DESCRIPTOR_HANDLE* result);

      // Remaining unused functions unneeded
    }

Which is to say, I expect it’s under 50 lines of code to enable for struct S { T Value; } where T is byte, sbyte, short, ushort, int, uint, long, ulong, nint, nuint, float, or double.

I could see some complexities for char or bool and I could see complexities for cases where users try to do more than 1 field or a non-primitive struct, but we already have logic to trivially throw a TypeLoadException (explicit layout with value type/reference type overlapping) for other similar invalid attributions and cases where we ignore it for invalid specifiers (incorrect packing specified), so we could just pick a right behavior and it still stays simple.

Should be safe to do so since (as far as I know) the only differnce between the both is how structs are returned.

I would not rely on this, as it can break on any future platforms. Doing this is effectively relying on an implementation detail of the x64 platform and historical JIT support. Platforms such as Arm64 or theoretical future platforms such as RISC-V or LoongArch can break from doing this (just as emulating the correct x64 signature does already break on Arm64 for some cases today).

It’s better to simply ensure your function pointers and P/Invokes are 1-to-1 to prevent any potential breaks (it’s the only surefire correct thing). You can hide the direct P/Invoke and expose a wrapper which only lets users see the nice HRESULT wrapper struct if that is the surface area you want to expose.

@tannergooding it looks like the winmd might not contain this info (or I’m missing something).

I made an issue to them to include these annotations I believe, when I stumbled upon one of these interfaces, let me look it up.

@JeremyKuhne yes, using [Stdcall, MemberFunction] is always correct for COM APIs.

@jkoritzinsky its worth noting this isn’t actually the case, unfortunately 😢

COM APIs are instance members and so MemberFunction is needed. Additionally, most COM APIs are explicitly exported as __stdcall and so [StdCall, MemberFunction] is correct.

However, there do exist some COM APIs which are not explicitly __stdcall. For example, some of these are on IDebugControl in um/DbgEng.h which use STDMETHODV instead (this is defined as virtual COM_DECLSPEC_NOTHROW HRESULT STDMETHODVCALLTYPE method in um/combaseapi.h, where STDMETHODVCALLTYPE is __cdecl in um/winnt.h).

Some other files that includes such COM methods are um/MethodCo.h, um/MspAddr.h, um/MspCall.h, um/MspStrm.h, uim/Mspterm.h, um/Msptrmac.h, um/Msptrmar.h, um/Msptrmvc.h, um/Provider.h, um/TextServ.h, um/axextend.idl, um/baseaudioprocessingobject.h, um/dxcapi.h, um/shdeprecated.h, um/strmif.h, um/vswriter.h, and um/xapobase.h.

There’s even one that uses __fastcall in um/baseaudioprocessingobject.h

yes, when the C++/Headers return a struct the interface (without stdcall/memberfunction) would need to return it as out parameter in last position to get the ABI right (returning the result via register vs. the stack) if you are supporting classic COM interop - this was done because (among others) WPF is returning a HRESULT struct commonly and “fixing” .NET to use stdcall/memberfunction by default breaks the common usecase of wrapping such returns like HRESULT in a struct. This was fixed in the past, regressed people, so rolled back to how Desktop Framework behaves. Net result is that C++ struct returns need to be special cased in COM APIs (and for Desktop Framework it always was this way anyways).

The question is whether you can differentiate struct returns from typedef returns in your API source from which you generate, I haven’t looked at it for a while since I went back to transcribing APIs manually again. HRESULT would be a typedef and returned via register as if it were just an integer, even if C# defines a wrapper struct for it, while D3D_SIZE_F above is a “real” C++ struct and need to be returned on the stack (out parameter or stdcall/memberfunction convention)

In this case, CsWin32 will need to manually adjust the signature to insert the return buffer since .NET will not do the correct thing without the new CallConvMemberFunction type.

Ok, so I need to modify the return type to be a pointer, and I need to add that same pointer type as an additional parameter in the method as well (always in last position).

You’ll need to add the additional parameter after the this parameter and before all other parameters.

And I do this when the return type is a struct that wasn’t a typedef on the native side. For COM interface methods only. Right?

Yes.

.NET accidentally gets the behavior right, since the native typedef HRESULT is treated the same as the underlying int type. This accidental success is the “back-compat” case mentioned previously.

do we know if the accidental success here is RyuJIT/Legacy JIT only or if it also applies to Mono and Mono/AOT?

I do not know if Mono has the same problem with their COM Interop support, but I wouldn’t be shocked if it did. I haven’t had a chance to test it yet. They’ll definitely have the same problem with function pointers though.

All our COM structs define vtbl’s with function pointers as fields, and they work on net472.

Do you have an example of what is being generated? I recall fairly simple examples showing this fails.

not sure about what the ABI is for large primitives, never seen a COM method return a primitive larger than 8 bytes

D3D12 has a few, one of which is the GetResourceAllocationInfo example I keep giving. D3D12_RESOURCE_ALLOCATION_INFO is a 16-byte struct containing 2x UINT64 fields. You can find many examples (currently 107) of these types of fixups by grepping for result; in my TerraFX.Interop.Windows project: https://github.com/terrafx/terrafx.interop.windows/tree/main/sources/Interop/Windows, https://source.terrafx.dev/#TerraFX.Interop.Windows/um/d3d12/ID3D12Device.cs,8b9b043be241c1ea. I’ve provided my own grep results here for convenience: result.txt

Edit: I misread the comment as struct, not primitive. As far as the ABI is concerned, things like __int128 aren’t true primitives but rather their own type. __m128 and friends are primitives and respected by the ABI. These correspond to Vector128<T> and friends in .NET and are only available in .NET Core 3.0+. They are currently blocked in P/Invokes because we don’t correctly handle the return scenario on Windows.

The correct solution here would be to do a two-pronged approach:

For the typedef structs, you can either do one of the two following options:

  • Use the underlying type as the return type for the function pointer. This will enable the correct results if the generated code ever uses CallConvMemberFunction.
  • Use the typedef type as the return type. This ends up using the “non-member function” calling convention, which will work in this case. This will continue to work if the code-gen uses the built-in COM support as well (this is the legacy behavior Aaron mentioned), but not if the code ever uses CallConvMemberFunction.

For the non-typedef structs, you can do one of the two following options:

  • Manually transform the function pointer/COM method signature to have an out return buffer parameter after the native this parameter and change the method to return void. This will be necessary in the “pointer-free” mode you mentioned. The built-in COM system will never support using the natural signature for this case because it breaks the other case pretty severely.
  • Use CallConvMemberFunction.

We’re introducing CallConvMemberFunction to enable using the natural function signature with member functions that return structs since we can’t change the built-in behavior without breaking people that rely on the “feature” that their HRESULT struct type can be used in place of an HRESULT.