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
- Always use BOOL instead of `bool` in native methods This in response to https://github.com/microsoft/CsWin32/issues/167#issuecomment-793124853 — committed to microsoft/CsWin32 by AArnott 6 years ago
- Always use BOOL instead of `bool` in native function pointers This in response to https://github.com/microsoft/CsWin32/issues/167#issuecomment-793124853 — committed to microsoft/CsWin32 by AArnott 6 years ago
- Always use BOOL instead of `bool` in native function pointers This in response to https://github.com/microsoft/CsWin32/issues/167#issuecomment-793124853 — committed to microsoft/CsWin32 by AArnott 6 years ago
- some COM methods need to return in an out parameter https://github.com/microsoft/CsWin32/issues/167 — committed to jayrulez/Win32-Beef by jayrulez 4 years ago
- Latest CsWin32 Update Updating to .NET 8. Updating to latest CsWin32 package. Updating to latest Win32Metadata package. Updating overrides signatures to match the latest generated with CsWin32. Updat... — committed to Shkyrockett/AutoGenDirectWritePlayground by Shkyrockett 3 years ago
- Updating to Latest CsWin32 Updating to .NET 8. Updating to latest CsWin32 package. Updating to latest Win32Metadata package. Updating overrides signatures to match the latest generated with CsWin32. ... — committed to Shkyrockett/Direct2DCanvasPlayground by Shkyrockett 3 years ago
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 forCLong,CULong, andNFloatto 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 byGetCPUDescriptorHandleForHeapStart(which is also the same as the pointer passed in) has its 32nd bit set, aSystem.Runtime.InteropServices.COMExceptionwill 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
MemberFunctioncalling convention which resolves the issue:@jkoritzinsky, it’s worth noting that this is compatible but also not quite right either:
The underlying ABI also returns a pointer to the return buffer parameter and so for a method such as:
The fixup on C# should/can be:
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
_VTblGapprefix 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:Which is to say, I expect it’s under 50 lines of code to enable for
struct S { T Value; }whereTisbyte,sbyte,short,ushort,int,uint,long,ulong,nint,nuint,float, ordouble.I could see some complexities for
charorbooland 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.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.
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.
@jkoritzinsky its worth noting this isn’t actually the case, unfortunately 😢
COM APIs are instance members and so
MemberFunctionis needed. Additionally, most COM APIs are explicitly exported as__stdcalland so[StdCall, MemberFunction]is correct.However, there do exist some COM APIs which are not explicitly
__stdcall. For example, some of these are onIDebugControlinum/DbgEng.hwhich useSTDMETHODVinstead (this is defined asvirtual COM_DECLSPEC_NOTHROW HRESULT STDMETHODVCALLTYPE methodinum/combaseapi.h, whereSTDMETHODVCALLTYPEis__cdeclinum/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, andum/xapobase.h.There’s even one that uses
__fastcallinum/baseaudioprocessingobject.hyes, 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)
You’ll need to add the additional parameter after the
thisparameter and before all other parameters.Yes.
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.
Do you have an example of what is being generated? I recall fairly simple examples showing this fails.
D3D12 has a few, one of which is the
GetResourceAllocationInfoexample I keep giving.D3D12_RESOURCE_ALLOCATION_INFOis a 16-byte struct containing 2xUINT64fields. You can find many examples (currently 107) of these types of fixups by grepping forresult;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 owngrepresults here for convenience: result.txtEdit: I misread the comment as struct, not primitive. As far as the ABI is concerned, things like
__int128aren’t true primitives but rather their own type.__m128and friends are primitives and respected by the ABI. These correspond toVector128<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:
CallConvMemberFunction.CallConvMemberFunction.For the non-typedef structs, you can do one of the two following options:
outreturn buffer parameter after the nativethisparameter and change the method to returnvoid. 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.CallConvMemberFunction.We’re introducing
CallConvMemberFunctionto 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 theirHRESULTstruct type can be used in place of anHRESULT.