[3.6] bpo-30708: Check for null characters in PyUnicode_AsWideCharString(). (GH-2285) (#2443)
Raise a ValueError if the second argument is NULL and the wchar_t\*
string contains null characters..
(cherry picked from commit e613e6add5f07ff6aad5802924596b631b707d2a)
diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c
index 4e0c663..3767064 100644
--- a/Objects/unicodeobject.c
+++ b/Objects/unicodeobject.c
@@ -3017,6 +3017,37 @@
return buffer;
}
+wchar_t*
+_PyUnicode_AsWideCharString(PyObject *unicode)
+{
+ const wchar_t *wstr;
+ wchar_t *buffer;
+ Py_ssize_t buflen;
+
+ if (unicode == NULL) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ wstr = PyUnicode_AsUnicodeAndSize(unicode, &buflen);
+ if (wstr == NULL) {
+ return NULL;
+ }
+ if (wcslen(wstr) != (size_t)buflen) {
+ PyErr_SetString(PyExc_ValueError,
+ "embedded null character");
+ return NULL;
+ }
+
+ buffer = PyMem_NEW(wchar_t, buflen + 1);
+ if (buffer == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memcpy(buffer, wstr, (buflen + 1) * sizeof(wchar_t));
+ return buffer;
+}
+
#endif /* HAVE_WCHAR_H */
PyObject *