◐ Shell
clean mode source ↗

bpo-42972: Fix GC assertion error in _winapi by untracking Overlapped earlier by Fidget-Spinner · Pull Request #26429 · python/cpython

If you want to modify overlapped_dealloc(), I suggest to also remove the compatibility code for Windows XP.

    if (self->pending) {
        if (check_CancelIoEx() &&
            Py_CancelIoEx(self->handle, &self->overlapped) &&
            GetOverlappedResult(self->handle, &self->overlapped, &bytes, TRUE))
        {
            /* The operation is no longer pending -- nothing to do. */
        }
        else if (_Py_IsFinalizing())
        {
            /* The operation is still pending -- give a warning.  This
               will probably only happen on Windows XP. */
            PyErr_SetString(PyExc_RuntimeError,
                            "I/O operations still in flight while destroying "
                            "Overlapped object, the process may crash");
            PyErr_WriteUnraisable(NULL);
        }
        else
        {
            /* The operation is still pending, but the process is
               probably about to exit, so we need not worry too much
               about memory leaks.  Leaking self prevents a potential
               crash.  This can happen when a daemon thread is cleaned
               up at exit -- see #19565.  We only expect to get here
               on Windows XP. */
            CloseHandle(self->overlapped.hEvent);
            SetLastError(err);
            return;
        }
    }

check_CancelIoEx() can be removed and CancelIoEx() can be used directly. It's available since Windows Vista and Python 3.11 requires Windows Vista or newer:
https://docs.microsoft.com/en-us/windows/win32/fileio/cancelioex-func

See also bpo-32592 "Drop support of Windows Vista and Windows 7".

Please open a separated PR for that.

I don't think that it's worth it to only move the PyObject_GC_UnTrack() call.