Skip to content

convert_pystr_to_str crashes on lone surrogates (std::string(NULL) UB) #225

Description

@devdanzin

convert_pystr_to_str in util.h:55-59 passes the return value of PyUnicode_AsUTF8 directly to std::string without checking for NULL. PyUnicode_AsUTF8 returns NULL when the string contains lone surrogates (which cannot be encoded as UTF-8). Passing NULL to std::string(const char*) is undefined behavior — crashes immediately.

Reproducer:

import kiwisolver
kiwisolver.Variable("test\ud800name")  # Segmentation fault

Current code (util.h:55-59):

inline bool
convert_pystr_to_str( PyObject* value, std::string& out )
{
    out = PyUnicode_AsUTF8( value );
    return true;
}

Fix:

inline bool
convert_pystr_to_str( PyObject* value, std::string& out )
{
    const char* s = PyUnicode_AsUTF8( value );
    if( !s )
        return false;
    out = s;
    return true;
}

This function is called from Variable_new, Variable_setName, convert_to_strength, and convert_to_relational_op — all reachable from Python.

Found by cext-review-toolkit.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions