PyAPI_FUNC(int) PyByteArray_Resize(PyObject *, Py_ssize_t);
/* Macros, trading safety for speed */
-#define PyByteArray_AS_STRING(self) (assert(PyByteArray_Check(self)),((PyByteArrayObject *)(self))->ob_bytes)
+#define PyByteArray_AS_STRING(self) \
+ (assert(PyByteArray_Check(self)), \
+ Py_SIZE(self) ? ((PyByteArrayObject *)(self))->ob_bytes : _PyByteArray_empty_string)
#define PyByteArray_GET_SIZE(self) (assert(PyByteArray_Check(self)),Py_SIZE(self))
+extern char _PyByteArray_empty_string[];
+
#ifdef __cplusplus
}
#endif
self.assertRaises(BufferError, delslice)
self.assertEquals(b, orig)
+ def test_empty_bytearray(self):
+ # Issue #7561: operations on empty bytearrays could crash in many
+ # situations, due to a fragile implementation of the
+ # PyByteArray_AS_STRING() C macro.
+ self.assertRaises(ValueError, int, bytearray(b''))
+
+
class AssortedBytesTest(unittest.TestCase):
#
# Test various combinations of bytes and bytearray
Core and Builtins
-----------------
+- Issue #7561: Operations on empty bytearrays (such as `int(bytearray())`)
+ could crash in many places because of the PyByteArray_AS_STRING() macro
+ returning NULL. The macro now returns a statically allocated empty
+ string instead.
+
- Issue #7604: Deleting an unset slotted attribute did not raise an
AttributeError.
#include "bytes_methods.h"
static PyByteArrayObject *nullbytes = NULL;
+char _PyByteArray_empty_string[] = "";
void
PyByteArray_Fini(void)
"accessing non-existent bytes segment");
return -1;
}
- *ptr = (void *)self->ob_bytes;
+ *ptr = (void *)PyByteArray_AS_STRING(self);
return Py_SIZE(self);
}
"accessing non-existent bytes segment");
return -1;
}
- *ptr = (void *)self->ob_bytes;
+ *ptr = (void *)PyByteArray_AS_STRING(self);
return Py_SIZE(self);
}
"accessing non-existent bytes segment");
return -1;
}
- *ptr = self->ob_bytes;
+ *ptr = PyByteArray_AS_STRING(self);
return Py_SIZE(self);
}
obj->ob_exports++;
return 0;
}
- if (obj->ob_bytes == NULL)
- ptr = "";
- else
- ptr = obj->ob_bytes;
+ ptr = (void *) PyByteArray_AS_STRING(obj);
ret = PyBuffer_FillInfo(view, (PyObject*)obj, ptr, Py_SIZE(obj), 0, flags);
if (ret >= 0) {
obj->ob_exports++;
Py_DECREF(new);
return PyErr_NoMemory();
}
- if (bytes != NULL)
+ if (bytes != NULL && size > 0)
memcpy(new->ob_bytes, bytes, size);
new->ob_bytes[size] = '\0'; /* Trailing null byte */
}