diff --git a/Include/internal/pycore_bytesobject.h b/Include/internal/pycore_bytesobject.h index e709940ad984316..8756c46328c5ff2 100644 --- a/Include/internal/pycore_bytesobject.h +++ b/Include/internal/pycore_bytesobject.h @@ -19,6 +19,50 @@ extern PyObject* _PyBytes_FormatEx( * reference rather than modifying its first argument in place. */ extern PyObject* _PyBytes_Concat(PyObject *a, PyObject *b); +/* Copy a bytearray while holding its lock. */ +static inline PyObject * +_PyBytes_FromByteArray(PyObject *op) +{ + PyObject *bytes; + Py_BEGIN_CRITICAL_SECTION(op); + bytes = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(op), + PyByteArray_GET_SIZE(op)); + Py_END_CRITICAL_SECTION(); + return bytes; +} + +/* If the bytearray has exactly one byte, store it in *p. Return the size + * of the bytearray. */ +static inline Py_ssize_t +_PyByteArray_GetByte(PyObject *op, char *p) +{ + Py_ssize_t size; + Py_BEGIN_CRITICAL_SECTION(op); + size = PyByteArray_GET_SIZE(op); + if (size == 1) { + *p = PyByteArray_AS_STRING(op)[0]; + } + Py_END_CRITICAL_SECTION(); + return size; +} + +/* Copy at most maxlen bytes of the bytearray into dest, which may overlap + * the bytearray's own storage. Return the size of the bytearray, which can + * be larger than maxlen. */ +static inline Py_ssize_t +_PyByteArray_CopyTo(PyObject *op, char *dest, Py_ssize_t maxlen) +{ + Py_ssize_t size; + Py_BEGIN_CRITICAL_SECTION(op); + size = PyByteArray_GET_SIZE(op); + Py_ssize_t n = Py_MIN(size, maxlen); + if (n > 0) { + memmove(dest, PyByteArray_AS_STRING(op), n); + } + Py_END_CRITICAL_SECTION(); + return size; +} + extern PyObject* _PyBytes_FromHex( PyObject *string, int use_bytearray); diff --git a/Include/internal/pycore_long.h b/Include/internal/pycore_long.h index fb5622c99f7a135..a2a648b96fc248e 100644 --- a/Include/internal/pycore_long.h +++ b/Include/internal/pycore_long.h @@ -92,6 +92,7 @@ static inline PyObject* _PyLong_FromUnsignedChar(unsigned char i) PyAPI_DATA(double) _PyLong_Frexp(PyLongObject *a, int64_t *e); extern PyObject* _PyLong_FromBytes(const char *, Py_ssize_t, int); +extern PyObject* _PyLong_FromByteArrayString(PyObject *, int); // _PyLong_DivmodNear. Given integers a and b, compute the nearest // integer q to the exact quotient a / b, rounding to the nearest even integer diff --git a/Lib/test/clinic.test.c b/Lib/test/clinic.test.c index 3b59db65f23b6f6..b7c56f713bb268d 100644 --- a/Lib/test/clinic.test.c +++ b/Lib/test/clinic.test.c @@ -561,14 +561,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) a = PyBytes_AS_STRING(args[0])[0]; } else if (PyByteArray_Check(args[0])) { - if (PyByteArray_GET_SIZE(args[0]) != 1) { + Py_ssize_t a_size = _PyByteArray_GetByte(args[0], &a); + if (a_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 1 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[0])); + "not a bytearray object of length %zd", a_size); goto exit; } - a = PyByteArray_AS_STRING(args[0])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 1", "a byte string of length 1", args[0]); @@ -588,14 +587,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) b = PyBytes_AS_STRING(args[1])[0]; } else if (PyByteArray_Check(args[1])) { - if (PyByteArray_GET_SIZE(args[1]) != 1) { + Py_ssize_t b_size = _PyByteArray_GetByte(args[1], &b); + if (b_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 2 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[1])); + "not a bytearray object of length %zd", b_size); goto exit; } - b = PyByteArray_AS_STRING(args[1])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 2", "a byte string of length 1", args[1]); @@ -615,14 +613,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) c = PyBytes_AS_STRING(args[2])[0]; } else if (PyByteArray_Check(args[2])) { - if (PyByteArray_GET_SIZE(args[2]) != 1) { + Py_ssize_t c_size = _PyByteArray_GetByte(args[2], &c); + if (c_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 3 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[2])); + "not a bytearray object of length %zd", c_size); goto exit; } - c = PyByteArray_AS_STRING(args[2])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 3", "a byte string of length 1", args[2]); @@ -642,14 +639,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) d = PyBytes_AS_STRING(args[3])[0]; } else if (PyByteArray_Check(args[3])) { - if (PyByteArray_GET_SIZE(args[3]) != 1) { + Py_ssize_t d_size = _PyByteArray_GetByte(args[3], &d); + if (d_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 4 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[3])); + "not a bytearray object of length %zd", d_size); goto exit; } - d = PyByteArray_AS_STRING(args[3])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 4", "a byte string of length 1", args[3]); @@ -669,14 +665,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) e = PyBytes_AS_STRING(args[4])[0]; } else if (PyByteArray_Check(args[4])) { - if (PyByteArray_GET_SIZE(args[4]) != 1) { + Py_ssize_t e_size = _PyByteArray_GetByte(args[4], &e); + if (e_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 5 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[4])); + "not a bytearray object of length %zd", e_size); goto exit; } - e = PyByteArray_AS_STRING(args[4])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 5", "a byte string of length 1", args[4]); @@ -696,14 +691,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) f = PyBytes_AS_STRING(args[5])[0]; } else if (PyByteArray_Check(args[5])) { - if (PyByteArray_GET_SIZE(args[5]) != 1) { + Py_ssize_t f_size = _PyByteArray_GetByte(args[5], &f); + if (f_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 6 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[5])); + "not a bytearray object of length %zd", f_size); goto exit; } - f = PyByteArray_AS_STRING(args[5])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 6", "a byte string of length 1", args[5]); @@ -723,14 +717,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) g = PyBytes_AS_STRING(args[6])[0]; } else if (PyByteArray_Check(args[6])) { - if (PyByteArray_GET_SIZE(args[6]) != 1) { + Py_ssize_t g_size = _PyByteArray_GetByte(args[6], &g); + if (g_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 7 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[6])); + "not a bytearray object of length %zd", g_size); goto exit; } - g = PyByteArray_AS_STRING(args[6])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 7", "a byte string of length 1", args[6]); @@ -750,14 +743,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) h = PyBytes_AS_STRING(args[7])[0]; } else if (PyByteArray_Check(args[7])) { - if (PyByteArray_GET_SIZE(args[7]) != 1) { + Py_ssize_t h_size = _PyByteArray_GetByte(args[7], &h); + if (h_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 8 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[7])); + "not a bytearray object of length %zd", h_size); goto exit; } - h = PyByteArray_AS_STRING(args[7])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 8", "a byte string of length 1", args[7]); @@ -777,14 +769,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) i = PyBytes_AS_STRING(args[8])[0]; } else if (PyByteArray_Check(args[8])) { - if (PyByteArray_GET_SIZE(args[8]) != 1) { + Py_ssize_t i_size = _PyByteArray_GetByte(args[8], &i); + if (i_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 9 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[8])); + "not a bytearray object of length %zd", i_size); goto exit; } - i = PyByteArray_AS_STRING(args[8])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 9", "a byte string of length 1", args[8]); @@ -804,14 +795,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) j = PyBytes_AS_STRING(args[9])[0]; } else if (PyByteArray_Check(args[9])) { - if (PyByteArray_GET_SIZE(args[9]) != 1) { + Py_ssize_t j_size = _PyByteArray_GetByte(args[9], &j); + if (j_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 10 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[9])); + "not a bytearray object of length %zd", j_size); goto exit; } - j = PyByteArray_AS_STRING(args[9])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 10", "a byte string of length 1", args[9]); @@ -831,14 +821,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) k = PyBytes_AS_STRING(args[10])[0]; } else if (PyByteArray_Check(args[10])) { - if (PyByteArray_GET_SIZE(args[10]) != 1) { + Py_ssize_t k_size = _PyByteArray_GetByte(args[10], &k); + if (k_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 11 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[10])); + "not a bytearray object of length %zd", k_size); goto exit; } - k = PyByteArray_AS_STRING(args[10])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 11", "a byte string of length 1", args[10]); @@ -858,14 +847,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) l = PyBytes_AS_STRING(args[11])[0]; } else if (PyByteArray_Check(args[11])) { - if (PyByteArray_GET_SIZE(args[11]) != 1) { + Py_ssize_t l_size = _PyByteArray_GetByte(args[11], &l); + if (l_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 12 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[11])); + "not a bytearray object of length %zd", l_size); goto exit; } - l = PyByteArray_AS_STRING(args[11])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 12", "a byte string of length 1", args[11]); @@ -885,14 +873,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) m = PyBytes_AS_STRING(args[12])[0]; } else if (PyByteArray_Check(args[12])) { - if (PyByteArray_GET_SIZE(args[12]) != 1) { + Py_ssize_t m_size = _PyByteArray_GetByte(args[12], &m); + if (m_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 13 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[12])); + "not a bytearray object of length %zd", m_size); goto exit; } - m = PyByteArray_AS_STRING(args[12])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 13", "a byte string of length 1", args[12]); @@ -912,14 +899,13 @@ test_char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) n = PyBytes_AS_STRING(args[13])[0]; } else if (PyByteArray_Check(args[13])) { - if (PyByteArray_GET_SIZE(args[13]) != 1) { + Py_ssize_t n_size = _PyByteArray_GetByte(args[13], &n); + if (n_size != 1) { PyErr_Format(PyExc_TypeError, "test_char_converter(): argument 14 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[13])); + "not a bytearray object of length %zd", n_size); goto exit; } - n = PyByteArray_AS_STRING(args[13])[0]; } else { _PyArg_BadArgument("test_char_converter", "argument 14", "a byte string of length 1", args[13]); @@ -936,7 +922,7 @@ static PyObject * test_char_converter_impl(PyObject *module, char a, char b, char c, char d, char e, char f, char g, char h, char i, char j, char k, char l, char m, char n) -/*[clinic end generated code: output=6503d15448e1d4c4 input=e42330417a44feac]*/ +/*[clinic end generated code: output=804e25f65fb146d8 input=e42330417a44feac]*/ /*[clinic input] diff --git a/Lib/test/test_clinic.py b/Lib/test/test_clinic.py index cb4ed55fabbbc1d..42473bf7a2861cd 100644 --- a/Lib/test/test_clinic.py +++ b/Lib/test/test_clinic.py @@ -4736,6 +4736,9 @@ def test_char_converter(self): chars = [b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'0', b'a', b'b', b'c', b'd'] expected = tuple(ord(c) for c in chars) self.assertEqual(ac_tester.char_converter(*chars), expected) + self.assertEqual(ac_tester.char_converter(*map(bytearray, chars)), expected) + with self.assertRaisesRegex(TypeError, 'bytearray object of length 2'): + ac_tester.char_converter(bytearray(b'ab')) def test_unsigned_char_converter(self): from _testcapi import UCHAR_MAX diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index eff0e95c3af7f47..69c43725997ba08 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -451,6 +451,8 @@ def __bytes__(self): fb = FakeBytes() testcommon(b"%b", b"abc", b"abc") testcommon(b"%b", bytearray(b"def"), b"def") + testcommon(b"%4.2b", bytearray(b"def"), b" de") + testcommon(b"%-4.0b", bytearray(b"def"), b" ") testcommon(b"%b", fb, b"123") testcommon(b"%b", memoryview(b"abc"), b"abc") # # %s is an alias for %b -- should only be used for Py2/3 code diff --git a/Lib/test/test_free_threading/test_bytes_object.py b/Lib/test/test_free_threading/test_bytes_object.py index a9017bac6de0295..38e003703e5a96e 100644 --- a/Lib/test/test_free_threading/test_bytes_object.py +++ b/Lib/test/test_free_threading/test_bytes_object.py @@ -1,3 +1,4 @@ +import struct import unittest from threading import Thread, Barrier, Event from test.support import threading_helper @@ -54,6 +55,33 @@ def reader(): threading_helper.run_concurrently([writer] + [reader] * 4) + def test_read_bytearray_during_resize(self): + # Each read must see one complete slice assignment, even if the + # writer replaces the backing storage. + short = b'1' + long = b'2' * 512 # Below the minimum configurable int digit limit. + data = bytearray(short) + pack_string = struct.Struct('1024s').pack + pack_pascal = struct.Struct('1024p').pack + strings = (pack_string(short), pack_string(long)) + pascals = (pack_pascal(short), pack_pascal(long)) + numbers = (int(short), int(long)) + + def writer(): + for _ in range(2000): + data[:] = long + data[:] = short + + def reader(): + for _ in range(2000): + self.assertIn(b'%b' % data, (short, long)) + self.assertIn(pack_string(data), strings) + self.assertIn(pack_pascal(data), pascals) + self.assertIn(int(data), numbers) + self.assertIn(int(data, 10), numbers) + + threading_helper.run_concurrently([writer, reader, reader]) + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-11-32-09.gh-issue-157601.K7mR2w.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-11-32-09.gh-issue-157601.K7mR2w.rst new file mode 100644 index 000000000000000..b315003bd5ce00e --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-26-11-32-09.gh-issue-157601.K7mR2w.rst @@ -0,0 +1,3 @@ +Fix unsafe reads of :class:`bytearray` storage during concurrent mutation +in free-threaded builds. Also prevent use-after-free when :func:`compile` +or :class:`int` calls Python code that resizes its :class:`bytearray` input. diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c index 193c60a1afee85c..cb629b2cb6141b6 100644 --- a/Modules/_ctypes/cfield.c +++ b/Modules/_ctypes/cfield.c @@ -9,6 +9,7 @@ #endif #include "pycore_bitutils.h" // _Py_bswap32() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_call.h" // _PyObject_CallNoArgs() #include @@ -1057,14 +1058,14 @@ c_set(void *ptr, PyObject *value, Py_ssize_t size) _RET(value); } if (PyByteArray_Check(value)) { - if (PyByteArray_GET_SIZE(value) != 1) { + Py_ssize_t len = _PyByteArray_GetByte(value, (char *)ptr); + if (len != 1) { PyErr_Format(PyExc_TypeError, "one character bytes, bytearray, or an integer " "in range(256) expected, not bytearray of length %zd", - PyByteArray_GET_SIZE(value)); + len); return NULL; } - *(char *)ptr = PyByteArray_AS_STRING(value)[0]; _RET(value); } if (PyLong_Check(value)) { diff --git a/Modules/_pickle.c b/Modules/_pickle.c index 6c9e97eaeba7a59..092e9f823f20fa8 100644 --- a/Modules/_pickle.c +++ b/Modules/_pickle.c @@ -2793,9 +2793,16 @@ save_bytearray(PickleState *state, PicklerObject *self, PyObject *obj) return status; } else { - return _save_bytearray_data(state, self, obj, - PyByteArray_AS_STRING(obj), - PyByteArray_GET_SIZE(obj)); + /* Export the buffer so the data cannot be freed by a resize + while it is written. */ + Py_buffer view; + if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) { + return -1; + } + int rc = _save_bytearray_data(state, self, obj, + (const char *)view.buf, view.len); + PyBuffer_Release(&view); + return rc; } } diff --git a/Modules/_ssl.c b/Modules/_ssl.c index 2e4c67b4058bc3e..3fce93723aac5f9 100644 --- a/Modules/_ssl.c +++ b/Modules/_ssl.c @@ -4722,39 +4722,12 @@ typedef struct { } _PySSLPasswordInfo; static int -_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password, - const char *bad_type_error) +_pwinfo_copy(_PySSLPasswordInfo *pw_info, const char *data, Py_ssize_t size) { - /* Set the password and size fields of a _PySSLPasswordInfo struct - from a unicode, bytes, or byte array object. - The password field will be dynamically allocated and must be freed - by the caller */ - PyObject *password_bytes = NULL; - const char *data = NULL; - Py_ssize_t size; - - if (PyUnicode_Check(password)) { - password_bytes = PyUnicode_AsUTF8String(password); - if (!password_bytes) { - goto error; - } - data = PyBytes_AS_STRING(password_bytes); - size = PyBytes_GET_SIZE(password_bytes); - } else if (PyBytes_Check(password)) { - data = PyBytes_AS_STRING(password); - size = PyBytes_GET_SIZE(password); - } else if (PyByteArray_Check(password)) { - data = PyByteArray_AS_STRING(password); - size = PyByteArray_GET_SIZE(password); - } else { - PyErr_SetString(PyExc_TypeError, bad_type_error); - goto error; - } - - if (size > (Py_ssize_t)INT_MAX) { + if (size > INT_MAX) { PyErr_Format(PyExc_ValueError, "password cannot be longer than %d bytes", INT_MAX); - goto error; + return 0; } PyMem_Free(pw_info->password); @@ -4762,16 +4735,39 @@ _pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password, if (!pw_info->password) { PyErr_SetString(PyExc_MemoryError, "unable to allocate password buffer"); - goto error; + return 0; } memcpy(pw_info->password, data, size); pw_info->size = (int)size; - - Py_XDECREF(password_bytes); return 1; +} -error: - Py_XDECREF(password_bytes); +static int +_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject *password, + const char *bad_type_error) +{ + /* The caller must free the allocated password buffer. */ + if (PyUnicode_Check(password)) { + PyObject *bytes = PyUnicode_AsUTF8String(password); + if (bytes == NULL) { + return 0; + } + int ok = _pwinfo_copy(pw_info, PyBytes_AS_STRING(bytes), + PyBytes_GET_SIZE(bytes)); + Py_DECREF(bytes); + return ok; + } else if (PyBytes_Check(password)) { + return _pwinfo_copy(pw_info, PyBytes_AS_STRING(password), + PyBytes_GET_SIZE(password)); + } else if (PyByteArray_Check(password)) { + int ok; + Py_BEGIN_CRITICAL_SECTION(password); + ok = _pwinfo_copy(pw_info, PyByteArray_AS_STRING(password), + PyByteArray_GET_SIZE(password)); + Py_END_CRITICAL_SECTION(); + return ok; + } + PyErr_SetString(PyExc_TypeError, bad_type_error); return 0; } diff --git a/Modules/_struct.c b/Modules/_struct.c index fad026ac8a4652e..eb67b0cf1ae4890 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -2388,58 +2388,31 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, Py_ssize_t j = code->repeat; while (j--) { PyObject *v = args[i++]; - if (strcmp(e->format, "s") == 0) { + int is_pascal = strcmp(e->format, "p") == 0; + if (is_pascal || strcmp(e->format, "s") == 0) { + Py_ssize_t maxlen = is_pascal ? Py_MAX(code->size - 1, 0) + : code->size; + // Don't advance past the buffer for a zero-width field. + char *dest = res + (is_pascal && code->size > 0); Py_ssize_t n; - int isstring; - const void *p; - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(state->StructError, - "argument for 's' must be a bytes object"); - return -1; + if (PyBytes_Check(v)) { + n = Py_MIN(PyBytes_GET_SIZE(v), maxlen); + if (n > 0) { + memmove(dest, PyBytes_AS_STRING(v), n); + } } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); + else if (PyByteArray_Check(v)) { + n = _PyByteArray_CopyTo(v, dest, maxlen); + n = Py_MIN(n, maxlen); } else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (n > code->size) - n = code->size; - if (n > 0) - memmove(res, p, n); - } else if (strcmp(e->format, "p") == 0) { - Py_ssize_t n; - int isstring; - const void *p; - isstring = PyBytes_Check(v); - if (!isstring && !PyByteArray_Check(v)) { - PyErr_SetString(state->StructError, - "argument for 'p' must be a bytes object"); + PyErr_Format(state->StructError, + "argument for '%c' must be a bytes object", + is_pascal ? 'p' : 's'); return -1; } - if (isstring) { - n = PyBytes_GET_SIZE(v); - p = PyBytes_AS_STRING(v); - } - else { - n = PyByteArray_GET_SIZE(v); - p = PyByteArray_AS_STRING(v); - } - if (code->size == 0) { - n = 0; - } - else if (n > (code->size - 1)) { - n = code->size - 1; - } - if (n > 0) - memmove(res + 1, p, n); - if (n > 255) - n = 255; - if (n > 0) { - *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); + if (is_pascal && n > 0) { + *res = (unsigned char)Py_MIN(n, 255); } } else { if (e->pack(state, res, v, e) < 0) { diff --git a/Modules/clinic/_testclinic.c.h b/Modules/clinic/_testclinic.c.h index 4527ae213f021e3..d5a09c81ea1593f 100644 --- a/Modules/clinic/_testclinic.c.h +++ b/Modules/clinic/_testclinic.c.h @@ -6,6 +6,7 @@ preserve # include "pycore_gc.h" // PyGC_Head #endif #include "pycore_abstract.h" // _PyNumber_Index() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION() #include "pycore_long.h" // _PyLong_UnsignedShort_Converter() #include "pycore_modsupport.h" // _PyArg_CheckPositional() @@ -306,14 +307,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) a = PyBytes_AS_STRING(args[0])[0]; } else if (PyByteArray_Check(args[0])) { - if (PyByteArray_GET_SIZE(args[0]) != 1) { + Py_ssize_t a_size = _PyByteArray_GetByte(args[0], &a); + if (a_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 1 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[0])); + "not a bytearray object of length %zd", a_size); goto exit; } - a = PyByteArray_AS_STRING(args[0])[0]; } else { _PyArg_BadArgument("char_converter", "argument 1", "a byte string of length 1", args[0]); @@ -333,14 +333,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) b = PyBytes_AS_STRING(args[1])[0]; } else if (PyByteArray_Check(args[1])) { - if (PyByteArray_GET_SIZE(args[1]) != 1) { + Py_ssize_t b_size = _PyByteArray_GetByte(args[1], &b); + if (b_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 2 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[1])); + "not a bytearray object of length %zd", b_size); goto exit; } - b = PyByteArray_AS_STRING(args[1])[0]; } else { _PyArg_BadArgument("char_converter", "argument 2", "a byte string of length 1", args[1]); @@ -360,14 +359,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) c = PyBytes_AS_STRING(args[2])[0]; } else if (PyByteArray_Check(args[2])) { - if (PyByteArray_GET_SIZE(args[2]) != 1) { + Py_ssize_t c_size = _PyByteArray_GetByte(args[2], &c); + if (c_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 3 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[2])); + "not a bytearray object of length %zd", c_size); goto exit; } - c = PyByteArray_AS_STRING(args[2])[0]; } else { _PyArg_BadArgument("char_converter", "argument 3", "a byte string of length 1", args[2]); @@ -387,14 +385,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) d = PyBytes_AS_STRING(args[3])[0]; } else if (PyByteArray_Check(args[3])) { - if (PyByteArray_GET_SIZE(args[3]) != 1) { + Py_ssize_t d_size = _PyByteArray_GetByte(args[3], &d); + if (d_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 4 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[3])); + "not a bytearray object of length %zd", d_size); goto exit; } - d = PyByteArray_AS_STRING(args[3])[0]; } else { _PyArg_BadArgument("char_converter", "argument 4", "a byte string of length 1", args[3]); @@ -414,14 +411,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) e = PyBytes_AS_STRING(args[4])[0]; } else if (PyByteArray_Check(args[4])) { - if (PyByteArray_GET_SIZE(args[4]) != 1) { + Py_ssize_t e_size = _PyByteArray_GetByte(args[4], &e); + if (e_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 5 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[4])); + "not a bytearray object of length %zd", e_size); goto exit; } - e = PyByteArray_AS_STRING(args[4])[0]; } else { _PyArg_BadArgument("char_converter", "argument 5", "a byte string of length 1", args[4]); @@ -441,14 +437,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) f = PyBytes_AS_STRING(args[5])[0]; } else if (PyByteArray_Check(args[5])) { - if (PyByteArray_GET_SIZE(args[5]) != 1) { + Py_ssize_t f_size = _PyByteArray_GetByte(args[5], &f); + if (f_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 6 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[5])); + "not a bytearray object of length %zd", f_size); goto exit; } - f = PyByteArray_AS_STRING(args[5])[0]; } else { _PyArg_BadArgument("char_converter", "argument 6", "a byte string of length 1", args[5]); @@ -468,14 +463,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) g = PyBytes_AS_STRING(args[6])[0]; } else if (PyByteArray_Check(args[6])) { - if (PyByteArray_GET_SIZE(args[6]) != 1) { + Py_ssize_t g_size = _PyByteArray_GetByte(args[6], &g); + if (g_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 7 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[6])); + "not a bytearray object of length %zd", g_size); goto exit; } - g = PyByteArray_AS_STRING(args[6])[0]; } else { _PyArg_BadArgument("char_converter", "argument 7", "a byte string of length 1", args[6]); @@ -495,14 +489,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) h = PyBytes_AS_STRING(args[7])[0]; } else if (PyByteArray_Check(args[7])) { - if (PyByteArray_GET_SIZE(args[7]) != 1) { + Py_ssize_t h_size = _PyByteArray_GetByte(args[7], &h); + if (h_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 8 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[7])); + "not a bytearray object of length %zd", h_size); goto exit; } - h = PyByteArray_AS_STRING(args[7])[0]; } else { _PyArg_BadArgument("char_converter", "argument 8", "a byte string of length 1", args[7]); @@ -522,14 +515,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) i = PyBytes_AS_STRING(args[8])[0]; } else if (PyByteArray_Check(args[8])) { - if (PyByteArray_GET_SIZE(args[8]) != 1) { + Py_ssize_t i_size = _PyByteArray_GetByte(args[8], &i); + if (i_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 9 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[8])); + "not a bytearray object of length %zd", i_size); goto exit; } - i = PyByteArray_AS_STRING(args[8])[0]; } else { _PyArg_BadArgument("char_converter", "argument 9", "a byte string of length 1", args[8]); @@ -549,14 +541,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) j = PyBytes_AS_STRING(args[9])[0]; } else if (PyByteArray_Check(args[9])) { - if (PyByteArray_GET_SIZE(args[9]) != 1) { + Py_ssize_t j_size = _PyByteArray_GetByte(args[9], &j); + if (j_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 10 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[9])); + "not a bytearray object of length %zd", j_size); goto exit; } - j = PyByteArray_AS_STRING(args[9])[0]; } else { _PyArg_BadArgument("char_converter", "argument 10", "a byte string of length 1", args[9]); @@ -576,14 +567,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) k = PyBytes_AS_STRING(args[10])[0]; } else if (PyByteArray_Check(args[10])) { - if (PyByteArray_GET_SIZE(args[10]) != 1) { + Py_ssize_t k_size = _PyByteArray_GetByte(args[10], &k); + if (k_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 11 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[10])); + "not a bytearray object of length %zd", k_size); goto exit; } - k = PyByteArray_AS_STRING(args[10])[0]; } else { _PyArg_BadArgument("char_converter", "argument 11", "a byte string of length 1", args[10]); @@ -603,14 +593,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) l = PyBytes_AS_STRING(args[11])[0]; } else if (PyByteArray_Check(args[11])) { - if (PyByteArray_GET_SIZE(args[11]) != 1) { + Py_ssize_t l_size = _PyByteArray_GetByte(args[11], &l); + if (l_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 12 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[11])); + "not a bytearray object of length %zd", l_size); goto exit; } - l = PyByteArray_AS_STRING(args[11])[0]; } else { _PyArg_BadArgument("char_converter", "argument 12", "a byte string of length 1", args[11]); @@ -630,14 +619,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) m = PyBytes_AS_STRING(args[12])[0]; } else if (PyByteArray_Check(args[12])) { - if (PyByteArray_GET_SIZE(args[12]) != 1) { + Py_ssize_t m_size = _PyByteArray_GetByte(args[12], &m); + if (m_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 13 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[12])); + "not a bytearray object of length %zd", m_size); goto exit; } - m = PyByteArray_AS_STRING(args[12])[0]; } else { _PyArg_BadArgument("char_converter", "argument 13", "a byte string of length 1", args[12]); @@ -657,14 +645,13 @@ char_converter(PyObject *module, PyObject *const *args, Py_ssize_t nargs) n = PyBytes_AS_STRING(args[13])[0]; } else if (PyByteArray_Check(args[13])) { - if (PyByteArray_GET_SIZE(args[13]) != 1) { + Py_ssize_t n_size = _PyByteArray_GetByte(args[13], &n); + if (n_size != 1) { PyErr_Format(PyExc_TypeError, "char_converter(): argument 14 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[13])); + "not a bytearray object of length %zd", n_size); goto exit; } - n = PyByteArray_AS_STRING(args[13])[0]; } else { _PyArg_BadArgument("char_converter", "argument 14", "a byte string of length 1", args[13]); @@ -5378,4 +5365,4 @@ vc_kwds_vectorcall(PyObject *type, PyObject *const *args, return return_value; } -/*[clinic end generated code: output=2e36c6f796a4ca09 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=5283303429da69e2 input=a9049054013a1b77]*/ diff --git a/Modules/clinic/_testclinic_depr.c.h b/Modules/clinic/_testclinic_depr.c.h index 1652e9223e54f94..47c467350970f00 100644 --- a/Modules/clinic/_testclinic_depr.c.h +++ b/Modules/clinic/_testclinic_depr.c.h @@ -6,6 +6,7 @@ preserve # include "pycore_gc.h" // PyGC_Head #endif #include "pycore_abstract.h" // _PyNumber_Index() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION() #include "pycore_long.h" // _PyLong_UnsignedShort_Converter() #include "pycore_modsupport.h" // _PyArg_CheckPositional() @@ -2682,4 +2683,4 @@ depr_multi(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject * exit: return return_value; } -/*[clinic end generated code: output=abe0af8d8c637c36 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=e7a97fe1501963dc input=a9049054013a1b77]*/ diff --git a/Modules/clinic/_testclinic_kwds.c.h b/Modules/clinic/_testclinic_kwds.c.h index 729ba1b6fa7c3da..bc30ca867e84d20 100644 --- a/Modules/clinic/_testclinic_kwds.c.h +++ b/Modules/clinic/_testclinic_kwds.c.h @@ -6,6 +6,7 @@ preserve # include "pycore_gc.h" // PyGC_Head #endif #include "pycore_abstract.h" // _PyNumber_Index() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_critical_section.h"// Py_BEGIN_CRITICAL_SECTION() #include "pycore_long.h" // _PyLong_UnsignedShort_Converter() #include "pycore_modsupport.h" // _PyArg_CheckPositional() @@ -189,4 +190,4 @@ kwds_with_pos_only_and_stararg(PyObject *module, PyObject *args, PyObject *kwarg return return_value; } -/*[clinic end generated code: output=ad46500147228faf input=a9049054013a1b77]*/ +/*[clinic end generated code: output=96f663aec33b061c input=a9049054013a1b77]*/ diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c index a6063f034463c82..349dc4946bca14c 100644 --- a/Modules/pyexpat.c +++ b/Modules/pyexpat.c @@ -3,6 +3,7 @@ #endif #include "Python.h" +#include "pycore_bytesobject.h" // _PyByteArray_CopyTo() #include "pycore_ceval.h" // _Py_EnterRecursiveCall() #include "pycore_codecs.h" // _PyCodec_LookupTextEncoding() #include "pycore_import.h" // _PyImport_SetModule() @@ -992,23 +993,26 @@ readinst(char *buf, int buf_size, PyObject *meth) { PyObject *str; Py_ssize_t len; - const char *ptr; str = PyObject_CallFunction(meth, "i", buf_size); if (str == NULL) - goto error; + return -1; - if (PyBytes_Check(str)) - ptr = PyBytes_AS_STRING(str); - else if (PyByteArray_Check(str)) - ptr = PyByteArray_AS_STRING(str); + if (PyBytes_Check(str)) { + len = PyBytes_GET_SIZE(str); + if (len <= buf_size) { + memcpy(buf, PyBytes_AS_STRING(str), len); + } + } + else if (PyByteArray_Check(str)) { + len = _PyByteArray_CopyTo(str, buf, buf_size); + } else { PyErr_Format(PyExc_TypeError, "read() did not return a bytes object (type=%.400s)", Py_TYPE(str)->tp_name); goto error; } - len = Py_SIZE(str); if (len > buf_size) { PyErr_Format(PyExc_ValueError, "read() returned too much data: " @@ -1016,7 +1020,6 @@ readinst(char *buf, int buf_size, PyObject *meth) buf_size, len); goto error; } - memcpy(buf, ptr, len); Py_DECREF(str); /* len <= buf_size <= INT_MAX */ return (int)len; diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c index 7a76882e1633e10..05a18f2ef147b1d 100644 --- a/Modules/socketmodule.c +++ b/Modules/socketmodule.c @@ -106,6 +106,7 @@ Local naming conventions: #endif #include "Python.h" +#include "pycore_bytesobject.h" // _PyBytes_FromByteArray() #include "pycore_capsule.h" // _PyCapsule_SetTraverse() #include "pycore_fileutils.h" // _Py_set_inheritable() #include "pycore_moduleobject.h" // _PyModule_GetState @@ -1816,8 +1817,15 @@ idna_converter(PyObject *obj, void *arg) len = PyBytes_Size(obj); } else if (PyByteArray_Check(obj)) { - data->buf = PyByteArray_AsString(obj); - len = PyByteArray_Size(obj); + /* Copy: the name is used after the GIL is released, while + another thread could resize the bytearray. */ + obj2 = _PyBytes_FromByteArray(obj); + if (obj2 == NULL) { + return 0; + } + data->obj = obj2; + data->buf = PyBytes_AS_STRING(obj2); + len = PyBytes_GET_SIZE(obj2); } else if (PyUnicode_Check(obj)) { if (PyUnicode_IS_COMPACT_ASCII(obj)) { diff --git a/Objects/abstract.c b/Objects/abstract.c index 635e1e927f23370..908167b348ea285 100644 --- a/Objects/abstract.c +++ b/Objects/abstract.c @@ -1585,9 +1585,9 @@ PyNumber_Long(PyObject *o) return _PyLong_FromBytes(PyBytes_AS_STRING(o), PyBytes_GET_SIZE(o), 10); - if (PyByteArray_Check(o)) - return _PyLong_FromBytes(PyByteArray_AS_STRING(o), - PyByteArray_GET_SIZE(o), 10); + if (PyByteArray_Check(o)) { + return _PyLong_FromByteArrayString(o, 10); + } if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) { PyObject *bytes; diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index e9264f765a08e6d..8e288a665cdc41e 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -584,14 +584,14 @@ byte_converter(PyObject *arg, Py_ssize_t argidx, PyObject *key, char *p) return 1; } else if (PyByteArray_Check(arg)) { - if (PyByteArray_GET_SIZE(arg) != 1) { + Py_ssize_t size = _PyByteArray_GetByte(arg, p); + if (size != 1) { FORMAT_ERROR(PyExc_TypeError, "%%c requires an integer in range(256) or " "a single byte, not a bytearray object of length %zd", - PyByteArray_GET_SIZE(arg)); + size); return 0; } - *p = PyByteArray_AS_STRING(arg)[0]; return 1; } else if (PyIndex_Check(arg)) { @@ -619,7 +619,7 @@ byte_converter(PyObject *arg, Py_ssize_t argidx, PyObject *key, char *p) static PyObject *_PyBytes_FromBuffer(PyObject *x); static PyObject * -format_obj(PyObject *v, Py_ssize_t argidx, PyObject *key, +format_obj(PyObject *v, Py_ssize_t argidx, PyObject *key, int prec, const char **pbuf, Py_ssize_t *plen) { PyObject *func, *result; @@ -630,9 +630,22 @@ format_obj(PyObject *v, Py_ssize_t argidx, PyObject *key, return Py_NewRef(v); } if (PyByteArray_Check(v)) { - *pbuf = PyByteArray_AS_STRING(v); - *plen = PyByteArray_GET_SIZE(v); - return Py_NewRef(v); + /* Slow path, used when padding is needed. Copy since the caller + uses the data after the lock is released. Lock rather than + export the buffer so a concurrent resize does not fail. */ + Py_BEGIN_CRITICAL_SECTION(v); + Py_ssize_t size = PyByteArray_GET_SIZE(v); + if (prec >= 0 && size > prec) { + size = prec; + } + result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), size); + Py_END_CRITICAL_SECTION(); + if (result == NULL) { + return NULL; + } + *pbuf = PyBytes_AS_STRING(result); + *plen = PyBytes_GET_SIZE(result); + return result; } /* does it support __bytes__? */ func = _PyObject_LookupSpecial(v, &_Py_ID(__bytes__)); @@ -968,7 +981,30 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, case 's': // %s is only for 2/3 code; 3 only code should use %b case 'b': - temp = format_obj(v, argidx, key, &pbuf, &len); + if (PyByteArray_Check(v) && width == -1) { + /* Fast path: copy into the writer while holding the + lock, so a concurrent resize cannot free the data. */ + Py_BEGIN_CRITICAL_SECTION(v); + len = PyByteArray_GET_SIZE(v); + if (prec >= 0 && len > prec) { + len = prec; + } + Py_ssize_t prealloc = fmt - start; + if (len > prealloc) { + res = PyBytesWriter_GrowAndUpdatePointer( + writer, len - prealloc, res); + } + if (res != NULL) { + memcpy(res, PyByteArray_AS_STRING(v), len); + res += len; + } + Py_END_CRITICAL_SECTION(); + if (res == NULL) { + goto error; + } + continue; + } + temp = format_obj(v, argidx, key, prec, &pbuf, &len); if (temp == NULL) goto error; if (prec >= 0 && len > prec) diff --git a/Objects/floatobject.c b/Objects/floatobject.c index e7b904c9b213b87..4e2cb78846c5d85 100644 --- a/Objects/floatobject.c +++ b/Objects/floatobject.c @@ -6,6 +6,7 @@ #include "Python.h" #include "pycore_abstract.h" // _PyNumber_Index() #include "pycore_bitutils.h" // _Py_bswap16() +#include "pycore_bytesobject.h" // _PyBytes_FromByteArray() #include "pycore_dtoa.h" // _Py_dg_dtoa() #include "pycore_floatobject.h" // _PyFloat_FormatAdvancedWriter() #include "pycore_freelist.h" // _Py_FREELIST_FREE(), _Py_FREELIST_POP() @@ -200,8 +201,13 @@ PyFloat_FromString(PyObject *v) len = PyBytes_GET_SIZE(v); } else if (PyByteArray_Check(v)) { - s = PyByteArray_AS_STRING(v); - len = PyByteArray_GET_SIZE(v); + /* Parsing errors may call the bytearray's __repr__. */ + s_buffer = _PyBytes_FromByteArray(v); + if (s_buffer == NULL) { + return NULL; + } + s = PyBytes_AS_STRING(s_buffer); + len = PyBytes_GET_SIZE(s_buffer); } else if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) == 0) { s = (const char *)view.buf; diff --git a/Objects/longobject.c b/Objects/longobject.c index b48328efa2f1b7c..ab81b36323be109 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -4,6 +4,7 @@ #include "Python.h" #include "pycore_bitutils.h" // _Py_popcount32() +#include "pycore_bytesobject.h" // _PyBytes_FromByteArray() #include "pycore_initconfig.h" // _PyStatus_OK() #include "pycore_call.h" // _PyObject_MakeTpCall #include "pycore_freelist.h" // _Py_FREELIST_FREE, _Py_FREELIST_POP @@ -3179,6 +3180,21 @@ _PyLong_FromBytes(const char *s, Py_ssize_t len, int base) return NULL; } +PyObject * +_PyLong_FromByteArrayString(PyObject *op, int base) +{ + /* Long decimal inputs can invoke Python code in _pylong, so don't + retain a pointer into the bytearray while parsing. */ + PyObject *bytes = _PyBytes_FromByteArray(op); + if (bytes == NULL) { + return NULL; + } + PyObject *result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes), + PyBytes_GET_SIZE(bytes), base); + Py_DECREF(bytes); + return result; +} + PyObject * PyLong_FromUnicodeObject(PyObject *u, int base) { @@ -6028,13 +6044,12 @@ long_new_impl(PyTypeObject *type, PyObject *x, PyObject *obase) if (PyUnicode_Check(x)) return PyLong_FromUnicodeObject(x, (int)base); - else if (PyByteArray_Check(x) || PyBytes_Check(x)) { - const char *string; - if (PyByteArray_Check(x)) - string = PyByteArray_AS_STRING(x); - else - string = PyBytes_AS_STRING(x); - return _PyLong_FromBytes(string, Py_SIZE(x), (int)base); + else if (PyBytes_Check(x)) { + return _PyLong_FromBytes(PyBytes_AS_STRING(x), PyBytes_GET_SIZE(x), + (int)base); + } + else if (PyByteArray_Check(x)) { + return _PyLong_FromByteArrayString(x, (int)base); } else { PyErr_SetString(PyExc_TypeError, diff --git a/Objects/stringlib/clinic/transmogrify.h.h b/Objects/stringlib/clinic/transmogrify.h.h index 588fc101dbb5e3e..4b60ad3a61e2824 100644 --- a/Objects/stringlib/clinic/transmogrify.h.h +++ b/Objects/stringlib/clinic/transmogrify.h.h @@ -7,6 +7,7 @@ preserve # include "pycore_runtime.h" // _Py_ID() #endif #include "pycore_abstract.h" // _PyNumber_Index() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_modsupport.h" // _PyArg_UnpackKeywords() PyDoc_STRVAR(stringlib_expandtabs__doc__, @@ -127,14 +128,13 @@ stringlib_ljust(PyObject *self, PyObject *const *args, Py_ssize_t nargs) fillchar = PyBytes_AS_STRING(args[1])[0]; } else if (PyByteArray_Check(args[1])) { - if (PyByteArray_GET_SIZE(args[1]) != 1) { + Py_ssize_t fillchar_size = _PyByteArray_GetByte(args[1], &fillchar); + if (fillchar_size != 1) { PyErr_Format(PyExc_TypeError, "ljust(): argument 2 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[1])); + "not a bytearray object of length %zd", fillchar_size); goto exit; } - fillchar = PyByteArray_AS_STRING(args[1])[0]; } else { _PyArg_BadArgument("ljust", "argument 2", "a byte string of length 1", args[1]); @@ -197,14 +197,13 @@ stringlib_rjust(PyObject *self, PyObject *const *args, Py_ssize_t nargs) fillchar = PyBytes_AS_STRING(args[1])[0]; } else if (PyByteArray_Check(args[1])) { - if (PyByteArray_GET_SIZE(args[1]) != 1) { + Py_ssize_t fillchar_size = _PyByteArray_GetByte(args[1], &fillchar); + if (fillchar_size != 1) { PyErr_Format(PyExc_TypeError, "rjust(): argument 2 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[1])); + "not a bytearray object of length %zd", fillchar_size); goto exit; } - fillchar = PyByteArray_AS_STRING(args[1])[0]; } else { _PyArg_BadArgument("rjust", "argument 2", "a byte string of length 1", args[1]); @@ -267,14 +266,13 @@ stringlib_center(PyObject *self, PyObject *const *args, Py_ssize_t nargs) fillchar = PyBytes_AS_STRING(args[1])[0]; } else if (PyByteArray_Check(args[1])) { - if (PyByteArray_GET_SIZE(args[1]) != 1) { + Py_ssize_t fillchar_size = _PyByteArray_GetByte(args[1], &fillchar); + if (fillchar_size != 1) { PyErr_Format(PyExc_TypeError, "center(): argument 2 must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(args[1])); + "not a bytearray object of length %zd", fillchar_size); goto exit; } - fillchar = PyByteArray_AS_STRING(args[1])[0]; } else { _PyArg_BadArgument("center", "argument 2", "a byte string of length 1", args[1]); @@ -324,4 +322,4 @@ stringlib_zfill(PyObject *self, PyObject *arg) exit: return return_value; } -/*[clinic end generated code: output=8363b4b6cdaad556 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=375d37acfbf2392a input=a9049054013a1b77]*/ diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 309621acdaa3c8c..156125dd342eb21 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -3912,8 +3912,9 @@ PyUnicode_AsEncodedString(PyObject *unicode, return NULL; } - b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), - PyByteArray_GET_SIZE(v)); + /* The codec may still share v; lock it so a concurrent resize + cannot free the data while it is copied. */ + b = _PyBytes_FromByteArray(v); Py_DECREF(v); return b; } diff --git a/PC/clinic/msvcrtmodule.c.h b/PC/clinic/msvcrtmodule.c.h index 7a43daa987b2066..cfb14a334bdb34d 100644 --- a/PC/clinic/msvcrtmodule.c.h +++ b/PC/clinic/msvcrtmodule.c.h @@ -2,6 +2,7 @@ preserve [clinic start generated code]*/ +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_modsupport.h" // _PyArg_CheckPositional() PyDoc_STRVAR(msvcrt_heapmin__doc__, @@ -366,14 +367,13 @@ msvcrt_putch(PyObject *module, PyObject *arg) char_value = PyBytes_AS_STRING(arg)[0]; } else if (PyByteArray_Check(arg)) { - if (PyByteArray_GET_SIZE(arg) != 1) { + Py_ssize_t char_value_size = _PyByteArray_GetByte(arg, &char_value); + if (char_value_size != 1) { PyErr_Format(PyExc_TypeError, "putch(): argument must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(arg)); + "not a bytearray object of length %zd", char_value_size); goto exit; } - char_value = PyByteArray_AS_STRING(arg)[0]; } else { _PyArg_BadArgument("putch", "argument", "a byte string of length 1", arg); @@ -458,14 +458,13 @@ msvcrt_ungetch(PyObject *module, PyObject *arg) char_value = PyBytes_AS_STRING(arg)[0]; } else if (PyByteArray_Check(arg)) { - if (PyByteArray_GET_SIZE(arg) != 1) { + Py_ssize_t char_value_size = _PyByteArray_GetByte(arg, &char_value); + if (char_value_size != 1) { PyErr_Format(PyExc_TypeError, "ungetch(): argument must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE(arg)); + "not a bytearray object of length %zd", char_value_size); goto exit; } - char_value = PyByteArray_AS_STRING(arg)[0]; } else { _PyArg_BadArgument("ungetch", "argument", "a byte string of length 1", arg); @@ -743,4 +742,4 @@ msvcrt_SetErrorMode(PyObject *module, PyObject *arg) #ifndef MSVCRT_GETERRORMODE_METHODDEF #define MSVCRT_GETERRORMODE_METHODDEF #endif /* !defined(MSVCRT_GETERRORMODE_METHODDEF) */ -/*[clinic end generated code: output=58c1771c8b9a209b input=a9049054013a1b77]*/ +/*[clinic end generated code: output=11a7085437a57e12 input=a9049054013a1b77]*/ diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 72f2e356c34f7c8..9062b1b64fbc4a0 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -2,6 +2,7 @@ #include "Python.h" #include "pycore_ast.h" // _PyAST_Validate() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_call.h" // _PyObject_CallNoArgs() #include "pycore_cell.h" // PyCell_GetRef() #include "pycore_ceval.h" // _PyEval_Vector() @@ -2173,11 +2174,10 @@ builtin_ord(PyObject *module, PyObject *c) } } else if (PyByteArray_Check(c)) { - /* XXX Hopefully this is temporary */ - size = PyByteArray_GET_SIZE(c); + char ch = 0; + size = _PyByteArray_GetByte(c, &ch); if (size == 1) { - ord = (long)((unsigned char)*PyByteArray_AS_STRING(c)); - return PyLong_FromLong(ord); + return PyLong_FromLong((unsigned char)ch); } } else { diff --git a/Python/getargs.c b/Python/getargs.c index 70bd54a23e939ce..8bb2d036529a604 100644 --- a/Python/getargs.c +++ b/Python/getargs.c @@ -4,6 +4,7 @@ #define PY_CXX_CONST const #include "Python.h" #include "pycore_abstract.h" // _PyNumber_Index() +#include "pycore_bytesobject.h" // _PyByteArray_GetByte() #include "pycore_dict.h" // _PyDict_HasOnlyStringKeys() #include "pycore_modsupport.h" // export _PyArg_NoKeywords() #include "pycore_pylifecycle.h" // _PyArg_Fini @@ -949,12 +950,12 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, *p = PyBytes_AS_STRING(arg)[0]; } else if (PyByteArray_Check(arg)) { - if (PyByteArray_GET_SIZE(arg) != 1) { + Py_ssize_t size = _PyByteArray_GetByte(arg, p); + if (size != 1) { return convertcharerr("a byte string of length 1", - "a bytearray object", PyByteArray_GET_SIZE(arg), + "a bytearray object", size, msgbuf, bufsize); } - *p = PyByteArray_AS_STRING(arg)[0]; } else return converterr("a byte string of length 1", arg, msgbuf, bufsize); @@ -1142,15 +1143,19 @@ convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags, /* Encode object */ if (!recode_strings && (PyBytes_Check(arg) || PyByteArray_Check(arg))) { - s = Py_NewRef(arg); if (PyBytes_Check(arg)) { - size = PyBytes_GET_SIZE(s); - ptr = PyBytes_AS_STRING(s); + s = Py_NewRef(arg); } else { - size = PyByteArray_GET_SIZE(s); - ptr = PyByteArray_AS_STRING(s); + /* Copy under the lock, so a concurrent resize of the + bytearray cannot free the data while it is used below. */ + s = _PyBytes_FromByteArray(arg); + if (s == NULL) { + RETURN_ERR_OCCURRED; + } } + size = PyBytes_GET_SIZE(s); + ptr = PyBytes_AS_STRING(s); } else if (PyUnicode_Check(arg)) { /* Encode object; use default error handling */ diff --git a/Python/pythonrun.c b/Python/pythonrun.c index 38003e60e985ca2..f0e071c5565bf27 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -12,6 +12,7 @@ #include "pycore_ast.h" // PyAST_mod2obj() #include "pycore_audit.h" // _PySys_Audit() +#include "pycore_bytesobject.h" // _PyBytes_FromByteArray() #include "pycore_ceval.h" // _Py_EnterRecursiveCall() #include "pycore_compile.h" // _PyAST_Compile() #include "pycore_fileutils.h" // _PyFile_Flush @@ -1667,8 +1668,12 @@ _Py_SourceAsString(PyObject *cmd, const char *funcname, const char *what, PyComp size = PyBytes_GET_SIZE(cmd); } else if (PyByteArray_Check(cmd)) { - str = PyByteArray_AS_STRING(cmd); - size = PyByteArray_GET_SIZE(cmd); + *cmd_copy = _PyBytes_FromByteArray(cmd); + if (*cmd_copy == NULL) { + return NULL; + } + str = PyBytes_AS_STRING(*cmd_copy); + size = PyBytes_GET_SIZE(*cmd_copy); } else if (PyObject_GetBuffer(cmd, &view, PyBUF_SIMPLE) == 0) { /* Copy to NUL-terminated buffer. */ diff --git a/Tools/clinic/libclinic/converters.py b/Tools/clinic/libclinic/converters.py index 014486f7f469def..94de63784172aea 100644 --- a/Tools/clinic/libclinic/converters.py +++ b/Tools/clinic/libclinic/converters.py @@ -184,7 +184,9 @@ def c_default_init(self) -> None: self.c_default = "'" + r + "'" def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> str | None: - if self.format_unit == 'c': + if self.format_unit == 'c' and not limited_capi: + self.add_include('pycore_bytesobject.h', + '_PyByteArray_GetByte()') return self.format_code(""" if (PyBytes_Check({argname})) {{{{ if (PyBytes_GET_SIZE({argname}) != 1) {{{{ @@ -197,14 +199,13 @@ def parse_arg(self, argname: str, displayname: str, *, limited_capi: bool) -> st {paramname} = PyBytes_AS_STRING({argname})[0]; }}}} else if (PyByteArray_Check({argname})) {{{{ - if (PyByteArray_GET_SIZE({argname}) != 1) {{{{ + Py_ssize_t {paramname}_size = _PyByteArray_GetByte({argname}, &{paramname}); + if ({paramname}_size != 1) {{{{ PyErr_Format(PyExc_TypeError, "{{name}}(): {displayname} must be a byte string of length 1, " - "not a bytearray object of length %zd", - PyByteArray_GET_SIZE({argname})); + "not a bytearray object of length %zd", {paramname}_size); goto exit; }}}} - {paramname} = PyByteArray_AS_STRING({argname})[0]; }}}} else {{{{ {bad_argument}