Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4c2e4fa

Browse files
author
Victor Stinner
committed
Issue #9979: Use PyUnicode_AsWideCharString() in _ctypes module
* Convert unicode to wide character string before creating the PyCapsule object * Catch integer overflow * Avoid useless memset() * Prepare the support of surrogates
1 parent b290478 commit 4c2e4fa

2 files changed

Lines changed: 5 additions & 24 deletions

File tree

Modules/_ctypes/callproc.c

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -665,24 +665,15 @@ static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
665665
pa->keep = obj;
666666
return 0;
667667
#else
668-
int size = PyUnicode_GET_SIZE(obj);
669668
pa->ffi_type = &ffi_type_pointer;
670-
size += 1; /* terminating NUL */
671-
size *= sizeof(wchar_t);
672-
pa->value.p = PyMem_Malloc(size);
673-
if (!pa->value.p) {
674-
PyErr_NoMemory();
669+
pa->value.p = PyUnicode_AsWideCharString((PyUnicodeObject *)obj, NULL);
670+
if (pa->value.p == NULL)
675671
return -1;
676-
}
677-
memset(pa->value.p, 0, size);
678672
pa->keep = PyCapsule_New(pa->value.p, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
679673
if (!pa->keep) {
680674
PyMem_Free(pa->value.p);
681675
return -1;
682676
}
683-
if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
684-
pa->value.p, PyUnicode_GET_SIZE(obj)))
685-
return -1;
686677
return 0;
687678
#endif
688679
}
@@ -1147,7 +1138,7 @@ PyObject *_ctypes_callproc(PPROC pProc,
11471138
}
11481139
for (i = 0; i < argcount; ++i) {
11491140
atypes[i] = args[i].ffi_type;
1150-
if (atypes[i]->type == FFI_TYPE_STRUCT
1141+
if (atypes[i]->type == FFI_TYPE_STRUCT
11511142
#ifdef _WIN64
11521143
&& atypes[i]->size <= sizeof(void *)
11531144
#endif

Modules/_ctypes/cfield.c

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,28 +1433,18 @@ Z_set(void *ptr, PyObject *value, Py_ssize_t size)
14331433
PyObject *keep;
14341434
wchar_t *buffer;
14351435

1436-
int size = PyUnicode_GET_SIZE(value);
1437-
size += 1; /* terminating NUL */
1438-
size *= sizeof(wchar_t);
1439-
buffer = (wchar_t *)PyMem_Malloc(size);
1436+
buffer = PyUnicode_AsWideCharString((PyUnicodeObject *)value, NULL);
14401437
if (!buffer) {
14411438
Py_DECREF(value);
1442-
return PyErr_NoMemory();
1439+
return NULL;
14431440
}
1444-
memset(buffer, 0, size);
14451441
keep = PyCapsule_New(buffer, CTYPES_CFIELD_CAPSULE_NAME_PYMEM, pymem_destructor);
14461442
if (!keep) {
14471443
Py_DECREF(value);
14481444
PyMem_Free(buffer);
14491445
return NULL;
14501446
}
14511447
*(wchar_t **)ptr = (wchar_t *)buffer;
1452-
if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
1453-
buffer, PyUnicode_GET_SIZE(value))) {
1454-
Py_DECREF(value);
1455-
Py_DECREF(keep);
1456-
return NULL;
1457-
}
14581448
Py_DECREF(value);
14591449
return keep;
14601450
}

0 commit comments

Comments
 (0)