Merge pull request #31324 from kari-pikkarainen/fix/python-lone-surrogate-5.x

5.x port of #31296 (merged to 4.x), requested there. It is a clean cherry-pick of the same change.

A Python str containing a lone surrogate, such as 'a\udcff', crashes the interpreter when it is passed to bindings that take a string, for example cv.putText, cv.imread or cv.imwrite. Python produces such strings for non-UTF-8 filenames on POSIX.

getUnicodeString() in modules/python/src2/pycompat.hpp passed the NULL that PyUnicode_AsUTF8String() returns on failure to PyBytes_Check(). This PR adds the NULL check, so the pending UnicodeEncodeError is reported instead.

Difference from 4.x: cv.getTextSize raises cv.error here, because 5.x has another overload; 4.x raises UnicodeEncodeError.
This commit is contained in:
Abhishek Gola
2026-12-02 22:40:18 +05:30
committed by GitHub
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

@@ -585,6 +585,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)