You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

662 lines
19 KiB

  1. /* Thread and interpreter state structures and their interfaces */
  2. #include "Python.h"
  3. /* --------------------------------------------------------------------------
  4. CAUTION
  5. Always use malloc() and free() directly in this file. A number of these
  6. functions are advertised as safe to call when the GIL isn't held, and in
  7. a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's debugging
  8. obmalloc functions. Those aren't thread-safe (they rely on the GIL to avoid
  9. the expense of doing their own locking).
  10. -------------------------------------------------------------------------- */
  11. #ifdef HAVE_DLOPEN
  12. #ifdef HAVE_DLFCN_H
  13. #include <dlfcn.h>
  14. #endif
  15. #ifndef RTLD_LAZY
  16. #define RTLD_LAZY 1
  17. #endif
  18. #endif
  19. #ifdef __cplusplus
  20. extern "C" {
  21. #endif
  22. #ifdef WITH_THREAD
  23. #include "pythread.h"
  24. static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
  25. #define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
  26. #define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
  27. #define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
  28. /* The single PyInterpreterState used by this process'
  29. GILState implementation
  30. */
  31. static PyInterpreterState *autoInterpreterState = NULL;
  32. static int autoTLSkey = 0;
  33. #else
  34. #define HEAD_INIT() /* Nothing */
  35. #define HEAD_LOCK() /* Nothing */
  36. #define HEAD_UNLOCK() /* Nothing */
  37. #endif
  38. static PyInterpreterState *interp_head = NULL;
  39. PyThreadState *_PyThreadState_Current = NULL;
  40. PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
  41. #ifdef WITH_THREAD
  42. static void _PyGILState_NoteThreadState(PyThreadState* tstate);
  43. #endif
  44. PyInterpreterState *
  45. PyInterpreterState_New(void)
  46. {
  47. PyInterpreterState *interp = (PyInterpreterState *)
  48. malloc(sizeof(PyInterpreterState));
  49. if (interp != NULL) {
  50. HEAD_INIT();
  51. #ifdef WITH_THREAD
  52. if (head_mutex == NULL)
  53. Py_FatalError("Can't initialize threads for interpreter");
  54. #endif
  55. interp->modules = NULL;
  56. interp->modules_reloading = NULL;
  57. interp->sysdict = NULL;
  58. interp->builtins = NULL;
  59. interp->tstate_head = NULL;
  60. interp->codec_search_path = NULL;
  61. interp->codec_search_cache = NULL;
  62. interp->codec_error_registry = NULL;
  63. #ifdef HAVE_DLOPEN
  64. #ifdef RTLD_NOW
  65. interp->dlopenflags = RTLD_NOW;
  66. #else
  67. interp->dlopenflags = RTLD_LAZY;
  68. #endif
  69. #endif
  70. #ifdef WITH_TSC
  71. interp->tscdump = 0;
  72. #endif
  73. HEAD_LOCK();
  74. interp->next = interp_head;
  75. interp_head = interp;
  76. HEAD_UNLOCK();
  77. }
  78. return interp;
  79. }
  80. void
  81. PyInterpreterState_Clear(PyInterpreterState *interp)
  82. {
  83. PyThreadState *p;
  84. HEAD_LOCK();
  85. for (p = interp->tstate_head; p != NULL; p = p->next)
  86. PyThreadState_Clear(p);
  87. HEAD_UNLOCK();
  88. Py_CLEAR(interp->codec_search_path);
  89. Py_CLEAR(interp->codec_search_cache);
  90. Py_CLEAR(interp->codec_error_registry);
  91. Py_CLEAR(interp->modules);
  92. Py_CLEAR(interp->modules_reloading);
  93. Py_CLEAR(interp->sysdict);
  94. Py_CLEAR(interp->builtins);
  95. }
  96. static void
  97. zapthreads(PyInterpreterState *interp)
  98. {
  99. PyThreadState *p;
  100. /* No need to lock the mutex here because this should only happen
  101. when the threads are all really dead (XXX famous last words). */
  102. while ((p = interp->tstate_head) != NULL) {
  103. PyThreadState_Delete(p);
  104. }
  105. }
  106. void
  107. PyInterpreterState_Delete(PyInterpreterState *interp)
  108. {
  109. PyInterpreterState **p;
  110. zapthreads(interp);
  111. HEAD_LOCK();
  112. for (p = &interp_head; ; p = &(*p)->next) {
  113. if (*p == NULL)
  114. Py_FatalError(
  115. "PyInterpreterState_Delete: invalid interp");
  116. if (*p == interp)
  117. break;
  118. }
  119. if (interp->tstate_head != NULL)
  120. Py_FatalError("PyInterpreterState_Delete: remaining threads");
  121. *p = interp->next;
  122. HEAD_UNLOCK();
  123. free(interp);
  124. }
  125. /* Default implementation for _PyThreadState_GetFrame */
  126. static struct _frame *
  127. threadstate_getframe(PyThreadState *self)
  128. {
  129. return self->frame;
  130. }
  131. static PyThreadState *
  132. new_threadstate(PyInterpreterState *interp, int init)
  133. {
  134. PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState));
  135. if (_PyThreadState_GetFrame == NULL)
  136. _PyThreadState_GetFrame = threadstate_getframe;
  137. if (tstate != NULL) {
  138. tstate->interp = interp;
  139. tstate->frame = NULL;
  140. tstate->recursion_depth = 0;
  141. tstate->tracing = 0;
  142. tstate->use_tracing = 0;
  143. tstate->tick_counter = 0;
  144. tstate->gilstate_counter = 0;
  145. tstate->async_exc = NULL;
  146. #ifdef WITH_THREAD
  147. tstate->thread_id = PyThread_get_thread_ident();
  148. #else
  149. tstate->thread_id = 0;
  150. #endif
  151. tstate->dict = NULL;
  152. tstate->curexc_type = NULL;
  153. tstate->curexc_value = NULL;
  154. tstate->curexc_traceback = NULL;
  155. tstate->exc_type = NULL;
  156. tstate->exc_value = NULL;
  157. tstate->exc_traceback = NULL;
  158. tstate->c_profilefunc = NULL;
  159. tstate->c_tracefunc = NULL;
  160. tstate->c_profileobj = NULL;
  161. tstate->c_traceobj = NULL;
  162. if (init)
  163. _PyThreadState_Init(tstate);
  164. HEAD_LOCK();
  165. tstate->next = interp->tstate_head;
  166. interp->tstate_head = tstate;
  167. HEAD_UNLOCK();
  168. }
  169. return tstate;
  170. }
  171. PyThreadState *
  172. PyThreadState_New(PyInterpreterState *interp)
  173. {
  174. return new_threadstate(interp, 1);
  175. }
  176. PyThreadState *
  177. _PyThreadState_Prealloc(PyInterpreterState *interp)
  178. {
  179. return new_threadstate(interp, 0);
  180. }
  181. void
  182. _PyThreadState_Init(PyThreadState *tstate)
  183. {
  184. #ifdef WITH_THREAD
  185. _PyGILState_NoteThreadState(tstate);
  186. #endif
  187. }
  188. void
  189. PyThreadState_Clear(PyThreadState *tstate)
  190. {
  191. if (Py_VerboseFlag && tstate->frame != NULL)
  192. fprintf(stderr,
  193. "PyThreadState_Clear: warning: thread still has a frame\n");
  194. Py_CLEAR(tstate->frame);
  195. Py_CLEAR(tstate->dict);
  196. Py_CLEAR(tstate->async_exc);
  197. Py_CLEAR(tstate->curexc_type);
  198. Py_CLEAR(tstate->curexc_value);
  199. Py_CLEAR(tstate->curexc_traceback);
  200. Py_CLEAR(tstate->exc_type);
  201. Py_CLEAR(tstate->exc_value);
  202. Py_CLEAR(tstate->exc_traceback);
  203. tstate->c_profilefunc = NULL;
  204. tstate->c_tracefunc = NULL;
  205. Py_CLEAR(tstate->c_profileobj);
  206. Py_CLEAR(tstate->c_traceobj);
  207. }
  208. /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
  209. static void
  210. tstate_delete_common(PyThreadState *tstate)
  211. {
  212. PyInterpreterState *interp;
  213. PyThreadState **p;
  214. PyThreadState *prev_p = NULL;
  215. if (tstate == NULL)
  216. Py_FatalError("PyThreadState_Delete: NULL tstate");
  217. interp = tstate->interp;
  218. if (interp == NULL)
  219. Py_FatalError("PyThreadState_Delete: NULL interp");
  220. HEAD_LOCK();
  221. for (p = &interp->tstate_head; ; p = &(*p)->next) {
  222. if (*p == NULL)
  223. Py_FatalError(
  224. "PyThreadState_Delete: invalid tstate");
  225. if (*p == tstate)
  226. break;
  227. /* Sanity check. These states should never happen but if
  228. * they do we must abort. Otherwise we'll end up spinning in
  229. * in a tight loop with the lock held. A similar check is done
  230. * in thread.c find_key(). */
  231. if (*p == prev_p)
  232. Py_FatalError(
  233. "PyThreadState_Delete: small circular list(!)"
  234. " and tstate not found.");
  235. prev_p = *p;
  236. if ((*p)->next == interp->tstate_head)
  237. Py_FatalError(
  238. "PyThreadState_Delete: circular list(!) and"
  239. " tstate not found.");
  240. }
  241. *p = tstate->next;
  242. HEAD_UNLOCK();
  243. free(tstate);
  244. }
  245. void
  246. PyThreadState_Delete(PyThreadState *tstate)
  247. {
  248. if (tstate == _PyThreadState_Current)
  249. Py_FatalError("PyThreadState_Delete: tstate is still current");
  250. tstate_delete_common(tstate);
  251. #ifdef WITH_THREAD
  252. if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
  253. PyThread_delete_key_value(autoTLSkey);
  254. #endif /* WITH_THREAD */
  255. }
  256. #ifdef WITH_THREAD
  257. void
  258. PyThreadState_DeleteCurrent()
  259. {
  260. PyThreadState *tstate = _PyThreadState_Current;
  261. if (tstate == NULL)
  262. Py_FatalError(
  263. "PyThreadState_DeleteCurrent: no current tstate");
  264. _PyThreadState_Current = NULL;
  265. tstate_delete_common(tstate);
  266. if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
  267. PyThread_delete_key_value(autoTLSkey);
  268. PyEval_ReleaseLock();
  269. }
  270. #endif /* WITH_THREAD */
  271. PyThreadState *
  272. PyThreadState_Get(void)
  273. {
  274. if (_PyThreadState_Current == NULL)
  275. Py_FatalError("PyThreadState_Get: no current thread");
  276. return _PyThreadState_Current;
  277. }
  278. PyThreadState *
  279. PyThreadState_Swap(PyThreadState *newts)
  280. {
  281. PyThreadState *oldts = _PyThreadState_Current;
  282. _PyThreadState_Current = newts;
  283. /* It should not be possible for more than one thread state
  284. to be used for a thread. Check this the best we can in debug
  285. builds.
  286. */
  287. #if defined(Py_DEBUG) && defined(WITH_THREAD)
  288. if (newts) {
  289. /* This can be called from PyEval_RestoreThread(). Similar
  290. to it, we need to ensure errno doesn't change.
  291. */
  292. int err = errno;
  293. PyThreadState *check = PyGILState_GetThisThreadState();
  294. if (check && check->interp == newts->interp && check != newts)
  295. Py_FatalError("Invalid thread state for this thread");
  296. errno = err;
  297. }
  298. #endif
  299. return oldts;
  300. }
  301. /* An extension mechanism to store arbitrary additional per-thread state.
  302. PyThreadState_GetDict() returns a dictionary that can be used to hold such
  303. state; the caller should pick a unique key and store its state there. If
  304. PyThreadState_GetDict() returns NULL, an exception has *not* been raised
  305. and the caller should assume no per-thread state is available. */
  306. PyObject *
  307. PyThreadState_GetDict(void)
  308. {
  309. if (_PyThreadState_Current == NULL)
  310. return NULL;
  311. if (_PyThreadState_Current->dict == NULL) {
  312. PyObject *d;
  313. _PyThreadState_Current->dict = d = PyDict_New();
  314. if (d == NULL)
  315. PyErr_Clear();
  316. }
  317. return _PyThreadState_Current->dict;
  318. }
  319. /* Asynchronously raise an exception in a thread.
  320. Requested by Just van Rossum and Alex Martelli.
  321. To prevent naive misuse, you must write your own extension
  322. to call this, or use ctypes. Must be called with the GIL held.
  323. Returns the number of tstates modified (normally 1, but 0 if `id` didn't
  324. match any known thread id). Can be called with exc=NULL to clear an
  325. existing async exception. This raises no exceptions. */
  326. int
  327. PyThreadState_SetAsyncExc(long id, PyObject *exc) {
  328. PyThreadState *tstate = PyThreadState_GET();
  329. PyInterpreterState *interp = tstate->interp;
  330. PyThreadState *p;
  331. /* Although the GIL is held, a few C API functions can be called
  332. * without the GIL held, and in particular some that create and
  333. * destroy thread and interpreter states. Those can mutate the
  334. * list of thread states we're traversing, so to prevent that we lock
  335. * head_mutex for the duration.
  336. */
  337. HEAD_LOCK();
  338. for (p = interp->tstate_head; p != NULL; p = p->next) {
  339. if (p->thread_id == id) {
  340. /* Tricky: we need to decref the current value
  341. * (if any) in p->async_exc, but that can in turn
  342. * allow arbitrary Python code to run, including
  343. * perhaps calls to this function. To prevent
  344. * deadlock, we need to release head_mutex before
  345. * the decref.
  346. */
  347. PyObject *old_exc = p->async_exc;
  348. Py_XINCREF(exc);
  349. p->async_exc = exc;
  350. HEAD_UNLOCK();
  351. Py_XDECREF(old_exc);
  352. return 1;
  353. }
  354. }
  355. HEAD_UNLOCK();
  356. return 0;
  357. }
  358. /* Routines for advanced debuggers, requested by David Beazley.
  359. Don't use unless you know what you are doing! */
  360. PyInterpreterState *
  361. PyInterpreterState_Head(void)
  362. {
  363. return interp_head;
  364. }
  365. PyInterpreterState *
  366. PyInterpreterState_Next(PyInterpreterState *interp) {
  367. return interp->next;
  368. }
  369. PyThreadState *
  370. PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
  371. return interp->tstate_head;
  372. }
  373. PyThreadState *
  374. PyThreadState_Next(PyThreadState *tstate) {
  375. return tstate->next;
  376. }
  377. /* The implementation of sys._current_frames(). This is intended to be
  378. called with the GIL held, as it will be when called via
  379. sys._current_frames(). It's possible it would work fine even without
  380. the GIL held, but haven't thought enough about that.
  381. */
  382. PyObject *
  383. _PyThread_CurrentFrames(void)
  384. {
  385. PyObject *result;
  386. PyInterpreterState *i;
  387. result = PyDict_New();
  388. if (result == NULL)
  389. return NULL;
  390. /* for i in all interpreters:
  391. * for t in all of i's thread states:
  392. * if t's frame isn't NULL, map t's id to its frame
  393. * Because these lists can mutate even when the GIL is held, we
  394. * need to grab head_mutex for the duration.
  395. */
  396. HEAD_LOCK();
  397. for (i = interp_head; i != NULL; i = i->next) {
  398. PyThreadState *t;
  399. for (t = i->tstate_head; t != NULL; t = t->next) {
  400. PyObject *id;
  401. int stat;
  402. struct _frame *frame = t->frame;
  403. if (frame == NULL)
  404. continue;
  405. id = PyInt_FromLong(t->thread_id);
  406. if (id == NULL)
  407. goto Fail;
  408. stat = PyDict_SetItem(result, id, (PyObject *)frame);
  409. Py_DECREF(id);
  410. if (stat < 0)
  411. goto Fail;
  412. }
  413. }
  414. HEAD_UNLOCK();
  415. return result;
  416. Fail:
  417. HEAD_UNLOCK();
  418. Py_DECREF(result);
  419. return NULL;
  420. }
  421. /* Python "auto thread state" API. */
  422. #ifdef WITH_THREAD
  423. /* Keep this as a static, as it is not reliable! It can only
  424. ever be compared to the state for the *current* thread.
  425. * If not equal, then it doesn't matter that the actual
  426. value may change immediately after comparison, as it can't
  427. possibly change to the current thread's state.
  428. * If equal, then the current thread holds the lock, so the value can't
  429. change until we yield the lock.
  430. */
  431. static int
  432. PyThreadState_IsCurrent(PyThreadState *tstate)
  433. {
  434. /* Must be the tstate for this thread */
  435. assert(PyGILState_GetThisThreadState()==tstate);
  436. /* On Windows at least, simple reads and writes to 32 bit values
  437. are atomic.
  438. */
  439. return tstate == _PyThreadState_Current;
  440. }
  441. /* Internal initialization/finalization functions called by
  442. Py_Initialize/Py_Finalize
  443. */
  444. void
  445. _PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
  446. {
  447. assert(i && t); /* must init with valid states */
  448. autoTLSkey = PyThread_create_key();
  449. autoInterpreterState = i;
  450. assert(PyThread_get_key_value(autoTLSkey) == NULL);
  451. assert(t->gilstate_counter == 0);
  452. _PyGILState_NoteThreadState(t);
  453. }
  454. void
  455. _PyGILState_Fini(void)
  456. {
  457. PyThread_delete_key(autoTLSkey);
  458. autoInterpreterState = NULL;
  459. }
  460. /* When a thread state is created for a thread by some mechanism other than
  461. PyGILState_Ensure, it's important that the GILState machinery knows about
  462. it so it doesn't try to create another thread state for the thread (this is
  463. a better fix for SF bug #1010677 than the first one attempted).
  464. */
  465. static void
  466. _PyGILState_NoteThreadState(PyThreadState* tstate)
  467. {
  468. /* If autoTLSkey isn't initialized, this must be the very first
  469. threadstate created in Py_Initialize(). Don't do anything for now
  470. (we'll be back here when _PyGILState_Init is called). */
  471. if (!autoInterpreterState)
  472. return;
  473. /* Stick the thread state for this thread in thread local storage.
  474. The only situation where you can legitimately have more than one
  475. thread state for an OS level thread is when there are multiple
  476. interpreters, when:
  477. a) You shouldn't really be using the PyGILState_ APIs anyway,
  478. and:
  479. b) The slightly odd way PyThread_set_key_value works (see
  480. comments by its implementation) means that the first thread
  481. state created for that given OS level thread will "win",
  482. which seems reasonable behaviour.
  483. */
  484. if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
  485. Py_FatalError("Couldn't create autoTLSkey mapping");
  486. /* PyGILState_Release must not try to delete this thread state. */
  487. tstate->gilstate_counter = 1;
  488. }
  489. /* The public functions */
  490. PyThreadState *
  491. PyGILState_GetThisThreadState(void)
  492. {
  493. if (autoInterpreterState == NULL)
  494. return NULL;
  495. return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
  496. }
  497. PyGILState_STATE
  498. PyGILState_Ensure(void)
  499. {
  500. int current;
  501. PyThreadState *tcur;
  502. /* Note that we do not auto-init Python here - apart from
  503. potential races with 2 threads auto-initializing, pep-311
  504. spells out other issues. Embedders are expected to have
  505. called Py_Initialize() and usually PyEval_InitThreads().
  506. */
  507. assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
  508. tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
  509. if (tcur == NULL) {
  510. /* Create a new thread state for this thread */
  511. tcur = PyThreadState_New(autoInterpreterState);
  512. if (tcur == NULL)
  513. Py_FatalError("Couldn't create thread-state for new thread");
  514. /* This is our thread state! We'll need to delete it in the
  515. matching call to PyGILState_Release(). */
  516. tcur->gilstate_counter = 0;
  517. current = 0; /* new thread state is never current */
  518. }
  519. else
  520. current = PyThreadState_IsCurrent(tcur);
  521. if (current == 0)
  522. PyEval_RestoreThread(tcur);
  523. /* Update our counter in the thread-state - no need for locks:
  524. - tcur will remain valid as we hold the GIL.
  525. - the counter is safe as we are the only thread "allowed"
  526. to modify this value
  527. */
  528. ++tcur->gilstate_counter;
  529. return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
  530. }
  531. void
  532. PyGILState_Release(PyGILState_STATE oldstate)
  533. {
  534. PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
  535. autoTLSkey);
  536. if (tcur == NULL)
  537. Py_FatalError("auto-releasing thread-state, "
  538. "but no thread-state for this thread");
  539. /* We must hold the GIL and have our thread state current */
  540. /* XXX - remove the check - the assert should be fine,
  541. but while this is very new (April 2003), the extra check
  542. by release-only users can't hurt.
  543. */
  544. if (! PyThreadState_IsCurrent(tcur))
  545. Py_FatalError("This thread state must be current when releasing");
  546. assert(PyThreadState_IsCurrent(tcur));
  547. --tcur->gilstate_counter;
  548. assert(tcur->gilstate_counter >= 0); /* illegal counter value */
  549. /* If we're going to destroy this thread-state, we must
  550. * clear it while the GIL is held, as destructors may run.
  551. */
  552. if (tcur->gilstate_counter == 0) {
  553. /* can't have been locked when we created it */
  554. assert(oldstate == PyGILState_UNLOCKED);
  555. PyThreadState_Clear(tcur);
  556. /* Delete the thread-state. Note this releases the GIL too!
  557. * It's vital that the GIL be held here, to avoid shutdown
  558. * races; see bugs 225673 and 1061968 (that nasty bug has a
  559. * habit of coming back).
  560. */
  561. PyThreadState_DeleteCurrent();
  562. }
  563. /* Release the lock if necessary */
  564. else if (oldstate == PyGILState_UNLOCKED)
  565. PyEval_SaveThread();
  566. }
  567. #endif /* WITH_THREAD */
  568. #ifdef __cplusplus
  569. }
  570. #endif