Debian Codegraph @

IPython/extensions/deduperreload/deduperreload_patching.py

raw
1 from __future__ import annotations
2 import ctypes
3 import sys
4 from typing import Any
5
6 NOT_FOUND: object = object()
7 NULL: object = object()
8 _MAX_FIELD_SEARCH_OFFSET = 50
9
10 POINTER_N_BYTES = ctypes.sizeof(ctypes.c_void_p)
11
12
13 class DeduperReloaderPatchingMixin:
14 @staticmethod
15 def infer_field_offset(
16 obj: object,
17 field: str,
18 ) -> int:
19 field_value = getattr(obj, field, NOT_FOUND)
20 if field_value is NOT_FOUND:
21 return -1
22 obj_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(obj)).value
23 field_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(field_value)).value
24 if obj_addr is None or field_addr is None:
25 return -1
26 ret = -1
27 for offset in range(1, _MAX_FIELD_SEARCH_OFFSET):
28 if (
29 ctypes.cast(
30 obj_addr + POINTER_N_BYTES * offset, ctypes.POINTER(ctypes.c_void_p)
31 ).contents.value
32 == field_addr
33 ):
34 ret = offset
35 break
36 return ret
37
38 @classmethod
39 def try_write_readonly_attr(
40 cls,
41 obj: object,
42 field: str,
43 new_value: object,
44 offset: int | None = None,
45 ) -> None:
46 prev_value = getattr(obj, field, NOT_FOUND)
47 if prev_value is NOT_FOUND:
48 return
49 if offset is None:
50 offset = cls.infer_field_offset(obj, field)
51 if offset == -1:
52 return
53 obj_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(obj)).value
54 if new_value is NULL:
55 new_value_addr: int | None = 0
56 else:
57 new_value_addr = ctypes.c_void_p.from_buffer(
58 ctypes.py_object(new_value)
59 ).value
60 if obj_addr is None or new_value_addr is None:
61 return
62 if prev_value is not None:
63 ctypes.pythonapi.Py_DecRef(ctypes.py_object(prev_value))
64 if new_value not in (None, NULL):
65 ctypes.pythonapi.Py_IncRef(ctypes.py_object(new_value))
66 ctypes.cast(
67 obj_addr + POINTER_N_BYTES * offset, ctypes.POINTER(ctypes.c_void_p)
68 ).contents.value = new_value_addr
69
70 @classmethod
71 def try_patch_readonly_attr(
72 cls,
73 old: object,
74 new: object,
75 field: str,
76 new_is_value: bool = False,
77 offset: int = -1,
78 ) -> None:
79 old_value = getattr(old, field, NOT_FOUND)
80 new_value = new if new_is_value else getattr(new, field, NOT_FOUND)
81 if old_value is NOT_FOUND or new_value is NOT_FOUND:
82 return
83 elif old_value is new_value:
84 return
85 elif old_value is not None and offset < 0:
86 offset = cls.infer_field_offset(old, field)
87 elif offset < 0:
88 assert not new_is_value
89 assert new_value is not None
90 offset = cls.infer_field_offset(new, field)
91 cls.try_write_readonly_attr(old, field, new_value, offset=offset)
92
93 @classmethod
94 def try_patch_attr(
95 cls,
96 old: object,
97 new: object,
98 field: str,
99 new_is_value: bool = False,
100 offset: int = -1,
101 ) -> None:
102 try:
103 setattr(old, field, new if new_is_value else getattr(new, field))
104 except (AttributeError, TypeError, ValueError):
105 cls.try_patch_readonly_attr(old, new, field, new_is_value, offset)
106
107 @classmethod
108 def patch_function(
109 cls, to_patch_to: Any, to_patch_from: Any, is_method: bool
110 ) -> None:
111 new_closure = []
112 for freevar, closure_val in zip(
113 to_patch_from.__code__.co_freevars or [], to_patch_from.__closure__ or []
114 ):
115 if (
116 callable(closure_val.cell_contents)
117 and freevar in to_patch_to.__code__.co_freevars
118 ):
119 new_closure.append(
120 to_patch_to.__closure__[
121 to_patch_to.__code__.co_freevars.index(freevar)
122 ]
123 )
124 else:
125 new_closure.append(closure_val)
126 # lambdas may complain if there is more than one freevar
127 cls.try_patch_attr(to_patch_to, to_patch_from, "__code__")
128 offset = -1
129 if to_patch_to.__closure__ is None and to_patch_from.__closure__ is not None:
130 offset = cls.infer_field_offset(to_patch_from, "__closure__")
131 if to_patch_to.__closure__ is not None or to_patch_from.__closure__ is not None:
132 cls.try_patch_readonly_attr(
133 to_patch_to,
134 tuple(new_closure) or NULL,
135 "__closure__",
136 new_is_value=True,
137 offset=offset,
138 )
139 for attr in ("__defaults__", "__kwdefaults__", "__doc__", "__dict__"):
140 cls.try_patch_attr(to_patch_to, to_patch_from, attr)
141 if is_method:
142 cls.try_patch_readonly_attr(to_patch_to, to_patch_from, "__self__")