Skip to content

Roslyn Code analyzers for interop #37039

Open

Description

@elinor-fung

This tracking issue for a small backlog of rules around interop to add to the officially recommended set of analyzers. The rules are grouped around runtime functionality/features, but would represent separate analyzers in implementation. Since many issues concerning interop are rooted in a discrepancy between the user's intent and implementation, it is expected that only a small number of rules would be useful and applicable to all users. Official documentation will remain the main source of guidance for more nuanced behaviour that requires clear understanding of intent.

The upcoming plan to provide source generators for p/invokes should not directly affect the rules here, as that functionality would be using a different attribute for declaring p/invokes. However, there is the opportunity to provide an analyzer to help users migrate to the source generator approach. Once a source generator exists, the rules here could also be updated to consider p/invokes which use that generator or, depending on their severity, warnings within the generator itself.

The intent is that as the runtime interop team works through a backlog of analyzers around existing features and functionality, the concept of considering and adding analyzers for any new features will become natural and simply be part of that feature work. The P/Invokes and Marshalling rules are expected to be the starting points for working through this backlog.

P/Invokes

These rules inspect the actual declaration and invocation of p/invokes.

  • Do not use [Out] string for P/Invokes: Do not use [Out] string for P/Invokes #35692
  • Avoid StringBuilder parameters for P/Invokes: Avoid StringBuilder parameters for P/Invokes #35693
  • Prefer ExactSpelling=true in [DllImport] for known APIs: Prefer ExactSpelling=true on [DllImport] for known APIs #35695
  • Remove redundant configuration from [DllImport] declaration Remove redundant configuration from [DllImport] declaration #33808
  • CA1404 port: Port FxCop rule CA1404: CallGetLastErrorImmediatelyAfterPInvoke roslyn-analyzers#420
  • Prefer SafeHandle over IntPtr for known APIs: Analyzer suggestion: Prefer SafeHandle over IntPtr #42404
  • Get the last error after calls to P/Invokes with SetLastError=true
    • Category: Interoperability
    • Default: Enabled
    • After calling a p/invoke that sets the last error, Marshal.GetLastWin32Error should be called to retrieve the last error.
      [DllImport("MyLibrary", SetLastError = true)]
      private static extern void Foo();
      
      public static void Bar()
      {
          Foo(); // Flag last error not retrieved
      }
      
      public static void Baz()
      {
          Foo(); // OK
          if (Marshal.GetLastWin32Error() == 0) { ... }
      }
  • Specify SetLastError=true in [DllImport] for known APIs
    • Category: Interoperability
    • Default: Enabled
    • For APIs that are known to set last error, SetLastError=true should be specified. This would require having/building a database of APIs to compare against.
      // Flag SetLastError=false for known API
      [DllImport("kernel32")]
      public static extern bool CloseHandle(IntPtr hObject);
      
      // OK - known API does not set last error
      [DllImport("kernel32")]
      public static extern int GetCurrentProcessId();
    • Recommend:
      [DllImport("kernel32.dll", SetLastError = true)]
      public static extern bool CloseHandle(IntPtr hObject);
    • If the user does not intend to check the error, this can be skipped, but the general guidance is to both define the p/invoke to set last error (for APIs that do so) and check the error.

Marshalling

These rules inspect how data is marshalled. They would apply to the parameters on p/invokes and any types (e.g. marshalled structs, delegates) used by p/invokes.

COM

These rules inspect COM-related functionality. Many of the existing rules that have not yet been ported are around COM.

Low-level interop APIs

These rules are related to APIs that provide low-level interaction/integration with the runtime's interop system.

Cross-platform

There is an existing proposal for an analyzer that detects the use of platform-specific APIs where the API might not be available. Many interop-related APIs are platform-specific and would be given the appropriate attribute such that the proposed analyzer would flag their use.

The logic that will be used by the proposed analyzer for platform-specific APIs could be leveraged for platform-specifc interop behaviour that is not tied to a specifid API. There are some types or MarshalAs values for which marshalling is not supported on all platforms. In these cases, it is not a known API that is platform-specific, but a user-defined p/invoke that is platform-specific due to the way it is defined. An analyzer would detect those p/invokes and treat those as platform-specific calls, following the same logic as that for the platform-specific APIs for determining the platform context and checking for platform guards around the call site.

Rules:

  • Marshalling of <Type> requires <OS>
  • Marshalling as <UnmanagedType.*> requires <OS>

Existing rules

There are a number of rules around interop and marshalling that go through legacy (static) analysis. They have all previously been deprecated or slated to be ported as time allows. See FxCop rule port status for a list of all ported, tracked, and deprecated rules.

Activity

  1. added
    untriaged
    on May 27, 2020
  2. elinor-fung commented on May 27, 2020

    @elinor-fung
    MemberAuthor
  3. changed the title [-]Code analyzers for interop[/-] [+]Roslyn Code analyzers for interop[/+] on May 27, 2020
  4. rseanhall commented on May 28, 2020

    @rseanhall
    Contributor

    In most Win32 APIs, it is wrong to use Marshal.GetLastWin32Error to check if the API failed because most functions that set the thread's last-error code [only] set it when they fail.

  5. elinor-fung commented on May 28, 2020

    @elinor-fung
    MemberAuthor

    That is definitely the case for the Win32 APIs themselves. However, when going through a p/invoke in .NET Core with SetLastError=true, the runtime will explicitly clear the last error before calling the target function: https://github.com/dotnet/runtime/blob/master/src/coreclr/src/vm/dllimport.cpp#L862-L868

  6. rseanhall commented on May 28, 2020

    @rseanhall
    Contributor

    Interesting, I didn't know that. It doesn't really solve the problem though. CreateFile is a typical Win32 API. In its documentation, it states how to tell when there's a failure (the returned value is INVALID_HANDLE_VALUE). Then it says if it failed, call GetLastError for more information. Nowhere does it say that GetLastError will return 0 on success. So theoretically, CreateFile could internally call another API which sets the last error to non-zero, and still complete successfully without ever putting it back to zero while still adhering to the documented contract.

    This code relies on undocumented behavior:

    var hFile = CreateFile(...);
    if (Marshal.GetLastWin32Error() == 0)
    {
      //succeeded
    }
    else
    {
      //failed
    }
    

    This code doesn't directly check the last error but is perfectly valid (Win32Exception calls Marshal.GetLastWin32Error internally):

    var hFile = CreateFile(...);
    if (hFile == INVALID_HANDLE_VALUE)
    {
      throw new Win32Exception();
    }
    
  7. elinor-fung commented on May 28, 2020

    @elinor-fung
    MemberAuthor

    The spirit of the rule is that there is a path after the p/invoke where the last error is retrieved without another call in between. As your example points out, only expecting Marshal.GetLastWin32Error is not sufficient, but I believe that still fits within the intent of the rule (i.e. the rule should consider Win32Exception and not flag something like that).

  8. added
    Epic
    on Jun 1, 2020
  9. removed
    untriaged
    on Jun 8, 2020
  10. added this to the 5.0 milestone on Jun 8, 2020
  11. modified the milestones: 5.0.0, 6.0.0 on Aug 8, 2020
  12. Mrnikbobjeff commented on Aug 30, 2020

    @Mrnikbobjeff

    One issue which seems to have fallen through the tracks seems to be #33808 which is not referenced in the todo list if I read this correctly

  13. elinor-fung commented on Aug 31, 2020

    @elinor-fung
    MemberAuthor

    Thanks @Mrnikbobjeff - updated the list.

  14. 5 remaining items

  15. added
    Bottom Up Work
    User Story
    and removed on Jan 20, 2021
  16. modified the milestones: 6.0.0, 7.0.0 on Jun 21, 2021
  17. carlossanlop commented on Sep 14, 2021

    @carlossanlop
    Contributor

    @elinor-fung Looks like this other approved proposal belongs to this list:
    #51193

  18. elinor-fung commented on Sep 14, 2021

    @elinor-fung
    MemberAuthor

    @carlossanlop This issue is listing out a backlog of interop-related analyzers. That one looks to be more general performance. I don't believe we do a tracking list for general runtime/performance analyzers.

  19. modified the milestones: 7.0.0, 8.0.0 on Aug 5, 2022
  20. modified the milestones: 8.0.0, 9.0.0 on Jul 19, 2023
  21. modified the milestones: 9.0.0, Future on Feb 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bottom Up WorkUser Storyarea-Interop-coreclr

    Type

    No type

    Projects

    • Status
      No status

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions