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
分支
36k
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 摘要。