@@ -180,20 +180,22 @@ PyByteArray_AsString(PyObject *self)
180180}
181181
182182int
183- PyByteArray_Resize (PyObject * self , Py_ssize_t size )
183+ PyByteArray_Resize (PyObject * self , Py_ssize_t requested_size )
184184{
185185 void * sval ;
186186 PyByteArrayObject * obj = ((PyByteArrayObject * )self );
187- Py_ssize_t alloc = obj -> ob_alloc ;
188- Py_ssize_t logical_offset = obj -> ob_start - obj -> ob_bytes ;
187+ /* All computations are done unsigned to avoid integer overflows
188+ (see issue #22335). */
189+ size_t alloc = (size_t ) obj -> ob_alloc ;
190+ size_t logical_offset = (size_t ) (obj -> ob_start - obj -> ob_bytes );
191+ size_t size = (size_t ) requested_size ;
189192
190193 assert (self != NULL );
191194 assert (PyByteArray_Check (self ));
192- assert (size >= 0 );
193- assert (logical_offset >= 0 );
194195 assert (logical_offset <= alloc );
196+ assert (requested_size >= 0 );
195197
196- if (size == Py_SIZE (self )) {
198+ if (requested_size == Py_SIZE (self )) {
197199 return 0 ;
198200 }
199201 if (!_canresize (obj )) {
@@ -225,14 +227,19 @@ PyByteArray_Resize(PyObject *self, Py_ssize_t size)
225227 alloc = size + 1 ;
226228 }
227229 }
230+ if (alloc > PY_SSIZE_T_MAX ) {
231+ PyErr_NoMemory ();
232+ return -1 ;
233+ }
228234
229235 if (logical_offset > 0 ) {
230236 sval = PyObject_Malloc (alloc );
231237 if (sval == NULL ) {
232238 PyErr_NoMemory ();
233239 return -1 ;
234240 }
235- memcpy (sval , PyByteArray_AS_STRING (self ), Py_MIN (size , Py_SIZE (self )));
241+ memcpy (sval , PyByteArray_AS_STRING (self ),
242+ Py_MIN (requested_size , Py_SIZE (self )));
236243 PyObject_Free (obj -> ob_bytes );
237244 }
238245 else {
0 commit comments