Skip to content

Analyzer for System.Runtime.CompilerServices.DisableRuntimeMarshallingAttribute #63714

@jkoritzinsky

Description

@jkoritzinsky

In #60639, we approved the System.Runtime.CompilerSevices.DisableRuntimeMarshallingAttribute API. This API is primarily intended to help enable using source-generated interop and to help simplify some concepts in the interop space by disabling some features of the built-in interop system.

This proposal proposes an analyzer to identify when users are using features of the built-in interop system when runtime marshalling is disabled with [assembly:DisableRuntimeMarshalling]. This analyzer will emit a warning diagnostic in the following scenarios (all of which fail at runtime when the P/Invoke or delegate would be called in an interop scenario):

  • SetLastError is set to true on a P/Invoke
  • [LCIDConversionAttribute] is used on a P/Invoke
  • A type that is not a C#-unmanaged type is in a P/Invoke signature or the signature of a delegate with the [UnmanagedFunctionPointer] attribute.
  • A C#-unmanaged type that has any fields with [StructLayout(LayoutKind.Auto)] that is in a P/Invoke signature or the signature of a delegate with the [UnmanagedFunctionPointer] attribute.

The analyzer can also emit a "notice"-level diagnostic for the following scenarios that are likely user errors when [assembly:DisableRuntimeMarshalling] is applied. These scenarios use APIs that do not change behavior when [assembly:DisableRuntimeMarshalling] is applied and always respect the built-in marshalling system. I suggest a "notice" level diagnostic as it's possible that the user is calling APIs defined in other assemblies that don't have [assembly:DisableRuntimeMarshalling] applied or that the results of the APIs are correct even when marshalling is disabled.

  • When Marshal.SizeOf is used on an unmanaged type. (We could also include a code-fix here to recommend switching to Unsafe.SizeOf or the sizeof keyword)
  • When Marshal.OffsetOf is used.
  • When Marshal.StructureToPtr or Marshal.PtrToStructure is used. (We can include code-fixes here to use "unsafe" code or other unsafe APIs).

cc: @dotnet/interop-contrib

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.Runtime.InteropServicescode-analyzerMarks an issue that suggests a Roslyn analyzercode-fixerMarks an issue that suggests a Roslyn code fixer

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions