`pickle.loads` will crash with self-references inside a custom hash function
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
Bug report
Bug description:
here is a reproduction of the issue:
import pickle
class Foo:
def __init__(self):
self.x: object = {self}
def __hash__(self):
return hash(self.x)
foo = Foo()
print(pickle.loads(pickle.dumps(foo)))
running this will result in the following exception:
Traceback (most recent call last):
File "/home/charles/vyper/foo.py", line 10, in <module>
foo = Foo()
^^^^^
File "/home/charles/vyper/foo.py", line 5, in __init__
self.x: object = {self}
^^^^^^
File "/home/charles/vyper/foo.py", line 8, in __hash__
return hash(self.x)
^^^^^^
AttributeError: 'Foo' object has no attribute 'x'
a workaround to the issue has been described at https://stackoverflow.com/a/44888113. however, i consider this a bug in the cpython implementation, because pickle theoretically handles object cycles (e.g., replacing line 5 with self.x = [self] poses no problem to the unpickler).
i suspect that cpython rehashes all items when reconstructing a dict or set, which makes the issue even more problematic, e.g. if the hash function has any side-effects, they will be executed by the unpickler.
build info:
$ python
Python 3.11.10 (main, Sep 7 2024, 18:35:41) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
CPython versions tested on:
3.11
Operating systems tested on:
Linux
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
該報告提供了一個以 pickle.dumps 和 pickle.loads 為中心的重現程式,但沒有指出任何 CPython 原始碼檔案或測試。先在所述的 Python 3.11/Linux 環境中執行它,並追蹤反序列化路徑;完成這項工作需要針對自我參照的自訂雜湊達成一致的行為、具備回歸測試涵蓋率,且不得產生非預期的雜湊副作用。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- backend
- Issue 類型
- 缺陷
- 難度
- 5/5
- 預估耗時
- 一週以上
- 活躍度
- 停滯
- 描述清晰度
- 需要釐清
- 新手友好度
- 25/100