Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_curses.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,6 +895,25 @@ def test_output_string_embedded_null_chars(self):
self.assertRaises(ValueError, stdscr.insstr, arg)
self.assertRaises(ValueError, stdscr.insnstr, arg, 1)

def test_cell_embedded_null_chars(self):
# A cell cannot hold a NUL: setcchar() keeps only the text before it,
# so reject it instead of silently truncating the cell.
stdscr = self.stdscr
for text in ['a\0', '\0', 'a\0\u0301', 'a\0b']:
with self.subTest(text=text):
self.assertRaises(ValueError, curses.complexchar, text)
self.assertRaises(ValueError, curses.complexstr, text)
self.assertRaises(ValueError, curses.complexstr, [text])
if WIDE_BUILD:
self.assertRaises(ValueError, stdscr.addch, 'a\0\u0301')
# A lone NUL is still written as a character, like addch(0).
stdscr.erase()
stdscr.addch(0, 0, 0)
expected = stdscr.instr(0, 0, 4)
stdscr.erase()
stdscr.addch(0, 0, '\0')
self.assertEqual(stdscr.instr(0, 0, 4), expected)

def test_add_string_behavior(self):
# addstr() advances the cursor past the written text; addnstr()
# writes at most n characters.
Expand Down
12 changes: 12 additions & 0 deletions Modules/_cursesmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,10 @@ PyCurses_ConvertToWideCell(PyObject *obj, wchar_t *wch)
setcchar() would silently drop a trailing spacing character, or fail
with a generic error for a control-character base. */
if (nch > 1) {
if (wmemchr(wch, L'\0', nch) != NULL) {
PyErr_SetString(PyExc_ValueError, "embedded null character");
return -1;
}
int bad = wcwidth(wch[0]) < 0;
for (Py_ssize_t i = 1; !bad && i < nch; i++) {
bad = wcwidth(wch[i]) != 0;
Expand Down Expand Up @@ -835,6 +839,10 @@ static int
curses_cell_pack(cursesmodule_state *state, curses_cell_t *cell,
PyObject *text, attr_t attr, int pair, const char *funcname)
{
if (PyUnicode_FindChar(text, 0, 0, PyUnicode_GET_LENGTH(text), 1) >= 0) {
PyErr_SetString(PyExc_ValueError, "embedded null character");
return -1;
}
#ifdef HAVE_NCURSESW
wchar_t wstr[CCHARW_MAX + 1];
if (PyCurses_ConvertToWideCell(text, wstr) < 0) {
Expand Down Expand Up @@ -1318,6 +1326,10 @@ static PyObject *
complexstr_from_string(cursesmodule_state *state, PyObject *str,
attr_t attr, int pair)
{
if (PyUnicode_FindChar(str, 0, 0, PyUnicode_GET_LENGTH(str), 1) >= 0) {
PyErr_SetString(PyExc_ValueError, "embedded null character");
return NULL;
}
#ifdef HAVE_NCURSESW
Py_ssize_t n;
wchar_t *wbuf = PyUnicode_AsWideCharString(str, &n);
Expand Down
Loading