Skip to content

readline.c: Missing NULL check on PyLong_FromLong #154385

Description

@aisk

Bug report

Bug description:

Original gist: https://gist.github.com/devdanzin/60aed55f44fba133ee2d34d46aa8d197

readline.c: Missing NULL check on PyLong_FromLong in setup_readline

Summary

PyLong_FromLong(0L) at lines 1418-1419 stored in begidx/endidx without NULL check. On OOM during module init, readline.get_begidx() does Py_NewRef(NULL) → segfault.

Reproducer

import_testcapi, sysif"readline"insys.modules: delsys.modules["readline"]
forninrange(1, 80):
if"readline"insys.modules: delsys.modules["readline"]
_testcapi.set_nomemory(n, 0)
try:
importreadline_testcapi.remove_mem_hooks()
breakexceptMemoryError:
_testcapi.remove_mem_hooks()
exceptImportError:
_testcapi.remove_mem_hooks()
except:
_testcapi.remove_mem_hooks()
# Assertion: obj != NULL in PyStackRef_FromPyObjectSteal

The original gist said we should check the result of PyLong_FromLong(0L), but I think this is a false positive, because 0 is small int and should not failed while creating a Python int object from it.

However there are other line of code in this file for calling PyLong_FromLong with begidx/endidx withoud check the result:

cpython/Modules/readline.c

Lines 1330 to 1331 in d333e5a

state->begidx=PyLong_FromLong((long) start);
state->endidx=PyLong_FromLong((long) end);

I guess the LLM found a real bug but reported it at the wrong place. Either way, we should fix it.

CPython versions tested on:

CPython main branch

Operating systems tested on:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirtype-crashA hard crash of the interpreter, possibly with a core dump

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions