This repository was archived by the owner on Jul 22, 2023. It is now read-only.
forked from pythonnet/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime_state.cs
More file actions
238 lines (217 loc) · 7.56 KB
/
runtime_state.cs
File metadata and controls
238 lines (217 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using static Python.Runtime.Runtime;
namespace Python.Runtime
{
class RuntimeState
{
public static bool ShouldRestoreObjects { get; set; } = false;
public static bool UseDummyGC { get; set; } = false;
public static void Save()
{
if (!PySys_GetObject("dummy_gc").IsNull)
{
throw new Exception("Runtime State set already");
}
IntPtr objs = IntPtr.Zero;
if (ShouldRestoreObjects)
{
objs = PySet_New(IntPtr.Zero);
foreach (var obj in PyGCGetObjects())
{
AddObjPtrToSet(objs, obj);
}
}
var modules = PySet_New(IntPtr.Zero);
foreach (var name in GetModuleNames())
{
int res = PySet_Add(modules, name);
PythonException.ThrowIfIsNotZero(res);
}
var dummyGCHead = PyMem_Malloc(Marshal.SizeOf(typeof(PyGC_Head)));
unsafe
{
var head = (PyGC_Head*)dummyGCHead;
head->gc.gc_next = dummyGCHead;
head->gc.gc_prev = dummyGCHead;
head->gc.gc_refs = IntPtr.Zero;
}
{
var pyDummyGC = PyLong_FromVoidPtr(dummyGCHead);
int res = PySys_SetObject("dummy_gc", pyDummyGC);
PythonException.ThrowIfIsNotZero(res);
XDecref(pyDummyGC);
try
{
res = PySys_SetObject("initial_modules", modules);
PythonException.ThrowIfIsNotZero(res);
}
finally
{
XDecref(modules);
}
if (ShouldRestoreObjects)
{
AddObjPtrToSet(objs, modules);
try
{
res = PySys_SetObject("initial_objs", objs);
PythonException.ThrowIfIsNotZero(res);
}
finally
{
XDecref(objs);
}
}
}
}
public static void Restore()
{
var dummyGCAddr = PySys_GetObject("dummy_gc").DangerousGetAddress();
if (dummyGCAddr == IntPtr.Zero)
{
throw new InvalidOperationException("Runtime state have not set");
}
var dummyGC = PyLong_AsVoidPtr(dummyGCAddr);
ResotreModules(dummyGC);
if (ShouldRestoreObjects)
{
RestoreObjects(dummyGC);
}
}
private static void ResotreModules(IntPtr dummyGC)
{
var intialModules = PySys_GetObject("initial_modules");
Debug.Assert(!intialModules.IsNull);
var modules = PyImport_GetModuleDict();
foreach (var name in GetModuleNames())
{
if (PySet_Contains(intialModules.DangerousGetAddress(), name) == 1)
{
continue;
}
var module = PyDict_GetItem(modules, name);
if (UseDummyGC && _PyObject_GC_IS_TRACKED(module))
{
ExchangeGCChain(module, dummyGC);
}
if (PyDict_DelItem(modules, name) != 0)
{
PyErr_Print();
}
}
}
private static void RestoreObjects(IntPtr dummyGC)
{
if (!UseDummyGC)
{
throw new Exception("To prevent crash by _PyObject_GC_UNTRACK in Python internal, UseDummyGC should be enabled when using ResotreObjects");
}
IntPtr intialObjs = PySys_GetObject("initial_objs").DangerousGetAddress();
Debug.Assert(intialObjs != IntPtr.Zero);
foreach (var obj in PyGCGetObjects())
{
var p = PyLong_FromVoidPtr(obj);
try
{
if (PySet_Contains(intialObjs, p) == 1)
{
continue;
}
}
finally
{
XDecref(p);
}
Debug.Assert(_PyObject_GC_IS_TRACKED(obj), "A GC object must be tracked");
ExchangeGCChain(obj, dummyGC);
}
}
public static IEnumerable<IntPtr> PyGCGetObjects()
{
var gc = PyImport_ImportModule("gc");
PythonException.ThrowIfIsNull(gc);
var get_objects = PyObject_GetAttrString(gc, "get_objects");
var objs = PyObject_CallObject(get_objects, IntPtr.Zero);
var length = PyList_Size(new BorrowedReference(objs));
for (long i = 0; i < length; i++)
{
var obj = PyList_GetItem(new BorrowedReference(objs), i);
yield return obj.DangerousGetAddress();
}
XDecref(objs);
XDecref(gc);
}
public static IEnumerable<IntPtr> GetModuleNames()
{
var modules = PyImport_GetModuleDict();
var names = PyDict_Keys(modules);
var length = PyList_Size(new BorrowedReference(names));
for (int i = 0; i < length; i++)
{
var name = PyList_GetItem(new BorrowedReference(names), i);
yield return name.DangerousGetAddress();
}
XDecref(names);
}
private static void AddObjPtrToSet(IntPtr set, IntPtr obj)
{
var p = PyLong_FromVoidPtr(obj);
XIncref(obj);
try
{
int res = PySet_Add(set, p);
PythonException.ThrowIfIsNotZero(res);
}
finally
{
XDecref(p);
}
}
/// <summary>
/// Exchange gc to a dummy gc prevent nullptr error in _PyObject_GC_UnTrack macro.
/// </summary>
private static void ExchangeGCChain(IntPtr obj, IntPtr gc)
{
var head = _Py_AS_GC(obj);
if ((long)_PyGCHead_REFS(head) == _PyGC_REFS_UNTRACKED)
{
throw new ArgumentException("GC object untracked");
}
unsafe
{
var g = (PyGC_Head*)head;
var newGCGen = (PyGC_Head*)gc;
((PyGC_Head*)g->gc.gc_prev)->gc.gc_next = g->gc.gc_next;
((PyGC_Head*)g->gc.gc_next)->gc.gc_prev = g->gc.gc_prev;
g->gc.gc_next = gc;
g->gc.gc_prev = newGCGen->gc.gc_prev;
((PyGC_Head*)g->gc.gc_prev)->gc.gc_next = head;
newGCGen->gc.gc_prev = head;
}
}
private static IEnumerable<IntPtr> IterGCNodes(IntPtr gc)
{
var node = GetNextGCNode(gc);
while (node != gc)
{
var next = GetNextGCNode(node);
yield return node;
node = next;
}
}
private static IEnumerable<IntPtr> IterObjects(IntPtr gc)
{
foreach (var node in IterGCNodes(gc))
{
yield return _Py_FROM_GC(node);
}
}
private static unsafe IntPtr GetNextGCNode(IntPtr node)
{
return ((PyGC_Head*)node)->gc.gc_next;
}
}
}