Skip to content

ComInterfaceGenerator does not properly handle lifetimes for return values and 'out' parameters in failing COM methods  #88111

Open

Description

@jtschuster

If a native COM method fails, the generated code will still attempt to clean up the return value and out parameters. The expected behavior is that a failing HRESULT means that out parameters and return values are not valid and any allocation of resources from the callee was cleaned up by the callee. It also means the callee is not expected to clean up any values passed to it, and they should be cleaned up by the caller. Generally, on a failure HRESULT no resources have changed ownership and all memory should be cleaned up by the entity that allocated them (caller or callee).

The issue with the generated code it that the UnmanagedToManaged callee methods with by reference parameters take ownership of the passed values after the managed interface method call succeeds, so if the generated code throws when marshalling the value back to native, the callee method will still cleanup the original and return a failing HRESULT. This goes against the expectation that the caller must clean up the passed in value if the return value is a failure.

Since the marshalling stubs may fail, the generated stubs must follow these rules as well. If the ManagedToUnmanaged wrapper sees a failure HRESULT, it should not try to clean up any of the out parameters or return values.

The UnamanagedToManaged wrapper may cause a failure HRESULT during marshalling and unmarshalling, so it must follow the rules for the parameters passed in. If it returns a failing HRESULT, it should not also clean up any of the memory passed by the parameters (though it doesn't need to worry about the memory it allocates; the GC will handle that).

Activity

  1. self-assigned this
    on Jun 27, 2023
  2. ghost added
    untriaged
    on Jun 27, 2023
  3. removed
    untriaged
    on Jun 27, 2023
  4. added this to the 8.0.0 milestone on Jun 28, 2023
  5. modified the milestones: 8.0.0, 9.0.0 on Jul 27, 2023
  6. modified the milestones: 9.0.0, 10.0.0 on Aug 8, 2024
  7. modified the milestones: 10.0.0, 11.0.0 on Aug 11, 2025
  8. dotnet-policy-service commented on Apr 13, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/interop-contrib
    See info in area-owners.md if you want to be subscribed.

  9. added
    source-generator
    and removed on Jun 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.Runtime.InteropServicessource-generator

Type

No type

Projects

  • Status
    No status

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions