Skip to content

_interpchannels: stack-use-after-return in _waiting_release() when send(timeout=...) times out on a closed channel #162656

Backlog

Description

@xuziqiang98

Crash report

_interpchannels.send(cid, obj, timeout=...) goes through channel_send_wait(), which keeps a _waiting_t and its lock on the sender's stack. The comment above it says:

    // We use a stack variable here, so we must ensure that &waiting
    // is not held by any channel item at the point this function exits.

That invariant can be broken:

  1. the receiver pops the item and is still busy deserializing it, so the item is gone from the queue but the receiver has not reached _waiting_release() yet;
  2. another thread closes the channel;
  3. the sender's timeout expires.

The timeout path calls channel_clear_sent(), which finds the channel closed and returns at once; its assert(waiting->status == WAITING_RELEASED) is not true at this point and does nothing in release builds. _waiting_finish_releasing() returns at once too, because the status is still WAITING_ACQUIRED. The sender returns, its frame (including waiting) is gone, and _waiting_clear() frees the lock. When the receiver finally calls _waiting_release(waiting, 1), it writes into the dead frame.

Reproducer

Single file, uses the private _interpchannels and _interpreters modules. The receiver is slow on purpose: unpickling the sent object sleeps for a while after the item has been popped.

import sys
import threading
import time

import _interpchannels as ch
import _interpreters as interp

DELAY = 1.0    # receiver sleeps this long while deserializing the item
TIMEOUT = 0.5  # sender gives up after this long


class Slow:
    """On the receiving side pickle calls __init__(), which reports that the
    item has been popped and then sleeps for a while."""

    def __init__(self, delay=0.0, notify=None):
        self._delay = delay
        self._notify = notify

    def __reduce__(self):
        return (Slow, (self._delay, self._notify))


# pickle looks the class up as "poc_slowmod.Slow"; make that importable here.
Slow.__module__ = "poc_slowmod"
Slow.__qualname__ = "Slow"
sys.modules["poc_slowmod"] = sys.modules["__main__"]

RECEIVER = """
import sys, time, types
import _interpchannels as ch

mod = types.ModuleType("poc_slowmod")
class Slow:
    def __init__(self, delay, notify):
        if notify is not None:
            ch.send(notify, b"popped", blocking=False)  # item is popped
            time.sleep(delay)                           # stay inside the deserializer
mod.Slow = Slow
sys.modules["poc_slowmod"] = mod

sentinel = object()
while ch.recv(CID, sentinel) is sentinel:   # pops the item, then unpickles it
    time.sleep(0.00005)
"""


def main():
    # Warm up the pickle path in the sending interpreter first.
    warm = ch.create()
    ch.send(warm, Slow(), blocking=False)
    sentinel = object()
    assert ch.recv(warm, sentinel) is not sentinel

    data = ch.create()
    notify = ch.create()

    other = interp.create()
    code = RECEIVER.replace("CID", str(int(data)))
    threading.Thread(
        target=interp.run_string, args=(other, code), daemon=True).start()

    def closer():
        deadline = time.monotonic() + 10.0
        while ch.get_count(notify) == 0:
            if time.monotonic() > deadline:
                return
            time.sleep(0.0002)
        # The receiver has popped the item and is sleeping inside the
        # deserializer.  Closing the channel now makes the sender's
        # channel_clear_sent() give up without releasing the sender's lock.
        ch.close(data)

    threading.Thread(target=closer, daemon=True).start()

    try:
        ch.send(data, Slow(DELAY, int(notify)), timeout=TIMEOUT)
    except TimeoutError as exc:
        print(f"sender timed out: {exc}", flush=True)

    time.sleep(DELAY + 0.5)   # give the receiver time to hit the stale pointer


main()

Run it against an ASan build with stack-use-after-return detection on:

ASAN_OPTIONS=detect_leaks=0:detect_stack_use_after_return=1 python poc.py

Output

3.15.2, built from the official tarball with --with-address-sanitizer:

sender timed out: timed out
ERROR: AddressSanitizer: stack-use-after-return
WRITE of size 4 at 0x7fc027442ca8 thread T1
    #0 _waiting_release Modules/_interpchannelsmodule.c:509:21
    #1 channel_recv Modules/_interpchannelsmodule.c:1968:9
    #2 channelsmod_recv Modules/_interpchannelsmodule.c:3279:15
    ...
Address 0x7fc027442ca8 is located in stack of thread T0 at offset 40 in frame
    #0 channel_send_wait Modules/_interpchannelsmodule.c:1851

  This frame has 1 object(s):
    [32, 56) 'waiting' (line 1854) <== Memory access at offset 40 is inside this variable

The line numbers are the same on main (4b66b87).

The error is timing dependent: I got it in 40 of 47 runs (about 6 in 7) in total, across 3.14.10, 3.15.2, 3.16.0a2 and main. Without detect_stack_use_after_return=1, an uninstrumented 3.16.0a2 build segfaulted in 3 of 5 runs.

3.13 has the same channel_send_wait() code, but _interpchannels.send() only accepts cross-interpreter shareable objects there (no pickle fallback), so this reproducer cannot make the receiver slow enough; I did not test 3.13.

Analysis

Modules/_interpchannelsmodule.c, main:

    /* Wait until the object is received. */
    if (wait_for_lock(waiting.mutex, timeout) < 0) {
        assert(PyErr_Occurred());
        _waiting_finish_releasing(&waiting);        /* returns: status is still ACQUIRED */
        /* The send() call is failing now, so make sure the item
           won't be received. */
        channel_clear_sent(channels, cid, &waiting);
        assert(waiting.status == WAITING_RELEASED); /* not true, no-op in release builds */
        if (!waiting.received) {
            res = -1;
            goto finally;
        }
        ...
    }
    ...
finally:
    _waiting_clear(&waiting);                       /* frees waiting.mutex; frame dies */
    return res;

channel_clear_sent():

    int err = _channels_lookup(channels, cid, &mutex, &chan);
    if (err != 0) {
        // The channel was already closed, etc.
        assert(waiting->status == WAITING_RELEASED);
        return;  // Ignore the error.
    }

Neither path releases the sender's _waiting_t in this situation, so the receiver's later _waiting_release(waiting, 1) in channel_recv() operates on a _waiting_t that no longer exists.

Reachability

Only through the private module: _interpchannels.send(..., timeout=...) and send_buffer(). The public concurrent.interpreters.Queue never passes a timeout to the channel (_queues.put() ignores block and timeout).

CPython versions tested on:

3.14, 3.15, 3.16, CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.15.2 (main, Nov 25 2026, 20:06:37) [Clang 18.1.3 (1ubuntu1)]

Activity

  1. added
    type-crash
    on Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulestopic-subinterpreterstype-crash

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions