Debian Codegraph @

src/c/misc_thread_common.h

raw
1 #ifndef CFFI_MISC_THREAD_COMMON_H
2 #define CFFI_MISC_THREAD_COMMON_H
3 #ifndef WITH_THREAD
4 # error "xxx no-thread configuration not tested, please report if you need that"
5 #endif
6 #include "pythread.h"
7 #include "inttypes.h"
8
9
10 struct cffi_tls_s {
11 /* The current thread's ThreadCanaryObj. This is only non-null in
12 case cffi builds the thread state here. It remains null if this
13 thread had already a thread state provided by CPython. */
14 struct thread_canary_s *local_thread_canary;
15
16 #ifndef USE__THREAD
17 /* The saved errno. If the C compiler supports '__thread', then
18 we use that instead. */
19 int saved_errno;
20 #endif
21
22 #ifdef MS_WIN32
23 /* The saved lasterror, on Windows. */
24 int saved_lasterror;
25 #endif
26 };
27
28 static struct cffi_tls_s *get_cffi_tls(void); /* in misc_thread_posix.h
29 or misc_win32.h */
30
31
32 /* We try to keep the PyThreadState around in a thread not started by
33 * Python but where cffi callbacks occur. If we didn't do that, then
34 * the standard logic in PyGILState_Ensure() and PyGILState_Release()
35 * would create a new PyThreadState and completely free it for every
36 * single call. For some applications, this is a huge slow-down.
37 *
38 * As shown by issue #362, it is quite messy to do. The current
39 * solution is to keep the PyThreadState alive by incrementing its
40 * 'gilstate_counter'. We detect thread shut-down, and we put the
41 * PyThreadState inside a list of zombies (we can't free it
42 * immediately because we don't have the GIL at that point in time).
43 * We also detect other pieces of code (notably Py_Finalize()) which
44 * clear and free PyThreadStates under our feet, using ThreadCanaryObj.
45 */
46
47 #define TLS_ZOM_LOCK() PyThread_acquire_lock(cffi_zombie_lock, WAIT_LOCK)
48 #define TLS_ZOM_UNLOCK() PyThread_release_lock(cffi_zombie_lock)
49 static PyThread_type_lock cffi_zombie_lock = NULL;
50
51
52 /* A 'canary' object is created in a thread when there is a callback
53 invoked, and that thread has no PyThreadState so far. It is an
54 object of reference count equal to 1, which is stored in the
55 PyThreadState->dict. Two things can occur then:
56
57 1. The PyThreadState can be forcefully cleared by Py_Finalize().
58 Then thread_canary_dealloc() is called, and we have to cancel
59 the hacks we did to keep the PyThreadState alive.
60
61 2. The thread finishes. In that case, we put the canary in a list
62 of zombies, and at some convenient time later when we have the
63 GIL, we free all PyThreadStates in the zombie list.
64
65 Some more fun comes from the fact that thread_canary_dealloc() can
66 be called at a point where the canary is in the zombie list already.
67 Also, the various pieces are freed at specific points in time, and
68 we must make sure not to access already-freed structures:
69
70 - the struct cffi_tls_s is valid until the thread shuts down, and
71 then it is freed by cffi_thread_shutdown().
72
73 - the canary is a normal Python object, but we have a borrowed
74 reference to it from cffi_tls_s.local_thread_canary.
75 */
76
77 typedef struct thread_canary_s {
78 PyObject_HEAD
79 struct thread_canary_s *zombie_prev, *zombie_next;
80 PyThreadState *tstate;
81 struct cffi_tls_s *tls;
82 } ThreadCanaryObj;
83
84 static PyTypeObject ThreadCanary_Type; /* forward */
85 static ThreadCanaryObj cffi_zombie_head;
86
87 static void
88 _thread_canary_detach_with_lock(ThreadCanaryObj *ob)
89 {
90 /* must be called with both the GIL and TLS_ZOM_LOCK. */
91 ThreadCanaryObj *p, *n;
92 p = ob->zombie_prev;
93 n = ob->zombie_next;
94 p->zombie_next = n;
95 n->zombie_prev = p;
96 ob->zombie_prev = NULL;
97 ob->zombie_next = NULL;
98 }
99
100 static void
101 thread_canary_dealloc(ThreadCanaryObj *ob)
102 {
103 /* this ThreadCanaryObj is being freed: if it is in the zombie
104 chained list, remove it. Thread-safety: 'zombie_next' amd
105 'local_thread_canary' accesses need to be protected with
106 the TLS_ZOM_LOCK.
107 */
108 //fprintf(stderr, "entering dealloc(%p)\n", ob);
109 TLS_ZOM_LOCK();
110 if (ob->zombie_next != NULL) {
111 //fprintf(stderr, "thread_canary_dealloc(%p): ZOMBIE\n", ob);
112 _thread_canary_detach_with_lock(ob);
113 }
114 else {
115 //fprintf(stderr, "thread_canary_dealloc(%p): not a zombie\n", ob);
116 }
117
118 if (ob->tls != NULL) {
119 //fprintf(stderr, "thread_canary_dealloc(%p): was local_thread_canary\n", ob);
120 assert(ob->tls->local_thread_canary == ob);
121 ob->tls->local_thread_canary = NULL;
122 }
123 TLS_ZOM_UNLOCK();
124
125 PyObject_Del((PyObject *)ob);
126 }
127
128 static void
129 thread_canary_make_zombie(ThreadCanaryObj *ob)
130 {
131 /* This must be called without the GIL, but with the TLS_ZOM_LOCK.
132 It must be called at most once for a given ThreadCanaryObj. */
133 ThreadCanaryObj *last;
134
135 //fprintf(stderr, "thread_canary_make_zombie(%p)\n", ob);
136 if (ob->zombie_next)
137 Py_FatalError("cffi: ThreadCanaryObj is already a zombie");
138 last = cffi_zombie_head.zombie_prev;
139 ob->zombie_next = &cffi_zombie_head;
140 ob->zombie_prev = last;
141 last->zombie_next = ob;
142 cffi_zombie_head.zombie_prev = ob;
143 //fprintf(stderr, "thread_canary_make_zombie(%p) DONE\n", ob);
144 }
145
146 static void
147 thread_canary_free_zombies(void)
148 {
149 /* This must be called with the GIL. */
150 if (cffi_zombie_head.zombie_next == &cffi_zombie_head)
151 return; /* fast path */
152
153 while (1) {
154 ThreadCanaryObj *ob;
155 PyThreadState *tstate = NULL;
156
157 TLS_ZOM_LOCK();
158 ob = cffi_zombie_head.zombie_next;
159 if (ob != &cffi_zombie_head) {
160 tstate = ob->tstate;
161 //fprintf(stderr, "thread_canary_free_zombie(%p) tstate=%p\n", ob, tstate);
162 _thread_canary_detach_with_lock(ob);
163 if (tstate == NULL)
164 Py_FatalError("cffi: invalid ThreadCanaryObj->tstate");
165 }
166 TLS_ZOM_UNLOCK();
167
168 if (tstate == NULL)
169 break;
170 PyThreadState_Clear(tstate); /* calls thread_canary_dealloc on 'ob',
171 but now ob->zombie_next == NULL. */
172 #if PY_VERSION_HEX >= 0x030C0000
173 /* this might be a bug introduced in 3.12, or just me abusing the
174 API around there. The issue is that PyThreadState_Delete()
175 called on a random old tstate will clear the *current* thread
176 notion of what PyGILState_GetThisThreadState() should be, at
177 least if the internal 'bound_gilstate' flag is set in the old
178 tstate. Workaround: clear that flag. */
179 tstate->_status.bound_gilstate = 0;
180 #endif
181 PyThreadState_Delete(tstate);
182 //fprintf(stderr, "thread_canary_free_zombie: cleared and deleted tstate=%p\n", tstate);
183 }
184 //fprintf(stderr, "thread_canary_free_zombie: end\n");
185 }
186
187 static void
188 thread_canary_register(PyThreadState *tstate)
189 {
190 /* called with the GIL; 'tstate' is the current PyThreadState. */
191 ThreadCanaryObj *canary;
192 PyObject *tdict;
193 struct cffi_tls_s *tls;
194 int err;
195
196 /* first free the zombies, if any */
197 thread_canary_free_zombies();
198
199 tls = get_cffi_tls();
200 if (tls == NULL)
201 goto ignore_error;
202
203 tdict = PyThreadState_GetDict();
204 if (tdict == NULL)
205 goto ignore_error;
206
207 canary = PyObject_New(ThreadCanaryObj, &ThreadCanary_Type);
208 //fprintf(stderr, "thread_canary_register(%p): tstate=%p tls=%p\n", canary, tstate, tls);
209 if (canary == NULL)
210 goto ignore_error;
211 canary->zombie_prev = NULL;
212 canary->zombie_next = NULL;
213 canary->tstate = tstate;
214 canary->tls = tls;
215
216 err = PyDict_SetItemString(tdict, "cffi.thread.canary", (PyObject *)canary);
217 Py_DECREF(canary);
218 if (err < 0)
219 goto ignore_error;
220
221 /* thread-safety: we have the GIL here, and 'tstate' is the one that
222 corresponds to our own thread. We are allocating a new 'canary'
223 and setting it up for our own thread, both in 'tdict' (which owns
224 the reference) and in 'tls->local_thread_canary' (which doesn't). */
225 assert(Py_REFCNT(canary) == 1);
226 tls->local_thread_canary = canary;
227 {
228 /* this extra PyGILState_Ensure() is deliberately never paired
229 with a PyGILState_Release(), so 'tstate' is never
230 automatically freed by PyGILState_Release() */
231 PyGILState_STATE state = PyGILState_Ensure();
232 assert(state == PyGILState_LOCKED);
233 (void)state;
234 }
235 //fprintf(stderr, "CANARY: ready, tstate=%p, tls=%p, canary=%p\n", tstate, tls, canary);
236 return;
237
238 ignore_error:
239 //fprintf(stderr, "CANARY: IGNORED ERROR\n");
240 PyErr_Clear();
241 }
242
243 static PyTypeObject ThreadCanary_Type = {
244 PyVarObject_HEAD_INIT(NULL, 0)
245 "_cffi_backend.thread_canary",
246 sizeof(ThreadCanaryObj),
247 0,
248 (destructor)thread_canary_dealloc, /* tp_dealloc */
249 0, /* tp_print */
250 0, /* tp_getattr */
251 0, /* tp_setattr */
252 0, /* tp_compare */
253 0, /* tp_repr */
254 0, /* tp_as_number */
255 0, /* tp_as_sequence */
256 0, /* tp_as_mapping */
257 0, /* tp_hash */
258 0, /* tp_call */
259 0, /* tp_str */
260 0, /* tp_getattro */
261 0, /* tp_setattro */
262 0, /* tp_as_buffer */
263 Py_TPFLAGS_DEFAULT, /* tp_flags */
264 };
265
266 static void init_cffi_tls_zombie(void)
267 {
268 cffi_zombie_head.zombie_next = &cffi_zombie_head;
269 cffi_zombie_head.zombie_prev = &cffi_zombie_head;
270 cffi_zombie_lock = PyThread_allocate_lock();
271 if (cffi_zombie_lock == NULL)
272 PyErr_SetString(PyExc_SystemError, "can't allocate cffi_zombie_lock");
273 }
274
275 static void cffi_thread_shutdown(void *p)
276 {
277 /* this function is called from misc_thread_posix or misc_win32
278 when a thread is about to end. */
279 struct cffi_tls_s *tls = (struct cffi_tls_s *)p;
280
281 /* thread-safety: this field 'local_thread_canary' can be reset
282 to NULL in parallel, protected by TLS_ZOM_LOCK. */
283 TLS_ZOM_LOCK();
284 if (tls->local_thread_canary != NULL) {
285 tls->local_thread_canary->tls = NULL;
286 thread_canary_make_zombie(tls->local_thread_canary);
287 }
288 TLS_ZOM_UNLOCK();
289 //fprintf(stderr, "thread_shutdown(%p)\n", tls);
290 free(tls);
291 }
292
293 /* USE__THREAD is defined by setup.py if it finds that it is
294 syntactically valid to use "__thread" with this C compiler. */
295 #ifdef USE__THREAD
296
297 static __thread int cffi_saved_errno = 0;
298 static void save_errno_only(void) { cffi_saved_errno = errno; }
299 static void restore_errno_only(void) { errno = cffi_saved_errno; }
300
301 #else
302
303 static void save_errno_only(void)
304 {
305 int saved = errno;
306 struct cffi_tls_s *tls = get_cffi_tls();
307 if (tls != NULL)
308 tls->saved_errno = saved;
309 }
310
311 static void restore_errno_only(void)
312 {
313 struct cffi_tls_s *tls = get_cffi_tls();
314 if (tls != NULL)
315 errno = tls->saved_errno;
316 }
317
318 #endif
319
320
321 static PyGILState_STATE gil_ensure(void)
322 {
323 /* Called at the start of a callback. */
324 PyGILState_STATE result;
325 PyThreadState *ts = PyGILState_GetThisThreadState();
326 //fprintf(stderr, "%p: gil_ensure(), tstate=%p, tls=%p\n", get_cffi_tls(), ts, get_cffi_tls());
327
328 if (ts != NULL) {
329 /* common case: this thread already has a thread state */
330 return PyGILState_Ensure();
331 }
332 else {
333 /* no thread state here so far. */
334 result = PyGILState_Ensure();
335 assert(result == PyGILState_UNLOCKED);
336
337 ts = PyGILState_GetThisThreadState();
338 //fprintf(stderr, "%p: gil_ensure(), made a new tstate=%p\n", get_cffi_tls(), ts);
339 assert(ts != NULL);
340
341 /* Use the ThreadCanary mechanism to keep 'ts' alive until the
342 thread really shuts down */
343 thread_canary_register(ts);
344
345 assert(ts == PyGILState_GetThisThreadState());
346 return result;
347 }
348 }
349
350 static void gil_release(PyGILState_STATE oldstate)
351 {
352 //fprintf(stderr, "%p: gil_release(%d), tls=%p\n", get_cffi_tls(), (int)oldstate, get_cffi_tls());
353 PyGILState_Release(oldstate);
354 }
355
356
357 #if PY_VERSION_HEX <= 0x030d00b3
358 # define Py_BEGIN_CRITICAL_SECTION(op) {
359 # define Py_END_CRITICAL_SECTION() }
360 #endif
361
362 #ifdef Py_GIL_DISABLED
363 static PyObject _dummy = {0};
364 #define cffi_check_flag(arg) cffi_atomic_load_uint8(&(arg))
365 #define cffi_set_flag(arg, value) cffi_atomic_store_uint8(&(arg), (value))
366 #define cffi_set_size(arg, value) cffi_atomic_store_ssize(&(arg)->ct_size, (value))
367 #define cffi_get_size(arg) cffi_atomic_load_ssize(&(arg)->ct_size)
368 #define _CFFI_LOAD_OP(arg) cffi_atomic_load(&(arg))
369 #else
370 #define cffi_check_flag(arg) (arg)
371 #define cffi_set_flag(arg, value) (arg) = (value)
372 #define cffi_set_size(arg, value) (arg)->ct_size = (value)
373 #define cffi_get_size(arg) (arg)->ct_size
374 #define _CFFI_LOAD_OP(arg) (arg)
375 #endif
376
377 #define CFFI_LOCK() Py_BEGIN_CRITICAL_SECTION(&_dummy)
378 #define CFFI_UNLOCK() Py_END_CRITICAL_SECTION()
379
380 #endif /* CFFI_MISC_THREAD_COMMON_H */