misc_thread_common.h 14 KB

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