python / python/cpython

The use of `PyStackRef_AsPyObjectBorrow` makes it hard to track ownership of references, making analysis of escaping calls too difficult

未关闭
#122,034 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

interpreter-core
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

The problem with PyStackRef_AsPyObjectBorrow is that it is not clear whether the reference is owned by the stack ref or the pointer.

Borrowing references across calls is fine but in less structured code, it is error prone and very hard to analyze.

The solution is change most, ideally all, uses of PyStackRef_AsPyObjectBorrow to PyStackRef_AsPyObjectSteal so that the ownership of the reference is clear.
E.g.

        inst(UNARY_NEGATIVE, (value -- res)) {
            PyObject *val_o = PyStackRef_AsPyObjectBorrow(value);
            PyObject *res_o = PyNumber_Negative(val_o);
            PyStackRef_CLOSE(value);
            ERROR_IF(res_o == NULL, error);
            res = PyStackRef_FromPyObjectSteal(res_o);
        }

would become:

        inst(UNARY_NEGATIVE, (value -- res)) {
            PyObject *val_o = PyStackRef_AsPyObjectSteal(value);
            PyObject *res_o = PyNumber_Negative(val_o);
            Py_DECREF(val_o);
            ERROR_IF(res_o == NULL, error);
            res = PyStackRef_FromPyObjectSteal(res_o);
        }

This ensures that during the escaping call to PyNumber_Negative, the reference to the value a PyObject *, so will not be reclaimed by the garbage collector.

Linked PRs
  • gh-122037

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

在 CPython 源代码中搜索 PyStackRef_AsPyObjectBorrow 的使用位置,并审查 issue 中展示的 PyStackRef_AsPyObjectSteal 和 PyStackRef_CLOSE 所有权模式。确定哪些使用位置跨越了可能导致引用逸出的调用,然后验证相关引用仍然有效且所有权是明确的;将这项工作与链接的 PR gh-122037 进行比较。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
backend
Issue 类型
重构
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。