Skip to content

Add support for freeing handles automatically - #3013

Merged
Kenny Kerr (kennykerr) merged 4 commits into
masterfrom
free
May 1, 2024
Merged

Kenny Kerr (kennykerr) merged 4 commits into
masterfrom
free

Conversation

@kennykerr

@kennykerr Kenny Kerr (kennykerr) commented Apr 30, 2024 •

Copy link
Copy Markdown
Collaborator

The Win32 metadata includes information about how to free certain kinds of handles. Since ownership is often unknown or contextual, this is not used to implement the standard Drop trait. Instead, a new Free trait provided by the windows-core crate is implemented for all handles with appropriate metadata. The free function can be used to free the handle manually, but an Owned<T> wrapper is provided to call free automatically when the owned handle is dropped.

This is supported by nearly 150 different handle types - not just HANDLE - including various crypto handle types, registry, GDI and USER32 types, and many more.

Workarounds are provided for the following Win32 metadata bugs:

Here's an example.

Before:

let event = CreateEventW(None, true, false, None)?;
SetEvent(event)?;
WaitForSingleObject(event, 0);
_ = CloseHandle(event);

After:

let event = Owned::new(CreateEventW(None, true, false, None)?);
SetEvent(*event)?;
WaitForSingleObject(*event, 0);

The BCrypt test provides a more comprehensive example: e386c51

Previously, the test was just leaking. You can see how Owned supports all kinds of BCrypt handle types through type inference.

Related: #2638 #2468 #2222

@MarijnS95

Marijn Suijten (MarijnS95) commented May 1, 2024 •

Copy link
Copy Markdown
Contributor

This looks like really nice stuff! Is the metadata enriched to know when functions like CreateEventW() return an owned handle so that they could possibly return Owned<> straight away in the future, forcing the user to handle automatic lifetime management?

@kennykerr

Copy link
Copy Markdown
Collaborator Author

This looks like really nice stuff! Is the metadata enriched to know when functions like CreateEventW() return an owned handle so that they could possibly return Owned<> straight away in the future, forcing the user to handle automatic lifetime management?

This isn't very clear today. Hopefully in future...

Mike Griese (zadjii-msft) pushed a commit to microsoft/sudo that referenced this pull request Jul 1, 2024
As it happens, another update to the `windows` family of crates is available:
https://github.com/microsoft/windows-rs/releases/tag/0.57.0

In particular, this one includes a new feature to support freeing handles automatically:
microsoft/windows-rs#3013

This avoids the need for the `OwnedHandle` helper type in Sudo.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants