misc_thread_common.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. TLS_ZOM_LOCK();
  87. if (ob->zombie_next != NULL) {
  88. //fprintf(stderr, "thread_canary_dealloc(%p): ZOMBIE\n", ob);
  89. _thread_canary_detach_with_lock(ob);
  90. }
  91. else {
  92. //fprintf(stderr, "thread_canary_dealloc(%p): not a zombie\n", ob);
  93. }
  94. if (ob->tls != NULL) {
  95. //fprintf(stderr, "thread_canary_dealloc(%p): was local_thread_canary\n", ob);
  96. assert(ob->tls->local_thread_canary == ob);
  97. ob->tls->local_thread_canary = NULL;
  98. }
  99. TLS_ZOM_UNLOCK();
  100. PyObject_Del((PyObject *)ob);
  101. }
  102. static void
  103. thread_canary_make_zombie(ThreadCanaryObj *ob)
  104. {
  105. /* This must be called without the GIL, but with the TLS_ZOM_LOCK.
  106. It must be called at most once for a given ThreadCanaryObj. */
  107. ThreadCanaryObj *last;
  108. //fprintf(stderr, "thread_canary_make_zombie(%p)\n", ob);
  109. if (ob->zombie_next)
  110. Py_FatalError("cffi: ThreadCanaryObj is already a zombie");
  111. last = cffi_zombie_head.zombie_prev;
  112. ob->zombie_next = &cffi_zombie_head;
  113. ob->zombie_prev = last;
  114. last->zombie_next = ob;
  115. cffi_zombie_head.zombie_prev = ob;
  116. }
  117. static void
  118. thread_canary_free_zombies(void)
  119. {
  120. /* This must be called with the GIL. */
  121. if (cffi_zombie_head.zombie_next == &cffi_zombie_head)
  122. return; /* fast path */
  123. while (1) {
  124. ThreadCanaryObj *ob;
  125. PyThreadState *tstate = NULL;
  126. TLS_ZOM_LOCK();
  127. ob = cffi_zombie_head.zombie_next;
  128. if (ob != &cffi_zombie_head) {
  129. tstate = ob->tstate;
  130. //fprintf(stderr, "thread_canary_free_zombie(%p) tstate=%p\n", ob, tstate);
  131. _thread_canary_detach_with_lock(ob);
  132. if (tstate == NULL)
  133. Py_FatalError("cffi: invalid ThreadCanaryObj->tstate");
  134. }
  135. TLS_ZOM_UNLOCK();
  136. if (tstate == NULL)
  137. break;
  138. PyThreadState_Clear(tstate); /* calls thread_canary_dealloc on 'ob',
  139. but now ob->zombie_next == NULL. */
  140. PyThreadState_Delete(tstate);
  141. //fprintf(stderr, "thread_canary_free_zombie: cleared and deleted tstate=%p\n", tstate);
  142. }
  143. //fprintf(stderr, "thread_canary_free_zombie: end\n");
  144. }
  145. static void
  146. thread_canary_register(PyThreadState *tstate)
  147. {
  148. /* called with the GIL; 'tstate' is the current PyThreadState. */
  149. ThreadCanaryObj *canary;
  150. PyObject *tdict;
  151. struct cffi_tls_s *tls;
  152. int err;
  153. /* first free the zombies, if any */
  154. thread_canary_free_zombies();
  155. tls = get_cffi_tls();
  156. if (tls == NULL)
  157. goto ignore_error;
  158. tdict = PyThreadState_GetDict();
  159. if (tdict == NULL)
  160. goto ignore_error;
  161. canary = PyObject_New(ThreadCanaryObj, &ThreadCanary_Type);
  162. //fprintf(stderr, "thread_canary_register(%p): tstate=%p tls=%p\n", canary, tstate, tls);
  163. if (canary == NULL)
  164. goto ignore_error;
  165. canary->zombie_prev = NULL;
  166. canary->zombie_next = NULL;
  167. canary->tstate = tstate;
  168. canary->tls = tls;
  169. err = PyDict_SetItemString(tdict, "cffi.thread.canary", (PyObject *)canary);
  170. Py_DECREF(canary);
  171. if (err < 0)
  172. goto ignore_error;
  173. /* thread-safety: we have the GIL here, and 'tstate' is the one that
  174. corresponds to our own thread. We are allocating a new 'canary'
  175. and setting it up for our own thread, both in 'tdict' (which owns
  176. the reference) and in 'tls->local_thread_canary' (which doesn't). */
  177. assert(Py_REFCNT(canary) == 1);
  178. tls->local_thread_canary = canary;
  179. tstate->gilstate_counter++;
  180. /* ^^^ this means 'tstate' will never be automatically freed by
  181. PyGILState_Release() */
  182. return;
  183. ignore_error:
  184. PyErr_Clear();
  185. }
  186. static PyTypeObject ThreadCanary_Type = {
  187. PyVarObject_HEAD_INIT(NULL, 0)
  188. "_cffi_backend.thread_canary",
  189. sizeof(ThreadCanaryObj),
  190. 0,
  191. (destructor)thread_canary_dealloc, /* tp_dealloc */
  192. 0, /* tp_print */
  193. 0, /* tp_getattr */
  194. 0, /* tp_setattr */
  195. 0, /* tp_compare */
  196. 0, /* tp_repr */
  197. 0, /* tp_as_number */
  198. 0, /* tp_as_sequence */
  199. 0, /* tp_as_mapping */
  200. 0, /* tp_hash */
  201. 0, /* tp_call */
  202. 0, /* tp_str */
  203. 0, /* tp_getattro */
  204. 0, /* tp_setattro */
  205. 0, /* tp_as_buffer */
  206. Py_TPFLAGS_DEFAULT, /* tp_flags */
  207. };
  208. static void init_cffi_tls_zombie(void)
  209. {
  210. cffi_zombie_head.zombie_next = &cffi_zombie_head;
  211. cffi_zombie_head.zombie_prev = &cffi_zombie_head;
  212. cffi_zombie_lock = PyThread_allocate_lock();
  213. if (cffi_zombie_lock == NULL)
  214. PyErr_SetString(PyExc_SystemError, "can't allocate cffi_zombie_lock");
  215. }
  216. static void cffi_thread_shutdown(void *p)
  217. {
  218. /* this function is called from misc_thread_posix or misc_win32
  219. when a thread is about to end. */
  220. struct cffi_tls_s *tls = (struct cffi_tls_s *)p;
  221. /* thread-safety: this field 'local_thread_canary' can be reset
  222. to NULL in parallel, protected by TLS_ZOM_LOCK. */
  223. TLS_ZOM_LOCK();
  224. if (tls->local_thread_canary != NULL) {
  225. tls->local_thread_canary->tls = NULL;
  226. thread_canary_make_zombie(tls->local_thread_canary);
  227. }
  228. TLS_ZOM_UNLOCK();
  229. //fprintf(stderr, "thread_shutdown(%p)\n", tls);
  230. free(tls);
  231. }
  232. /* USE__THREAD is defined by setup.py if it finds that it is
  233. syntactically valid to use "__thread" with this C compiler. */
  234. #ifdef USE__THREAD
  235. static __thread int cffi_saved_errno = 0;
  236. static void save_errno_only(void) { cffi_saved_errno = errno; }
  237. static void restore_errno_only(void) { errno = cffi_saved_errno; }
  238. #else
  239. static void save_errno_only(void)
  240. {
  241. int saved = errno;
  242. struct cffi_tls_s *tls = get_cffi_tls();
  243. if (tls != NULL)
  244. tls->saved_errno = saved;
  245. }
  246. static void restore_errno_only(void)
  247. {
  248. struct cffi_tls_s *tls = get_cffi_tls();
  249. if (tls != NULL)
  250. errno = tls->saved_errno;
  251. }
  252. #endif
  253. /* MESS. We can't use PyThreadState_GET(), because that calls
  254. PyThreadState_Get() which fails an assert if the result is NULL.
  255. * in Python 2.7 and <= 3.4, the variable _PyThreadState_Current
  256. is directly available, so use that.
  257. * in Python 3.5, the variable is available too, but it might be
  258. the case that the headers don't define it (this changed in 3.5.1).
  259. In case we're compiling with 3.5.x with x >= 1, we need to
  260. manually define this variable.
  261. * in Python >= 3.6 there is _PyThreadState_UncheckedGet().
  262. It was added in 3.5.2 but should never be used in 3.5.x
  263. because it is not available in 3.5.0 or 3.5.1.
  264. */
  265. #if PY_VERSION_HEX >= 0x03050100 && PY_VERSION_HEX < 0x03060000
  266. PyAPI_DATA(void *volatile) _PyThreadState_Current;
  267. #endif
  268. static PyThreadState *get_current_ts(void)
  269. {
  270. #if PY_VERSION_HEX >= 0x03060000
  271. return _PyThreadState_UncheckedGet();
  272. #elif defined(_Py_atomic_load_relaxed)
  273. return (PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current);
  274. #else
  275. return (PyThreadState*)_PyThreadState_Current; /* assume atomic read */
  276. #endif
  277. }
  278. static PyGILState_STATE gil_ensure(void)
  279. {
  280. /* Called at the start of a callback. Replacement for
  281. PyGILState_Ensure().
  282. */
  283. PyGILState_STATE result;
  284. PyThreadState *ts = PyGILState_GetThisThreadState();
  285. if (ts != NULL) {
  286. ts->gilstate_counter++;
  287. if (ts != get_current_ts()) {
  288. /* common case: 'ts' is our non-current thread state and
  289. we have to make it current and acquire the GIL */
  290. PyEval_RestoreThread(ts);
  291. return PyGILState_UNLOCKED;
  292. }
  293. else {
  294. return PyGILState_LOCKED;
  295. }
  296. }
  297. else {
  298. /* no thread state here so far. */
  299. result = PyGILState_Ensure();
  300. assert(result == PyGILState_UNLOCKED);
  301. ts = PyGILState_GetThisThreadState();
  302. assert(ts != NULL);
  303. assert(ts == get_current_ts());
  304. assert(ts->gilstate_counter >= 1);
  305. /* Use the ThreadCanary mechanism to keep 'ts' alive until the
  306. thread really shuts down */
  307. thread_canary_register(ts);
  308. return result;
  309. }
  310. }
  311. static void gil_release(PyGILState_STATE oldstate)
  312. {
  313. PyGILState_Release(oldstate);
  314. }