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
223 lines (202 loc) · 7.32 KB
/
runtime_state.cs
File metadata and controls
223 lines (202 loc) · 7.32 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
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");
}
NewReference objs = default;
if (ShouldRestoreObjects)
{
objs = PySet_New(default);
foreach (var objRaw in PyGCGetObjects())
{
AddObjPtrToSet(objs, new BorrowedReference(objRaw));
}
}
var modules = PySet_New(default);
foreach (var name in GetModuleNames())
{
int res = PySet_Add(modules, new BorrowedReference(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;
}
{
using var pyDummyGC = PyLong_FromVoidPtr(dummyGCHead);
int res = PySys_SetObject("dummy_gc", pyDummyGC);
PythonException.ThrowIfIsNotZero(res);
try
{
res = PySys_SetObject("initial_modules", modules);
PythonException.ThrowIfIsNotZero(res);
}
finally
{
modules.Dispose();
}
if (ShouldRestoreObjects)
{
AddObjPtrToSet(objs, modules);
try
{
res = PySys_SetObject("initial_objs", objs);
PythonException.ThrowIfIsNotZero(res);
}
finally
{
objs.Dispose();
}
}
}
}
public static void Restore()
{
var dummyGCAddr = PySys_GetObject("dummy_gc");
if (dummyGCAddr.IsNull)
{
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 nameRaw in GetModuleNames())
{
var name = new BorrowedReference(nameRaw);
if (PySet_Contains(intialModules, 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");
}
BorrowedReference intialObjs = PySys_GetObject("initial_objs");
Debug.Assert(@intialObjs.IsNull);
foreach (var objRaw in PyGCGetObjects())
{
using var p = PyLong_FromVoidPtr(objRaw);
var obj = new BorrowedReference(objRaw);
if (PySet_Contains(intialObjs, p) == 1)
{
continue;
}
Debug.Assert(_PyObject_GC_IS_TRACKED(obj), "A GC object must be tracked");
ExchangeGCChain(obj, dummyGC);
}
}
public static IEnumerable<IntPtr> PyGCGetObjects()
{
using var gc = PyModule.Import("gc");
using var get_objects = gc.GetAttr("get_objects");
var objs = PyObject_CallObject(get_objects.Handle, 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();
}
}
public static IEnumerable<IntPtr> GetModuleNames()
{
var modules = PyImport_GetModuleDict();
using var names = PyDict_Keys(modules);
var length = PyList_Size(names);
var result = new IntPtr[length];
for (int i = 0; i < length; i++)
{
result[i] = PyList_GetItem(names, i).DangerousGetAddress();
}
return result;
}
private static void AddObjPtrToSet(BorrowedReference set, BorrowedReference obj)
{
IntPtr objRaw = obj.DangerousGetAddress();
using var p = PyLong_FromVoidPtr(objRaw);
XIncref(objRaw);
int res = PySet_Add(set, p);
PythonException.ThrowIfIsNotZero(res);
}
/// <summary>
/// Exchange gc to a dummy gc prevent nullptr error in _PyObject_GC_UnTrack macro.
/// </summary>
private static void ExchangeGCChain(BorrowedReference 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;
}
}
}