Skip to content

gh-162266: Fix a memory leak in os.fork() on macOS - #162276

Open
maurycy wants to merge 5 commits into
python:mainfrom
maurycy:gh-162266-macos-fork-thread-count
Open

maurycy wants to merge 5 commits into
python:mainfrom
maurycy:gh-162266-macos-fork-thread-count

Conversation

@maurycy

@maurycy maurycy commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

To count threads for the fork DeprecationWarning, os.fork(), os.fork1() and os.forkpty() called task_for_pid() and task_threads() and releases nothing, so each call leaks a VM region and a port reference per thread.

The PR instead reads pti_threadnum from proc_pidinfo(), so there's nothing to release.

Measured with the repro from the issue, counting Mach Message regions with vmmap.

This is going to need backport, possibly dating 3.13 or even 3.12 (security only)?

Details

I think this is the fix, given that we don't need a port, only the count.

We already use proc_pidinfo() (available since 10.5 (2007)):

int ret = proc_pidinfo(pid_list[i], PROC_PIDTBSDINFO, 0,

int size = proc_pidinfo(unwinder->handle.pid, PROC_PIDTHREADID64INFO,

That said, to be honest, the alternative fixes are:

  • keeping task_for_pid() and task_threads(), then deallocate thread ports, list, and task ports. There are three things to release and I don't think it works in the App Sandbox. Also: should we use task_for_pid() for the self process?
  • use task_threads(mach_task_self(), ...) and deallocate thread ports and the thread list. I don't think that we could use task_info() here?
`task_threads(mach_task_self(), ...)` example
mach_port_t self = mach_task_self();
thread_act_array_t threads;
mach_msg_type_number_t n;
if (task_threads(self, &threads, &n) == KERN_SUCCESS) {
    num_python_threads = n;
    for (mach_msg_type_number_t i = 0; i < n; i++) {
        mach_port_deallocate(self, threads[i]);
    }
    vm_deallocate(self, (vm_address_t)threads, n * sizeof(thread_act_t));
}

Where:

My other problem is that the alternatives are easy to get wrong (eg: found googletest having this problem, too.)

@maurycy

maurycy commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

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