Skip to content

Resource leak if allocation of SafeHandle fails #1430

@carlreinke

Description

@carlreinke

Actual behavior

The generated code leaks the resource if allocation of the SafeHandle instance causes OOM. E.g.

internal static unsafe winmdroot.Devices.DeviceAndDriverInstallation.CONFIGRET CM_Open_DevNode_Key(uint dnDevNode, uint samDesired, uint ulHardwareProfile, uint Disposition, out Microsoft.Win32.SafeHandles.SafeRegistryHandle phkDevice, uint ulFlags)
{
    winmdroot.System.Registry.HKEY phkDeviceLocal;
    winmdroot.Devices.DeviceAndDriverInstallation.CONFIGRET __result = PInvoke.CM_Open_DevNode_Key(dnDevNode, samDesired, ulHardwareProfile, Disposition, &phkDeviceLocal, ulFlags);
    phkDevice = new Microsoft.Win32.SafeHandles.SafeRegistryHandle(phkDeviceLocal, ownsHandle: true);  // OOM
    return __result;
}

Expected behavior

The generated code should allocate the SafeHandle instance before the P/Invoke and use Marshal.InitHandle to initialize the handle after the P/Invoke. E.g.

internal static unsafe winmdroot.Devices.DeviceAndDriverInstallation.CONFIGRET CM_Open_DevNode_Key(uint dnDevNode, uint samDesired, uint ulHardwareProfile, uint Disposition, out Microsoft.Win32.SafeHandles.SafeRegistryHandle phkDevice, uint ulFlags)
{
    phkDevice = new Microsoft.Win32.SafeHandles.SafeRegistryHandle();
    winmdroot.System.Registry.HKEY phkDeviceLocal;
    winmdroot.Devices.DeviceAndDriverInstallation.CONFIGRET __result = PInvoke.CM_Open_DevNode_Key(dnDevNode, samDesired, ulHardwareProfile, Disposition, &phkDeviceLocal, ulFlags);
    System.Runtime.InteropServices.Marshal.InitHandle(phkDevice, phkDeviceLocal);
    return __result;
}

See also the API review for Marshal.InitHandle.

Context

  • CsWin32 version: 0.3.183
  • Target Framework: net8.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomers

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions