This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Possible divide by zero problems
Type: behavior Stage: resolved
Components: Unicode Versions: Python 3.11
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ezio.melotti, methane, serhiy.storchaka, vstinner, yiyuaner
Priority: normal Keywords:

Created on 2021-05-07 15:00 by yiyuaner, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg393188 - (view) Author: yiyuaner (yiyuaner) Date: 2021-05-07 15:00
In the file Objects/unicodeobject.c, we have the following code:

static PyObject*
resize_compact(PyObject *unicode, Py_ssize_t length) {
  ...
  char_size = PyUnicode_KIND(unicode);
  ...
  if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
    PyErr_NoMemory();
    return NULL;
  }
}

However, PyUnicode_KIND may return 0 if the variable unicode has kind PyUnicode_WCHAR_KIND, leading to a divide by zero problem.

The same pattern is also used without checking in function "static int
resize_inplace(PyObject *unicode, Py_ssize_t length)".

Here is the link to the code location: https://github.com/python/cpython/blob/main/Objects/unicodeobject.c#L1045

Should we add an explicit check on variable char_size before using it in division?
msg393189 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2021-05-07 15:14
It cannot be 0 if PyUnicode_IS_READY() returns true.
msg393431 - (view) Author: STINNER Victor (vstinner) * (Python committer) Date: 2021-05-10 20:53
> Should we add an explicit check on variable char_size before using it in division?

Search for "There are 4 forms of Unicode strings" in Include/cpython/unicodeobject.h. char_size cannot be 0 in resize_compact(): it's checked by 2 assertions:

    assert(PyUnicode_IS_READY(unicode));
    assert(PyUnicode_IS_COMPACT(unicode));

The function cannot be called on a string which is not compact.

There is no bug, I close the issue.

Hopefully, Inada-san will remove state.compact field in Python 3.12 with his PEP 623!
https://www.python.org/dev/peps/pep-0623/#python-3-12
History
Date User Action Args
2022-04-11 14:59:45adminsetgithub: 88234
2021-05-10 20:53:17vstinnersetstatus: open -> closed

nosy: + methane
messages: + msg393431

resolution: not a bug
stage: resolved
2021-05-07 15:14:14serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg393189
2021-05-07 15:00:44yiyuanercreate