Skip to content

Possible memory leak in _ctypes/PyCStructUnionType_update_stginfo on fail path #131311

Closed
@sergey-miryanov

Description

@sergey-miryanov

Bug report

Bug description:

  1. I have found that layout_func may leak when creating of kwnames fails:

    PyObject *layout_func = PyImport_ImportModuleAttrString("ctypes._layout",
    "get_layout");
    if (!layout_func) {
    goto error;
    }
    PyObject *kwnames = PyTuple_Pack(
    2,
    &_Py_ID(is_struct),
    &_Py_ID(base));
    if (!kwnames) {
    goto error;

    But on error it doesn't clear layout_func:
    retval = MakeAnonFields(type);
    error:
    Py_XDECREF(layout_fields);
    Py_XDECREF(layout);
    Py_XDECREF(format_spec_obj);
    return retval;
    }

  2. StructParam_traverse should VISIT keep member:

    StructParam_traverse(PyObject *self, visitproc visit, void *arg)
    {
    Py_VISIT(Py_TYPE(self));
    return 0;
    }

  3. PyCSimpleType_init should DECREF swapped local variable if no StgInfo:

    PyObject *swapped = CreateSwappedType(st, type, args, kwds,
    proto, fmt);
    if (swapped == NULL) {
    return -1;
    }
    StgInfo *sw_info;
    if (PyStgInfo_FromType(st, swapped, &sw_info) < 0) {
    return -1;
    }
    assert(sw_info);

  4. make_funcptrtype_dict should DECREF 'ob' local variable if no StgInfo:

    if (PyDict_GetItemRef(attrdict, &_Py_ID(_restype_), &ob) < 0) {
    return -1;
    }
    if (ob) {
    StgInfo *info;
    if (PyStgInfo_FromType(st, ob, &info) < 0) {
    return -1;
    }

  5. Not memory leak, but possible crush. Pointer_subscript should check Pointer_item result before putting it to result list:

    for (cur = start, i = 0; i < len; cur += step, i++) {
    PyObject *v = Pointer_item(myself, cur);
    PyList_SET_ITEM(np, i, v);
    }

  6. As discussed at gh-131311: Fix memory leak in PyCStructUnionType_update_stginfo #131312 we should split PyCStructUnionType_update_stginfo and manage type_block in separate function.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions