mheily / libkqueue

kqueue(2) compatibility library
Other
236 stars 77 forks source link

Closing a file descriptor on Windows might cause an assertion #151

Open timwoj opened 1 year ago

timwoj commented 1 year ago

I'm working on some stuff in Windows and I'm running into a assertion where we call close on the file descriptor returned from kqueue(). The problem is that if you call close on a file descriptor twice in Windows in a debug build, you get the following:

2022-12-09 13_21_14-Microsoft Visual C++ Runtime Library

I think the issue is that the Windows code in libkqueue always returns a zero from windows_kqueue_init without any backing to an actual file or handle, which seems a bit fraught with danger. There's no guarantee that some other code somewhere isn't already using that file descriptor, and if you have already closed it somewhere else you end up with the assertion above.

The _open_osfhandle function can convert a HANDLE into a file descriptor but I'm not sure of the ramifications of that. The docs say that it transfers ownership of the handle to the descriptor, but that might alright as long as the handle remains valid. Otherwise windows_kevent_wait wouldn't be able to use the handle to check for completion status. Is windows_kqueue_free called from anywhere? It probably wouldn't be possible to call CloseHandle anymore.

timwoj commented 1 year ago

The _open_osfhandle function can convert a HANDLE into a file descriptor but I'm not sure of the ramifications of that. The docs say that it transfers ownership of the handle to the descriptor, but that might alright as long as the handle remains valid. Otherwise windows_kevent_wait wouldn't be able to use the handle to check for completion status. Is windows_kqueue_free called from anywhere? It probably wouldn't be possible to call CloseHandle anymore.

I went ahead and tried to implement this without any luck sadly. I'm not entirely sure open_osfhandle is compatible with the IO Completion Port handle that's in use here, or if it's something else I'm missing.