ctypes check for PyUnicode_GET_SIZE() failure

This commit is contained in:
Victor Stinner 2011-11-21 02:11:26 +01:00
parent 8ef18872b4
commit ea90e0fd95
2 changed files with 16 additions and 6 deletions

View File

@ -1142,6 +1142,8 @@ static int
WCharArray_set_value(CDataObject *self, PyObject *value) WCharArray_set_value(CDataObject *self, PyObject *value)
{ {
Py_ssize_t result = 0; Py_ssize_t result = 0;
Py_UNICODE *wstr;
Py_ssize_t len;
if (value == NULL) { if (value == NULL) {
PyErr_SetString(PyExc_TypeError, PyErr_SetString(PyExc_TypeError,
@ -1155,7 +1157,11 @@ WCharArray_set_value(CDataObject *self, PyObject *value)
return -1; return -1;
} else } else
Py_INCREF(value); Py_INCREF(value);
if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
wstr = PyUnicode_AsUnicodeAndSize(value, &len);
if (wstr == NULL)
return -1;
if ((unsigned)len > self->b_size/sizeof(wchar_t)) {
PyErr_SetString(PyExc_ValueError, PyErr_SetString(PyExc_ValueError,
"string too long"); "string too long");
result = -1; result = -1;

View File

@ -1259,6 +1259,7 @@ U_get(void *ptr, Py_ssize_t size)
static PyObject * static PyObject *
U_set(void *ptr, PyObject *value, Py_ssize_t length) U_set(void *ptr, PyObject *value, Py_ssize_t length)
{ {
Py_UNICODE *wstr;
Py_ssize_t size; Py_ssize_t size;
/* It's easier to calculate in characters than in bytes */ /* It's easier to calculate in characters than in bytes */
@ -1271,7 +1272,10 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
return NULL; return NULL;
} else } else
Py_INCREF(value); Py_INCREF(value);
size = PyUnicode_GET_SIZE(value);
wstr = PyUnicode_AsUnicodeAndSize(value, &size);
if (wstr == NULL)
return NULL;
if (size > length) { if (size > length) {
PyErr_Format(PyExc_ValueError, PyErr_Format(PyExc_ValueError,
"string too long (%zd, maximum length %zd)", "string too long (%zd, maximum length %zd)",
@ -1471,15 +1475,15 @@ BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
/* create a BSTR from value */ /* create a BSTR from value */
if (value) { if (value) {
Py_ssize_t size = PyUnicode_GET_SIZE(value);
wchar_t* wvalue; wchar_t* wvalue;
Py_ssize_t size;
wvalue = PyUnicode_AsUnicodeAndSize(value, &size);
if (wvalue == NULL)
return NULL;
if ((unsigned) size != size) { if ((unsigned) size != size) {
PyErr_SetString(PyExc_ValueError, "String too long for BSTR"); PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
return NULL; return NULL;
} }
wvalue = PyUnicode_AsUnicode(value);
if (wvalue == NULL)
return NULL;
bstr = SysAllocStringLen(wvalue, (unsigned)size); bstr = SysAllocStringLen(wvalue, (unsigned)size);
Py_DECREF(value); Py_DECREF(value);
} else } else