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

Skip to content

Commit f18bf6f

Browse files
committed
add some overflow checks before multiplying (closes #23165)
1 parent 47e782a commit f18bf6f

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 3.2.6?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #23165: Perform overflow checks before allocating memory in the
14+
_Py_char2wchar function.
15+
1316
- Issue #19529: Fix a potential crash in converting Unicode objects to wchar_t
1417
when Py_UNICODE is 4 bytes but wchar_t is 2 bytes, for example on AIX.
1518

Python/fileutils.c

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,11 @@ decode_ascii_surrogateescape(const char *arg, size_t *size)
169169
wchar_t *res;
170170
unsigned char *in;
171171
wchar_t *out;
172+
size_t argsize = strlen(arg) + 1;
172173

173-
res = PyMem_Malloc((strlen(arg)+1)*sizeof(wchar_t));
174+
if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
175+
return NULL;
176+
res = PyMem_Malloc(argsize*sizeof(wchar_t));
174177
if (!res)
175178
return NULL;
176179

@@ -250,10 +253,15 @@ _Py_char2wchar(const char* arg, size_t *size)
250253
argsize = mbstowcs(NULL, arg, 0);
251254
#endif
252255
if (argsize != (size_t)-1) {
253-
res = (wchar_t *)PyMem_Malloc((argsize+1)*sizeof(wchar_t));
256+
if (argsize == PY_SSIZE_T_MAX)
257+
goto oom;
258+
argsize += 1;
259+
if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
260+
goto oom;
261+
res = (wchar_t *)PyMem_Malloc(argsize*sizeof(wchar_t));
254262
if (!res)
255263
goto oom;
256-
count = mbstowcs(res, arg, argsize+1);
264+
count = mbstowcs(res, arg, argsize);
257265
if (count != (size_t)-1) {
258266
wchar_t *tmp;
259267
/* Only use the result if it contains no
@@ -276,6 +284,8 @@ _Py_char2wchar(const char* arg, size_t *size)
276284
/* Overallocate; as multi-byte characters are in the argument, the
277285
actual output could use less memory. */
278286
argsize = strlen(arg) + 1;
287+
if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
288+
goto oom;
279289
res = (wchar_t*)PyMem_Malloc(argsize*sizeof(wchar_t));
280290
if (!res)
281291
goto oom;

0 commit comments

Comments
 (0)