python / python/cpython

readline.c: Missing NULL check on PyLong_FromLong

Open
#154,385 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

extension-modules type-crash
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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, sys
if "readline" in sys.modules: del sys.modules["readline"]
for n in range(1, 80):
    if "readline" in sys.modules: del sys.modules["readline"]
    _testcapi.set_nomemory(n, 0)
    try:
        import readline
        _testcapi.remove_mem_hooks()
        break
    except MemoryError:
        _testcapi.remove_mem_hooks()
    except ImportError:
        _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:

https://github.com/python/cpython/blob/d333e5aa59f6cc20198502f4ff50b14eabde9b8b/Modules/readline.c#L1330-L1331

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
  • gh-154386

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read Modules/readline.c around setup_readline and the PyLong_FromLong calls near lines 1330-1331; first run the supplied _testcapi memory-hook reproducer and inspect linked PR gh-154386. Done means the affected out-of-memory path no longer permits a NULL object to reach readline accessors, with the relevant CPython tests passing.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, python
Domain
cli
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.