← 输入框|github.com|刷新
Skip to content

Free-threaded bytearray construction can crash when the source list is concurrently modified #162822

Backlog

Description

@shashankrxj

Bug report

Description

In a free-threaded CPython build, constructing a bytearray from an exact list while another thread concurrently replaces elements in that list can cause a segmentation fault.

The issue appears to be in the exact-list fast path of bytearray___init___impl() in Objects/bytearrayobject.c.

In the tested checkout, the relevant code is around lines 1116–1141:

if (PyList_CheckExact(arg) || PyTuple_CheckExact(arg)) {
    Py_ssize_t size = PySequence_Fast_GET_SIZE(arg);
    if (PyByteArray_Resize((PyObject *)self, size) < 0) {
        return -1;
    }
    PyObject **items = PySequence_Fast_ITEMS(arg);
    char *s = PyByteArray_AS_STRING(self);

    for (Py_ssize_t i = 0; i < size; i++) {
        int value;
        if (!PyLong_CheckExact(items[i])) {
            /* Resize to 0 and go through slowpath */
            ...
            goto slowpath;
        }
        int rc = _getbytevalue(items[i], &value);
        ...
        s[i] = value;
    }
    return 0;
}

The constructor accesses list elements through PySequence_Fast_ITEMS(arg) without acquiring an independent strong reference to each element.

In a free-threaded build, another thread can replace a list element while the constructor is accessing it. This may allow the previous element to be deallocated while its pointer is still being used.

Minimal reproducer

Save the following as repro_bytearray_list_race.py:

#!/usr/bin/env python3

import argparse
import sys
import threading

parser = argparse.ArgumentParser()
parser.add_argument("--seconds", type=int, default=60)
parser.add_argument("--readers", type=int, default=4)
args = parser.parse_args()

if args.seconds <= 0 or args.readers <= 0:
    parser.error("--seconds and --readers must be positive")

gil_check = getattr(sys, "_is_gil_enabled", None)
gil_enabled = gil_check() if gil_check is not None else None

print("Python:", sys.version, flush=True)
print(
    "GIL enabled:",
    gil_enabled if gil_enabled is not None else "unknown (API unavailable)",
    flush=True,
)

if gil_enabled is not False:
    print(
        "WARNING: The GIL is enabled or its status could not be "
        "confirmed. This run does not verify the free-threaded case.",
        flush=True,
    )

# Use a large heap-allocated integer rather than a cached small integer.
base = 1 << 1000
source = [base]

stop = threading.Event()
start = threading.Event()

counts = {
    "writer": 0,
    **{f"reader-{i}": 0 for i in range(args.readers)},
}

errors = []
error_lock = threading.Lock()


def record_error(worker, exc):
    with error_lock:
        errors.append(f"{worker}: {type(exc).__name__}: {exc}")
    stop.set()


def writer():
    n = base

    try:
        start.wait()

        while not stop.is_set():
            # Replace the existing element without changing list size.
            source[0] = n
            n += 1
            counts["writer"] += 1

    except BaseException as exc:
        record_error("writer", exc)


def reader(index):
    name = f"reader-{index}"

    try:
        start.wait()

        while not stop.is_set():
            try:
                bytearray(source)
            except ValueError:
                # Expected because the integer is outside the byte range.
                pass

            counts[name] += 1

    except BaseException as exc:
        record_error(name, exc)


threads = [
    threading.Thread(target=writer, name="list-writer")
]

threads.extend(
    threading.Thread(
        target=reader,
        args=(i,),
        name=f"bytearray-reader-{i}",
    )
    for i in range(args.readers)
)

started = []

for thread in threads:
    try:
        thread.start()
        started.append(thread)
    except RuntimeError as exc:
        print(f"Could not start {thread.name}: {exc}", flush=True)
        stop.set()
        break

start.set()

writer_started = threads[0] in started
reader_count = sum(
    thread in started for thread in threads[1:]
)

if not writer_started or reader_count == 0:
    stop.set()
else:
    stop.wait(args.seconds)

stop.set()

for thread in started:
    thread.join()

print("\n========== RESULTS ==========")
print("Writer replacements:", counts["writer"])
print(
    "Constructor attempts:",
    sum(counts[f"reader-{i}"] for i in range(args.readers)),
)
print(
    "Per-reader attempts:",
    [counts[f"reader-{i}"] for i in range(args.readers)],
)
print("Unexpected Python exceptions:", errors)
print("Final list length:", len(source))
print("=============================")

Steps to reproduce

  1. Build CPython with free-threading and AddressSanitizer enabled.
  2. Save the reproducer as repro_bytearray_list_race.py alongside the CPython python executable.
  3. Run with the GIL disabled:
ASAN_OPTIONS=detect_leaks=0:halt_on_error=1:abort_on_error=1 \
PYTHON_GIL=0 ./python -X faulthandler repro_bytearray_list_race.py --seconds 15
  1. Observe whether the interpreter crashes during concurrent list replacement and bytearray(source) construction.
  2. Run the same reproducer with the GIL enabled as a control:
ASAN_OPTIONS=detect_leaks=0:halt_on_error=1:abort_on_error=1 \
PYTHON_GIL=1 ./python repro_bytearray_list_race.py --seconds 5

The race is timing-dependent, so the free-threaded test may need to be repeated if it does not crash immediately.

Actual behaviour

On the tested free-threaded CPython build, the reproducer caused a segmentation fault during bytearray(source) construction.

AddressSanitizer reported a SEGV caused by an invalid read.

The relevant stack trace was:

PyType_HasFeature
PyLong_AsLongAndOverflow
_getbytevalue
bytearray___init___impl

A separate instrumented diagnostic run recorded the following sequence:

CAPTURE 0x7f638a0541b0
DEALLOC 0x7f638a0541b0
WRITER: replaced source[0]
DEREF  0x7f638a0541b0
LONG_AS_ENTRY 0x7f638a0541b0

The same PyLong pointer received by _getbytevalue() was passed to long_dealloc() before conversion attempted to access it.

The process subsequently crashed while inspecting the object's type metadata.

The GIL-enabled control test completed without crashing in the tested run.

Expected behaviour

Constructing a bytearray from a list should not result in a segmentation fault or invalid memory access when another thread concurrently replaces an element.

The constructor should ensure that source elements remain valid while they are accessed and converted.

Suspected cause

The exact-list fast path in bytearray___init___impl() obtains the underlying list item array using PySequence_Fast_ITEMS(arg).

The elements are subsequently accessed through items[i] without acquiring independent strong references.

In a free-threaded build, concurrent replacement of a list element can release the previous object while the constructor is still using its pointer.

The instrumented diagnostic run supports this borrowed-reference lifetime violation.

CPython versions tested on:

3.16

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Nov 28, 2026
  2. added
    interpreter-core
    and removed on Nov 28, 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

    interpreter-coretopic-free-threadingtype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions