Skip to content

Commit

Permalink
Towards soundness of PyByteArrayMethods::to_vec
Browse files Browse the repository at this point in the history
In free-threaded Python, to_vec needs to make sure to run inside a critical
section so that no other Python thread is mutating the bytearray causing UB.

See also #4736
  • Loading branch information
robsdedude committed Nov 29, 2024
1 parent b308ffa commit 982ac64
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/types/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::err::{PyErr, PyResult};
use crate::ffi_ptr_ext::FfiPtrExt;
use crate::instance::{Borrowed, Bound};
use crate::py_result_ext::PyResultExt;
use crate::sync::with_critical_section;
use crate::types::any::PyAnyMethods;
use crate::{ffi, PyAny, Python};
use std::slice;
Expand Down Expand Up @@ -152,7 +153,7 @@ pub trait PyByteArrayMethods<'py>: crate::sealed::Sealed {
/// using the slice.
///
/// As a result, this slice should only be used for short-lived operations without executing any
/// Python code, such as copying into a Vec.
/// Python code, such as copying into a Vec. For free-threaded Python support see also [`with_critical_section`].
///
/// # Examples
///
Expand Down Expand Up @@ -295,7 +296,7 @@ impl<'py> PyByteArrayMethods<'py> for Bound<'py, PyByteArray> {
}

fn to_vec(&self) -> Vec<u8> {
unsafe { self.as_bytes() }.to_vec()
with_critical_section(self, || unsafe { self.as_bytes() }.to_vec())
}

fn resize(&self, len: usize) -> PyResult<()> {
Expand Down

0 comments on commit 982ac64

Please sign in to comment.