Skip to content

gh-160561: Close the duplicated descriptor when fromfd() is rejected - #160579

Open
wlkr73 wants to merge 1 commit into
python:mainfrom
wlkr73:gh-160561-fromfd-leak
Open

wlkr73 wants to merge 1 commit into
python:mainfrom
wlkr73:gh-160561-fromfd-leak

Conversation

@wlkr73

@wlkr73 wlkr73 commented Oct 24, 2026 •

Copy link
Copy Markdown

socket.fromfd() duplicates the descriptor and then hands it to the constructor. If the constructor rejects its arguments, the duplicate has no owner and is never closed.

fd = sock.fileno()
for _ in range(3):
    try:
        socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM, 1 << 100)
    except OverflowError:
        pass

That leaks 3 descriptors; with the change, 0. A valid call still returns a working socket and the descriptor count is unchanged.

The test counts /proc/self/fd before and after one rejected call, so it is skipped where /proc is absent. It passes on this branch and fails against unmodified Lib/socket.py with AssertionError: 7 != 6.

./python -m unittest test.test_socket.BasicTCPTest.testFromFdInvalidArgsDoesNotLeak is OK, and test_socket is green on the free-threading debug build (run=755, skipped=50).

NEWS entry included. No behaviour change on the success path.

@wlkr73
wlkr73 force-pushed the gh-160561-fromfd-leak branch from 06cb5dc to c7af374 Compare October 24, 2026 09:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant