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 <noreply@anthropic.com>
This commit is contained in:
Kari Pikkarainen
2026-12-01 09:12:48 -08:00
parent 085c194218
commit fe6205d02c
2 changed files with 17 additions and 1 deletions

View File

@@ -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)

View File

@@ -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)