From fe6205d02c94f73011fc0b815d8897821afe07d9 Mon Sep 17 00:00:00 2001 From: Kari Pikkarainen <154351964+kari-pikkarainen@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:12:48 -0800 Subject: [PATCH] python: raise instead of crashing on strings that can't be encoded as UTF-8 getUnicodeString passed the result of PyUnicode_AsUTF8String to PyBytes_Check without a NULL check. For a str with a lone surrogate (for example '\udcff') the encoder fails and returns NULL, so passing such a string to any std::string argument (putText, getTextSize, ...) crashed the interpreter. It now returns false with the UnicodeEncodeError set, which the converters already report. Prepared with AI assistance (Claude Code); I reviewed the change and the verification results. Co-Authored-By: Claude Opus 5.5 --- modules/python/src2/pycompat.hpp | 3 ++- modules/python/test/test_misc.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/modules/python/src2/pycompat.hpp b/modules/python/src2/pycompat.hpp index c936f5e66a..5257ea5194 100644 --- a/modules/python/src2/pycompat.hpp +++ b/modules/python/src2/pycompat.hpp @@ -72,8 +72,9 @@ static inline bool getUnicodeString(PyObject * obj, std::string &str) bool res = false; if (PyUnicode_Check(obj)) { + // NULL with UnicodeEncodeError set, e.g. for a lone surrogate PyObject * bytes = PyUnicode_AsUTF8String(obj); - if (PyBytes_Check(bytes)) + if (bytes && PyBytes_Check(bytes)) { const char * raw = PyBytes_AsString(bytes); if (raw) diff --git a/modules/python/test/test_misc.py b/modules/python/test/test_misc.py index e132240544..06dc384da7 100644 --- a/modules/python/test/test_misc.py +++ b/modules/python/test/test_misc.py @@ -555,6 +555,21 @@ class Arguments(NewOpenCVTests): with self.assertRaises((TypeError), msg=get_no_exception_msg(not_convertible)): _ = cv.utils.dumpString(not_convertible) + @unittest.skipIf(sys.version_info[0] < 3, 'lone surrogates need Python 3 str') + def test_parse_to_string_not_encodable(self): + # A lone surrogate can't be encoded as UTF-8; this used to crash the interpreter + not_encodable = 'a\udcff' + for func in (cv.utils.dumpString, cv.utils.dumpCString): + with self.assertRaises(UnicodeEncodeError, msg=get_no_exception_msg(not_encodable)): + _ = func(not_encodable) + # Functions with several overloads report the encoding error through cv.error + for call in (lambda: cv.putText(np.zeros((8, 8), np.uint8), not_encodable, (0, 7), + cv.FONT_HERSHEY_SIMPLEX, 0.3, 255), + lambda: cv.imread(not_encodable), + lambda: cv.imwrite(not_encodable, np.zeros((2, 2), np.uint8))): + with self.assertRaises((cv.error, UnicodeEncodeError), msg=get_no_exception_msg(not_encodable)): + call() + def test_parse_to_rect_convertible(self): Rect = namedtuple('Rect', ('x', 'y', 'w', 'h')) try_to_convert = partial(self._try_to_convert, cv.utils.dumpRect)