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.

665 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. tstate->trash_delete_nesting = 0;
  163. tstate->trash_delete_later = NULL;
  164. if (init)
  165. _PyThreadState_Init(tstate);
  166. HEAD_LOCK();
  167. tstate->next = interp->tstate_head;
  168. interp->tstate_head = tstate;
  169. HEAD_UNLOCK();
  170. }
  171. return tstate;
  172. }
  173. PyThreadState *
  174. PyThreadState_New(PyInterpreterState *interp)
  175. {
  176. return new_threadstate(interp, 1);
  177. }
  178. PyThreadState *
  179. _PyThreadState_Prealloc(PyInterpreterState *interp)
  180. {
  181. return new_threadstate(interp, 0);
  182. }
  183. void
  184. _PyThreadState_Init(PyThreadState *tstate)
  185. {
  186. #ifdef WITH_THREAD
  187. _PyGILState_NoteThreadState(tstate);
  188. #endif
  189. }
  190. void
  191. PyThreadState_Clear(PyThreadState *tstate)
  192. {
  193. if (Py_VerboseFlag && tstate->frame != NULL)
  194. fprintf(stderr,
  195. "PyThreadState_Clear: warning: thread still has a frame\n");
  196. Py_CLEAR(tstate->frame);
  197. Py_CLEAR(tstate->dict);
  198. Py_CLEAR(tstate->async_exc);
  199. Py_CLEAR(tstate->curexc_type);
  200. Py_CLEAR(tstate->curexc_value);
  201. Py_CLEAR(tstate->curexc_traceback);
  202. Py_CLEAR(tstate->exc_type);
  203. Py_CLEAR(tstate->exc_value);
  204. Py_CLEAR(tstate->exc_traceback);
  205. tstate->c_profilefunc = NULL;
  206. tstate->c_tracefunc = NULL;
  207. Py_CLEAR(tstate->c_profileobj);
  208. Py_CLEAR(tstate->c_traceobj);
  209. }
  210. /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
  211. static void
  212. tstate_delete_common(PyThreadState *tstate)
  213. {
  214. PyInterpreterState *interp;
  215. PyThreadState **p;
  216. PyThreadState *prev_p = NULL;
  217. if (tstate == NULL)
  218. Py_FatalError("PyThreadState_Delete: NULL tstate");
  219. interp = tstate->interp;
  220. if (interp == NULL)
  221. Py_FatalError("PyThreadState_Delete: NULL interp");
  222. HEAD_LOCK();
  223. for (p = &interp->tstate_head; ; p = &(*p)->next) {
  224. if (*p == NULL)
  225. Py_FatalError(
  226. "PyThreadState_Delete: invalid tstate");
  227. if (*p == tstate)
  228. break;
  229. /* Sanity check. These states should never happen but if
  230. * they do we must abort. Otherwise we'll end up spinning in
  231. * in a tight loop with the lock held. A similar check is done
  232. * in thread.c find_key(). */
  233. if (*p == prev_p)
  234. Py_FatalError(
  235. "PyThreadState_Delete: small circular list(!)"
  236. " and tstate not found.");
  237. prev_p = *p;
  238. if ((*p)->next == interp->tstate_head)
  239. Py_FatalError(
  240. "PyThreadState_Delete: circular list(!) and"
  241. " tstate not found.");
  242. }
  243. *p = tstate->next;
  244. HEAD_UNLOCK();
  245. free(tstate);
  246. }
  247. void
  248. PyThreadState_Delete(PyThreadState *tstate)
  249. {
  250. if (tstate == _PyThreadState_Current)
  251. Py_FatalError("PyThreadState_Delete: tstate is still current");
  252. tstate_delete_common(tstate);
  253. #ifdef WITH_THREAD
  254. if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
  255. PyThread_delete_key_value(autoTLSkey);
  256. #endif /* WITH_THREAD */
  257. }
  258. #ifdef WITH_THREAD
  259. void
  260. PyThreadState_DeleteCurrent()
  261. {
  262. PyThreadState *tstate = _PyThreadState_Current;
  263. if (tstate == NULL)
  264. Py_FatalError(
  265. "PyThreadState_DeleteCurrent: no current tstate");
  266. _PyThreadState_Current = NULL;
  267. tstate_delete_common(tstate);
  268. if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
  269. PyThread_delete_key_value(autoTLSkey);
  270. PyEval_ReleaseLock();
  271. }
  272. #endif /* WITH_THREAD */
  273. PyThreadState *
  274. PyThreadState_Get(void)
  275. {
  276. if (_PyThreadState_Current == NULL)
  277. Py_FatalError("PyThreadState_Get: no current thread");
  278. return _PyThreadState_Current;
  279. }
  280. PyThreadState *
  281. PyThreadState_Swap(PyThreadState *newts)
  282. {
  283. PyThreadState *oldts = _PyThreadState_Current;
  284. _PyThreadState_Current = newts;
  285. /* It should not be possible for more than one thread state
  286. to be used for a thread. Check this the best we can in debug
  287. builds.
  288. */
  289. #if defined(Py_DEBUG) && defined(WITH_THREAD)
  290. if (newts) {
  291. /* This can be called from PyEval_RestoreThread(). Similar
  292. to it, we need to ensure errno doesn't change.
  293. */
  294. int err = errno;
  295. PyThreadState *check = PyGILState_GetThisThreadState();
  296. if (check && check->interp == newts->interp && check != newts)
  297. Py_FatalError("Invalid thread state for this thread");
  298. errno = err;
  299. }
  300. #endif
  301. return oldts;
  302. }
  303. /* An extension mechanism to store arbitrary additional per-thread state.
  304. PyThreadState_GetDict() returns a dictionary that can be used to hold such
  305. state; the caller should pick a unique key and store its state there. If
  306. PyThreadState_GetDict() returns NULL, an exception has *not* been raised
  307. and the caller should assume no per-thread state is available. */
  308. PyObject *
  309. PyThreadState_GetDict(void)
  310. {
  311. if (_PyThreadState_Current == NULL)
  312. return NULL;
  313. if (_PyThreadState_Current->dict == NULL) {
  314. PyObject *d;
  315. _PyThreadState_Current->dict = d = PyDict_New();
  316. if (d == NULL)
  317. PyErr_Clear();
  318. }
  319. return _PyThreadState_Current->dict;
  320. }
  321. /* Asynchronously raise an exception in a thread.
  322. Requested by Just van Rossum and Alex Martelli.
  323. To prevent naive misuse, you must write your own extension
  324. to call this, or use ctypes. Must be called with the GIL held.
  325. Returns the number of tstates modified (normally 1, but 0 if `id` didn't
  326. match any known thread id). Can be called with exc=NULL to clear an
  327. existing async exception. This raises no exceptions. */
  328. int
  329. PyThreadState_SetAsyncExc(long id, PyObject *exc) {
  330. PyThreadState *tstate = PyThreadState_GET();
  331. PyInterpreterState *interp = tstate->interp;
  332. PyThreadState *p;
  333. /* Although the GIL is held, a few C API functions can be called
  334. * without the GIL held, and in particular some that create and
  335. * destroy thread and interpreter states. Those can mutate the
  336. * list of thread states we're traversing, so to prevent that we lock
  337. * head_mutex for the duration.
  338. */
  339. HEAD_LOCK();
  340. for (p = interp->tstate_head; p != NULL; p = p->next) {
  341. if (p->thread_id == id) {
  342. /* Tricky: we need to decref the current value
  343. * (if any) in p->async_exc, but that can in turn
  344. * allow arbitrary Python code to run, including
  345. * perhaps calls to this function. To prevent
  346. * deadlock, we need to release head_mutex before
  347. * the decref.
  348. */
  349. PyObject *old_exc = p->async_exc;
  350. Py_XINCREF(exc);
  351. p->async_exc = exc;
  352. HEAD_UNLOCK();
  353. Py_XDECREF(old_exc);
  354. return 1;
  355. }
  356. }
  357. HEAD_UNLOCK();
  358. return 0;
  359. }
  360. /* Routines for advanced debuggers, requested by David Beazley.
  361. Don't use unless you know what you are doing! */
  362. PyInterpreterState *
  363. PyInterpreterState_Head(void)
  364. {
  365. return interp_head;
  366. }
  367. PyInterpreterState *
  368. PyInterpreterState_Next(PyInterpreterState *interp) {
  369. return interp->next;
  370. }
  371. PyThreadState *
  372. PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
  373. return interp->tstate_head;
  374. }
  375. PyThreadState *
  376. PyThreadState_Next(PyThreadState *tstate) {
  377. return tstate->next;
  378. }
  379. /* The implementation of sys._current_frames(). This is intended to be
  380. called with the GIL held, as it will be when called via
  381. sys._current_frames(). It's possible it would work fine even without
  382. the GIL held, but haven't thought enough about that.
  383. */
  384. PyObject *
  385. _PyThread_CurrentFrames(void)
  386. {
  387. PyObject *result;
  388. PyInterpreterState *i;
  389. result = PyDict_New();
  390. if (result == NULL)
  391. return NULL;
  392. /* for i in all interpreters:
  393. * for t in all of i's thread states:
  394. * if t's frame isn't NULL, map t's id to its frame
  395. * Because these lists can mutate even when the GIL is held, we
  396. * need to grab head_mutex for the duration.
  397. */
  398. HEAD_LOCK();
  399. for (i = interp_head; i != NULL; i = i->next) {
  400. PyThreadState *t;
  401. for (t = i->tstate_head; t != NULL; t = t->next) {
  402. PyObject *id;
  403. int stat;
  404. struct _frame *frame = t->frame;
  405. if (frame == NULL)
  406. continue;
  407. id = PyInt_FromLong(t->thread_id);
  408. if (id == NULL)
  409. goto Fail;
  410. stat = PyDict_SetItem(result, id, (PyObject *)frame);
  411. Py_DECREF(id);
  412. if (stat < 0)
  413. goto Fail;
  414. }
  415. }
  416. HEAD_UNLOCK();
  417. return result;
  418. Fail:
  419. HEAD_UNLOCK();
  420. Py_DECREF(result);
  421. return NULL;
  422. }
  423. /* Python "auto thread state" API. */
  424. #ifdef WITH_THREAD
  425. /* Keep this as a static, as it is not reliable! It can only
  426. ever be compared to the state for the *current* thread.
  427. * If not equal, then it doesn't matter that the actual
  428. value may change immediately after comparison, as it can't
  429. possibly change to the current thread's state.
  430. * If equal, then the current thread holds the lock, so the value can't
  431. change until we yield the lock.
  432. */
  433. static int
  434. PyThreadState_IsCurrent(PyThreadState *tstate)
  435. {
  436. /* Must be the tstate for this thread */
  437. assert(PyGILState_GetThisThreadState()==tstate);
  438. /* On Windows at least, simple reads and writes to 32 bit values
  439. are atomic.
  440. */
  441. return tstate == _PyThreadState_Current;
  442. }
  443. /* Internal initialization/finalization functions called by
  444. Py_Initialize/Py_Finalize
  445. */
  446. void
  447. _PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
  448. {
  449. assert(i && t); /* must init with valid states */
  450. autoTLSkey = PyThread_create_key();
  451. autoInterpreterState = i;
  452. assert(PyThread_get_key_value(autoTLSkey) == NULL);
  453. assert(t->gilstate_counter == 0);
  454. _PyGILState_NoteThreadState(t);
  455. }
  456. void
  457. _PyGILState_Fini(void)
  458. {
  459. PyThread_delete_key(autoTLSkey);
  460. autoInterpreterState = NULL;
  461. }
  462. /* When a thread state is created for a thread by some mechanism other than
  463. PyGILState_Ensure, it's important that the GILState machinery knows about
  464. it so it doesn't try to create another thread state for the thread (this is
  465. a better fix for SF bug #1010677 than the first one attempted).
  466. */
  467. static void
  468. _PyGILState_NoteThreadState(PyThreadState* tstate)
  469. {
  470. /* If autoTLSkey isn't initialized, this must be the very first
  471. threadstate created in Py_Initialize(). Don't do anything for now
  472. (we'll be back here when _PyGILState_Init is called). */
  473. if (!autoInterpreterState)
  474. return;
  475. /* Stick the thread state for this thread in thread local storage.
  476. The only situation where you can legitimately have more than one
  477. thread state for an OS level thread is when there are multiple
  478. interpreters, when:
  479. a) You shouldn't really be using the PyGILState_ APIs anyway,
  480. and:
  481. b) The slightly odd way PyThread_set_key_value works (see
  482. comments by its implementation) means that the first thread
  483. state created for that given OS level thread will "win",
  484. which seems reasonable behaviour.
  485. */
  486. if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
  487. Py_FatalError("Couldn't create autoTLSkey mapping");
  488. /* PyGILState_Release must not try to delete this thread state. */
  489. tstate->gilstate_counter = 1;
  490. }
  491. /* The public functions */
  492. PyThreadState *
  493. PyGILState_GetThisThreadState(void)
  494. {
  495. if (autoInterpreterState == NULL)
  496. return NULL;
  497. return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
  498. }
  499. PyGILState_STATE
  500. PyGILState_Ensure(void)
  501. {
  502. int current;
  503. PyThreadState *tcur;
  504. /* Note that we do not auto-init Python here - apart from
  505. potential races with 2 threads auto-initializing, pep-311
  506. spells out other issues. Embedders are expected to have
  507. called Py_Initialize() and usually PyEval_InitThreads().
  508. */
  509. assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
  510. tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
  511. if (tcur == NULL) {
  512. /* Create a new thread state for this thread */
  513. tcur = PyThreadState_New(autoInterpreterState);
  514. if (tcur == NULL)
  515. Py_FatalError("Couldn't create thread-state for new thread");
  516. /* This is our thread state! We'll need to delete it in the
  517. matching call to PyGILState_Release(). */
  518. tcur->gilstate_counter = 0;
  519. current = 0; /* new thread state is never current */
  520. }
  521. else
  522. current = PyThreadState_IsCurrent(tcur);
  523. if (current == 0)
  524. PyEval_RestoreThread(tcur);
  525. /* Update our counter in the thread-state - no need for locks:
  526. - tcur will remain valid as we hold the GIL.
  527. - the counter is safe as we are the only thread "allowed"
  528. to modify this value
  529. */
  530. ++tcur->gilstate_counter;
  531. return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
  532. }
  533. void
  534. PyGILState_Release(PyGILState_STATE oldstate)
  535. {
  536. PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
  537. autoTLSkey);
  538. if (tcur == NULL)
  539. Py_FatalError("auto-releasing thread-state, "
  540. "but no thread-state for this thread");
  541. /* We must hold the GIL and have our thread state current */
  542. /* XXX - remove the check - the assert should be fine,
  543. but while this is very new (April 2003), the extra check
  544. by release-only users can't hurt.
  545. */
  546. if (! PyThreadState_IsCurrent(tcur))
  547. Py_FatalError("This thread state must be current when releasing");
  548. assert(PyThreadState_IsCurrent(tcur));
  549. --tcur->gilstate_counter;
  550. assert(tcur->gilstate_counter >= 0); /* illegal counter value */
  551. /* If we're going to destroy this thread-state, we must
  552. * clear it while the GIL is held, as destructors may run.
  553. */
  554. if (tcur->gilstate_counter == 0) {
  555. /* can't have been locked when we created it */
  556. assert(oldstate == PyGILState_UNLOCKED);
  557. PyThreadState_Clear(tcur);
  558. /* Delete the thread-state. Note this releases the GIL too!
  559. * It's vital that the GIL be held here, to avoid shutdown
  560. * races; see bugs 225673 and 1061968 (that nasty bug has a
  561. * habit of coming back).
  562. */
  563. PyThreadState_DeleteCurrent();
  564. }
  565. /* Release the lock if necessary */
  566. else if (oldstate == PyGILState_UNLOCKED)
  567. PyEval_SaveThread();
  568. }
  569. #endif /* WITH_THREAD */
  570. #ifdef __cplusplus
  571. }
  572. #endif