pystate.c 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068
  1. /* Thread and interpreter state structures and their interfaces */
  2. #include "Python.h"
  3. #include "pycore_ceval.h"
  4. #include "pycore_code.h" // stats
  5. #include "pycore_dtoa.h" // _dtoa_state_INIT()
  6. #include "pycore_frame.h"
  7. #include "pycore_initconfig.h"
  8. #include "pycore_object.h" // _PyType_InitCache()
  9. #include "pycore_pyerrors.h"
  10. #include "pycore_pylifecycle.h"
  11. #include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
  12. #include "pycore_pystate.h"
  13. #include "pycore_runtime_init.h" // _PyRuntimeState_INIT
  14. #include "pycore_sysmodule.h"
  15. /* --------------------------------------------------------------------------
  16. CAUTION
  17. Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
  18. number of these functions are advertised as safe to call when the GIL isn't
  19. held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
  20. debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
  21. to avoid the expense of doing their own locking).
  22. -------------------------------------------------------------------------- */
  23. #ifdef HAVE_DLOPEN
  24. #ifdef HAVE_DLFCN_H
  25. #include <dlfcn.h>
  26. #endif
  27. #if !HAVE_DECL_RTLD_LAZY
  28. #define RTLD_LAZY 1
  29. #endif
  30. #endif
  31. #ifdef __cplusplus
  32. extern "C" {
  33. #endif
  34. /****************************************/
  35. /* helpers for the current thread state */
  36. /****************************************/
  37. // API for the current thread state is further down.
  38. /* "current" means one of:
  39. - bound to the current OS thread
  40. - holds the GIL
  41. */
  42. //-------------------------------------------------
  43. // a highly efficient lookup for the current thread
  44. //-------------------------------------------------
  45. /*
  46. The stored thread state is set by PyThreadState_Swap().
  47. For each of these functions, the GIL must be held by the current thread.
  48. */
  49. #ifdef HAVE_THREAD_LOCAL
  50. _Py_thread_local PyThreadState *_Py_tss_tstate = NULL;
  51. #endif
  52. static inline PyThreadState *
  53. current_fast_get(_PyRuntimeState *Py_UNUSED(runtime))
  54. {
  55. #ifdef HAVE_THREAD_LOCAL
  56. return _Py_tss_tstate;
  57. #else
  58. // XXX Fall back to the PyThread_tss_*() API.
  59. # error "no supported thread-local variable storage classifier"
  60. #endif
  61. }
  62. static inline void
  63. current_fast_set(_PyRuntimeState *Py_UNUSED(runtime), PyThreadState *tstate)
  64. {
  65. assert(tstate != NULL);
  66. #ifdef HAVE_THREAD_LOCAL
  67. _Py_tss_tstate = tstate;
  68. #else
  69. // XXX Fall back to the PyThread_tss_*() API.
  70. # error "no supported thread-local variable storage classifier"
  71. #endif
  72. }
  73. static inline void
  74. current_fast_clear(_PyRuntimeState *Py_UNUSED(runtime))
  75. {
  76. #ifdef HAVE_THREAD_LOCAL
  77. _Py_tss_tstate = NULL;
  78. #else
  79. // XXX Fall back to the PyThread_tss_*() API.
  80. # error "no supported thread-local variable storage classifier"
  81. #endif
  82. }
  83. #define tstate_verify_not_active(tstate) \
  84. if (tstate == current_fast_get((tstate)->interp->runtime)) { \
  85. _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate); \
  86. }
  87. PyThreadState *
  88. _PyThreadState_GetCurrent(void)
  89. {
  90. return current_fast_get(&_PyRuntime);
  91. }
  92. //------------------------------------------------
  93. // the thread state bound to the current OS thread
  94. //------------------------------------------------
  95. static inline int
  96. tstate_tss_initialized(Py_tss_t *key)
  97. {
  98. return PyThread_tss_is_created(key);
  99. }
  100. static inline int
  101. tstate_tss_init(Py_tss_t *key)
  102. {
  103. assert(!tstate_tss_initialized(key));
  104. return PyThread_tss_create(key);
  105. }
  106. static inline void
  107. tstate_tss_fini(Py_tss_t *key)
  108. {
  109. assert(tstate_tss_initialized(key));
  110. PyThread_tss_delete(key);
  111. }
  112. static inline PyThreadState *
  113. tstate_tss_get(Py_tss_t *key)
  114. {
  115. assert(tstate_tss_initialized(key));
  116. return (PyThreadState *)PyThread_tss_get(key);
  117. }
  118. static inline int
  119. tstate_tss_set(Py_tss_t *key, PyThreadState *tstate)
  120. {
  121. assert(tstate != NULL);
  122. assert(tstate_tss_initialized(key));
  123. return PyThread_tss_set(key, (void *)tstate);
  124. }
  125. static inline int
  126. tstate_tss_clear(Py_tss_t *key)
  127. {
  128. assert(tstate_tss_initialized(key));
  129. return PyThread_tss_set(key, (void *)NULL);
  130. }
  131. #ifdef HAVE_FORK
  132. /* Reset the TSS key - called by PyOS_AfterFork_Child().
  133. * This should not be necessary, but some - buggy - pthread implementations
  134. * don't reset TSS upon fork(), see issue #10517.
  135. */
  136. static PyStatus
  137. tstate_tss_reinit(Py_tss_t *key)
  138. {
  139. if (!tstate_tss_initialized(key)) {
  140. return _PyStatus_OK();
  141. }
  142. PyThreadState *tstate = tstate_tss_get(key);
  143. tstate_tss_fini(key);
  144. if (tstate_tss_init(key) != 0) {
  145. return _PyStatus_NO_MEMORY();
  146. }
  147. /* If the thread had an associated auto thread state, reassociate it with
  148. * the new key. */
  149. if (tstate && tstate_tss_set(key, tstate) != 0) {
  150. return _PyStatus_ERR("failed to re-set autoTSSkey");
  151. }
  152. return _PyStatus_OK();
  153. }
  154. #endif
  155. /*
  156. The stored thread state is set by bind_tstate() (AKA PyThreadState_Bind().
  157. The GIL does no need to be held for these.
  158. */
  159. #define gilstate_tss_initialized(runtime) \
  160. tstate_tss_initialized(&(runtime)->autoTSSkey)
  161. #define gilstate_tss_init(runtime) \
  162. tstate_tss_init(&(runtime)->autoTSSkey)
  163. #define gilstate_tss_fini(runtime) \
  164. tstate_tss_fini(&(runtime)->autoTSSkey)
  165. #define gilstate_tss_get(runtime) \
  166. tstate_tss_get(&(runtime)->autoTSSkey)
  167. #define _gilstate_tss_set(runtime, tstate) \
  168. tstate_tss_set(&(runtime)->autoTSSkey, tstate)
  169. #define _gilstate_tss_clear(runtime) \
  170. tstate_tss_clear(&(runtime)->autoTSSkey)
  171. #define gilstate_tss_reinit(runtime) \
  172. tstate_tss_reinit(&(runtime)->autoTSSkey)
  173. static inline void
  174. gilstate_tss_set(_PyRuntimeState *runtime, PyThreadState *tstate)
  175. {
  176. assert(tstate != NULL && tstate->interp->runtime == runtime);
  177. if (_gilstate_tss_set(runtime, tstate) != 0) {
  178. Py_FatalError("failed to set current tstate (TSS)");
  179. }
  180. }
  181. static inline void
  182. gilstate_tss_clear(_PyRuntimeState *runtime)
  183. {
  184. if (_gilstate_tss_clear(runtime) != 0) {
  185. Py_FatalError("failed to clear current tstate (TSS)");
  186. }
  187. }
  188. #ifndef NDEBUG
  189. static inline int tstate_is_alive(PyThreadState *tstate);
  190. static inline int
  191. tstate_is_bound(PyThreadState *tstate)
  192. {
  193. return tstate->_status.bound && !tstate->_status.unbound;
  194. }
  195. #endif // !NDEBUG
  196. static void bind_gilstate_tstate(PyThreadState *);
  197. static void unbind_gilstate_tstate(PyThreadState *);
  198. static void
  199. bind_tstate(PyThreadState *tstate)
  200. {
  201. assert(tstate != NULL);
  202. assert(tstate_is_alive(tstate) && !tstate->_status.bound);
  203. assert(!tstate->_status.unbound); // just in case
  204. assert(!tstate->_status.bound_gilstate);
  205. assert(tstate != gilstate_tss_get(tstate->interp->runtime));
  206. assert(!tstate->_status.active);
  207. assert(tstate->thread_id == 0);
  208. assert(tstate->native_thread_id == 0);
  209. // Currently we don't necessarily store the thread state
  210. // in thread-local storage (e.g. per-interpreter).
  211. tstate->thread_id = PyThread_get_thread_ident();
  212. #ifdef PY_HAVE_THREAD_NATIVE_ID
  213. tstate->native_thread_id = PyThread_get_thread_native_id();
  214. #endif
  215. tstate->_status.bound = 1;
  216. }
  217. static void
  218. unbind_tstate(PyThreadState *tstate)
  219. {
  220. assert(tstate != NULL);
  221. assert(tstate_is_bound(tstate));
  222. #ifndef HAVE_PTHREAD_STUBS
  223. assert(tstate->thread_id > 0);
  224. #endif
  225. #ifdef PY_HAVE_THREAD_NATIVE_ID
  226. assert(tstate->native_thread_id > 0);
  227. #endif
  228. // We leave thread_id and native_thread_id alone
  229. // since they can be useful for debugging.
  230. // Check the `_status` field to know if these values
  231. // are still valid.
  232. // We leave tstate->_status.bound set to 1
  233. // to indicate it was previously bound.
  234. tstate->_status.unbound = 1;
  235. }
  236. /* Stick the thread state for this thread in thread specific storage.
  237. When a thread state is created for a thread by some mechanism
  238. other than PyGILState_Ensure(), it's important that the GILState
  239. machinery knows about it so it doesn't try to create another
  240. thread state for the thread.
  241. (This is a better fix for SF bug #1010677 than the first one attempted.)
  242. The only situation where you can legitimately have more than one
  243. thread state for an OS level thread is when there are multiple
  244. interpreters.
  245. Before 3.12, the PyGILState_*() APIs didn't work with multiple
  246. interpreters (see bpo-10915 and bpo-15751), so this function used
  247. to set TSS only once. Thus, the first thread state created for that
  248. given OS level thread would "win", which seemed reasonable behaviour.
  249. */
  250. static void
  251. bind_gilstate_tstate(PyThreadState *tstate)
  252. {
  253. assert(tstate != NULL);
  254. assert(tstate_is_alive(tstate));
  255. assert(tstate_is_bound(tstate));
  256. // XXX assert(!tstate->_status.active);
  257. assert(!tstate->_status.bound_gilstate);
  258. _PyRuntimeState *runtime = tstate->interp->runtime;
  259. PyThreadState *tcur = gilstate_tss_get(runtime);
  260. assert(tstate != tcur);
  261. if (tcur != NULL) {
  262. tcur->_status.bound_gilstate = 0;
  263. }
  264. gilstate_tss_set(runtime, tstate);
  265. tstate->_status.bound_gilstate = 1;
  266. }
  267. static void
  268. unbind_gilstate_tstate(PyThreadState *tstate)
  269. {
  270. assert(tstate != NULL);
  271. // XXX assert(tstate_is_alive(tstate));
  272. assert(tstate_is_bound(tstate));
  273. // XXX assert(!tstate->_status.active);
  274. assert(tstate->_status.bound_gilstate);
  275. assert(tstate == gilstate_tss_get(tstate->interp->runtime));
  276. gilstate_tss_clear(tstate->interp->runtime);
  277. tstate->_status.bound_gilstate = 0;
  278. }
  279. //----------------------------------------------
  280. // the thread state that currently holds the GIL
  281. //----------------------------------------------
  282. /* This is not exported, as it is not reliable! It can only
  283. ever be compared to the state for the *current* thread.
  284. * If not equal, then it doesn't matter that the actual
  285. value may change immediately after comparison, as it can't
  286. possibly change to the current thread's state.
  287. * If equal, then the current thread holds the lock, so the value can't
  288. change until we yield the lock.
  289. */
  290. static int
  291. holds_gil(PyThreadState *tstate)
  292. {
  293. // XXX Fall back to tstate->interp->runtime->ceval.gil.last_holder
  294. // (and tstate->interp->runtime->ceval.gil.locked).
  295. assert(tstate != NULL);
  296. #ifndef NDEBUG
  297. if (!tstate_is_alive(tstate)) {
  298. return 0;
  299. }
  300. #endif
  301. _PyRuntimeState *runtime = tstate->interp->runtime;
  302. /* Must be the tstate for this thread */
  303. assert(tstate == gilstate_tss_get(runtime));
  304. return tstate == current_fast_get(runtime);
  305. }
  306. /****************************/
  307. /* the global runtime state */
  308. /****************************/
  309. //----------
  310. // lifecycle
  311. //----------
  312. /* Suppress deprecation warning for PyBytesObject.ob_shash */
  313. _Py_COMP_DIAG_PUSH
  314. _Py_COMP_DIAG_IGNORE_DEPR_DECLS
  315. /* We use "initial" if the runtime gets re-used
  316. (e.g. Py_Finalize() followed by Py_Initialize().
  317. Note that we initialize "initial" relative to _PyRuntime,
  318. to ensure pre-initialized pointers point to the active
  319. runtime state (and not "initial"). */
  320. static const _PyRuntimeState initial = _PyRuntimeState_INIT(_PyRuntime);
  321. _Py_COMP_DIAG_POP
  322. #define NUMLOCKS 9
  323. #define LOCKS_INIT(runtime) \
  324. { \
  325. &(runtime)->interpreters.mutex, \
  326. &(runtime)->xidregistry.mutex, \
  327. &(runtime)->getargs.mutex, \
  328. &(runtime)->unicode_state.ids.lock, \
  329. &(runtime)->imports.extensions.mutex, \
  330. &(runtime)->ceval.pending_mainthread.lock, \
  331. &(runtime)->atexit.mutex, \
  332. &(runtime)->audit_hooks.mutex, \
  333. &(runtime)->allocators.mutex, \
  334. }
  335. static int
  336. alloc_for_runtime(PyThread_type_lock locks[NUMLOCKS])
  337. {
  338. /* Force default allocator, since _PyRuntimeState_Fini() must
  339. use the same allocator than this function. */
  340. PyMemAllocatorEx old_alloc;
  341. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  342. for (int i = 0; i < NUMLOCKS; i++) {
  343. PyThread_type_lock lock = PyThread_allocate_lock();
  344. if (lock == NULL) {
  345. for (int j = 0; j < i; j++) {
  346. PyThread_free_lock(locks[j]);
  347. locks[j] = NULL;
  348. }
  349. break;
  350. }
  351. locks[i] = lock;
  352. }
  353. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  354. return 0;
  355. }
  356. static void
  357. init_runtime(_PyRuntimeState *runtime,
  358. void *open_code_hook, void *open_code_userdata,
  359. _Py_AuditHookEntry *audit_hook_head,
  360. Py_ssize_t unicode_next_index,
  361. PyThread_type_lock locks[NUMLOCKS])
  362. {
  363. if (runtime->_initialized) {
  364. Py_FatalError("runtime already initialized");
  365. }
  366. assert(!runtime->preinitializing &&
  367. !runtime->preinitialized &&
  368. !runtime->core_initialized &&
  369. !runtime->initialized);
  370. runtime->open_code_hook = open_code_hook;
  371. runtime->open_code_userdata = open_code_userdata;
  372. runtime->audit_hooks.head = audit_hook_head;
  373. PyPreConfig_InitPythonConfig(&runtime->preconfig);
  374. PyThread_type_lock *lockptrs[NUMLOCKS] = LOCKS_INIT(runtime);
  375. for (int i = 0; i < NUMLOCKS; i++) {
  376. assert(locks[i] != NULL);
  377. *lockptrs[i] = locks[i];
  378. }
  379. // Set it to the ID of the main thread of the main interpreter.
  380. runtime->main_thread = PyThread_get_thread_ident();
  381. runtime->unicode_state.ids.next_index = unicode_next_index;
  382. runtime->_initialized = 1;
  383. }
  384. PyStatus
  385. _PyRuntimeState_Init(_PyRuntimeState *runtime)
  386. {
  387. /* We preserve the hook across init, because there is
  388. currently no public API to set it between runtime
  389. initialization and interpreter initialization. */
  390. void *open_code_hook = runtime->open_code_hook;
  391. void *open_code_userdata = runtime->open_code_userdata;
  392. _Py_AuditHookEntry *audit_hook_head = runtime->audit_hooks.head;
  393. // bpo-42882: Preserve next_index value if Py_Initialize()/Py_Finalize()
  394. // is called multiple times.
  395. Py_ssize_t unicode_next_index = runtime->unicode_state.ids.next_index;
  396. PyThread_type_lock locks[NUMLOCKS];
  397. if (alloc_for_runtime(locks) != 0) {
  398. return _PyStatus_NO_MEMORY();
  399. }
  400. if (runtime->_initialized) {
  401. // Py_Initialize() must be running again.
  402. // Reset to _PyRuntimeState_INIT.
  403. memcpy(runtime, &initial, sizeof(*runtime));
  404. }
  405. if (gilstate_tss_init(runtime) != 0) {
  406. _PyRuntimeState_Fini(runtime);
  407. return _PyStatus_NO_MEMORY();
  408. }
  409. if (PyThread_tss_create(&runtime->trashTSSkey) != 0) {
  410. _PyRuntimeState_Fini(runtime);
  411. return _PyStatus_NO_MEMORY();
  412. }
  413. init_runtime(runtime, open_code_hook, open_code_userdata, audit_hook_head,
  414. unicode_next_index, locks);
  415. return _PyStatus_OK();
  416. }
  417. static void _xidregistry_clear(struct _xidregistry *);
  418. void
  419. _PyRuntimeState_Fini(_PyRuntimeState *runtime)
  420. {
  421. #ifdef Py_REF_DEBUG
  422. /* The count is cleared by _Py_FinalizeRefTotal(). */
  423. assert(runtime->object_state.interpreter_leaks == 0);
  424. #endif
  425. _xidregistry_clear(&runtime->xidregistry);
  426. if (gilstate_tss_initialized(runtime)) {
  427. gilstate_tss_fini(runtime);
  428. }
  429. if (PyThread_tss_is_created(&runtime->trashTSSkey)) {
  430. PyThread_tss_delete(&runtime->trashTSSkey);
  431. }
  432. /* Force the allocator used by _PyRuntimeState_Init(). */
  433. PyMemAllocatorEx old_alloc;
  434. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  435. #define FREE_LOCK(LOCK) \
  436. if (LOCK != NULL) { \
  437. PyThread_free_lock(LOCK); \
  438. LOCK = NULL; \
  439. }
  440. PyThread_type_lock *lockptrs[NUMLOCKS] = LOCKS_INIT(runtime);
  441. for (int i = 0; i < NUMLOCKS; i++) {
  442. FREE_LOCK(*lockptrs[i]);
  443. }
  444. #undef FREE_LOCK
  445. if (runtime->sys_path_0 != NULL) {
  446. PyMem_RawFree(runtime->sys_path_0);
  447. runtime->sys_path_0 = NULL;
  448. }
  449. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  450. }
  451. #ifdef HAVE_FORK
  452. /* This function is called from PyOS_AfterFork_Child to ensure that
  453. newly created child processes do not share locks with the parent. */
  454. PyStatus
  455. _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
  456. {
  457. // This was initially set in _PyRuntimeState_Init().
  458. runtime->main_thread = PyThread_get_thread_ident();
  459. /* Force default allocator, since _PyRuntimeState_Fini() must
  460. use the same allocator than this function. */
  461. PyMemAllocatorEx old_alloc;
  462. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  463. PyThread_type_lock *lockptrs[NUMLOCKS] = LOCKS_INIT(runtime);
  464. int reinit_err = 0;
  465. for (int i = 0; i < NUMLOCKS; i++) {
  466. reinit_err += _PyThread_at_fork_reinit(lockptrs[i]);
  467. }
  468. /* PyOS_AfterFork_Child(), which calls this function, later calls
  469. _PyInterpreterState_DeleteExceptMain(), so we only need to update
  470. the main interpreter here. */
  471. assert(runtime->interpreters.main != NULL);
  472. runtime->interpreters.main->xidregistry.mutex = runtime->xidregistry.mutex;
  473. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  474. /* bpo-42540: id_mutex is freed by _PyInterpreterState_Delete, which does
  475. * not force the default allocator. */
  476. reinit_err += _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
  477. if (reinit_err < 0) {
  478. return _PyStatus_ERR("Failed to reinitialize runtime locks");
  479. }
  480. PyStatus status = gilstate_tss_reinit(runtime);
  481. if (_PyStatus_EXCEPTION(status)) {
  482. return status;
  483. }
  484. if (PyThread_tss_is_created(&runtime->trashTSSkey)) {
  485. PyThread_tss_delete(&runtime->trashTSSkey);
  486. }
  487. if (PyThread_tss_create(&runtime->trashTSSkey) != 0) {
  488. return _PyStatus_NO_MEMORY();
  489. }
  490. return _PyStatus_OK();
  491. }
  492. #endif
  493. /*************************************/
  494. /* the per-interpreter runtime state */
  495. /*************************************/
  496. //----------
  497. // lifecycle
  498. //----------
  499. /* Calling this indicates that the runtime is ready to create interpreters. */
  500. PyStatus
  501. _PyInterpreterState_Enable(_PyRuntimeState *runtime)
  502. {
  503. struct pyinterpreters *interpreters = &runtime->interpreters;
  504. interpreters->next_id = 0;
  505. /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
  506. Create a new mutex if needed. */
  507. if (interpreters->mutex == NULL) {
  508. /* Force default allocator, since _PyRuntimeState_Fini() must
  509. use the same allocator than this function. */
  510. PyMemAllocatorEx old_alloc;
  511. _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  512. interpreters->mutex = PyThread_allocate_lock();
  513. PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
  514. if (interpreters->mutex == NULL) {
  515. return _PyStatus_ERR("Can't initialize threads for interpreter");
  516. }
  517. }
  518. return _PyStatus_OK();
  519. }
  520. static PyInterpreterState *
  521. alloc_interpreter(void)
  522. {
  523. return PyMem_RawCalloc(1, sizeof(PyInterpreterState));
  524. }
  525. static void
  526. free_interpreter(PyInterpreterState *interp)
  527. {
  528. // The main interpreter is statically allocated so
  529. // should not be freed.
  530. if (interp != &_PyRuntime._main_interpreter) {
  531. PyMem_RawFree(interp);
  532. }
  533. }
  534. /* Get the interpreter state to a minimal consistent state.
  535. Further init happens in pylifecycle.c before it can be used.
  536. All fields not initialized here are expected to be zeroed out,
  537. e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized.
  538. The runtime state is not manipulated. Instead it is assumed that
  539. the interpreter is getting added to the runtime.
  540. Note that the main interpreter was statically initialized as part
  541. of the runtime and most state is already set properly. That leaves
  542. a small number of fields to initialize dynamically, as well as some
  543. that are initialized lazily.
  544. For subinterpreters we memcpy() the main interpreter in
  545. PyInterpreterState_New(), leaving it in the same mostly-initialized
  546. state. The only difference is that the interpreter has some
  547. self-referential state that is statically initializexd to the
  548. main interpreter. We fix those fields here, in addition
  549. to the other dynamically initialized fields.
  550. */
  551. static void
  552. init_interpreter(PyInterpreterState *interp,
  553. _PyRuntimeState *runtime, int64_t id,
  554. PyInterpreterState *next,
  555. PyThread_type_lock pending_lock)
  556. {
  557. if (interp->_initialized) {
  558. Py_FatalError("interpreter already initialized");
  559. }
  560. assert(runtime != NULL);
  561. interp->runtime = runtime;
  562. assert(id > 0 || (id == 0 && interp == runtime->interpreters.main));
  563. interp->id = id;
  564. assert(runtime->interpreters.head == interp);
  565. assert(next != NULL || (interp == runtime->interpreters.main));
  566. interp->next = next;
  567. /* Initialize obmalloc, but only for subinterpreters,
  568. since the main interpreter is initialized statically. */
  569. if (interp != &runtime->_main_interpreter) {
  570. poolp temp[OBMALLOC_USED_POOLS_SIZE] = \
  571. _obmalloc_pools_INIT(interp->obmalloc.pools);
  572. memcpy(&interp->obmalloc.pools.used, temp, sizeof(temp));
  573. }
  574. _PyObject_InitState(interp);
  575. _PyEval_InitState(interp, pending_lock);
  576. _PyGC_InitState(&interp->gc);
  577. PyConfig_InitPythonConfig(&interp->config);
  578. _PyType_InitCache(interp);
  579. for (int i = 0; i < _PY_MONITORING_UNGROUPED_EVENTS; i++) {
  580. interp->monitors.tools[i] = 0;
  581. }
  582. for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
  583. for (int e = 0; e < _PY_MONITORING_EVENTS; e++) {
  584. interp->monitoring_callables[t][e] = NULL;
  585. }
  586. }
  587. interp->sys_profile_initialized = false;
  588. interp->sys_trace_initialized = false;
  589. if (interp != &runtime->_main_interpreter) {
  590. /* Fix the self-referential, statically initialized fields. */
  591. interp->dtoa = (struct _dtoa_state)_dtoa_state_INIT(interp);
  592. }
  593. interp->f_opcode_trace_set = false;
  594. assert(runtime->xidregistry.mutex != NULL);
  595. interp->xidregistry.mutex = runtime->xidregistry.mutex;
  596. interp->_initialized = 1;
  597. }
  598. PyInterpreterState *
  599. PyInterpreterState_New(void)
  600. {
  601. PyInterpreterState *interp;
  602. _PyRuntimeState *runtime = &_PyRuntime;
  603. PyThreadState *tstate = current_fast_get(runtime);
  604. /* tstate is NULL when Py_InitializeFromConfig() calls
  605. PyInterpreterState_New() to create the main interpreter. */
  606. if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
  607. return NULL;
  608. }
  609. PyThread_type_lock pending_lock = PyThread_allocate_lock();
  610. if (pending_lock == NULL) {
  611. if (tstate != NULL) {
  612. _PyErr_NoMemory(tstate);
  613. }
  614. return NULL;
  615. }
  616. /* Don't get runtime from tstate since tstate can be NULL. */
  617. struct pyinterpreters *interpreters = &runtime->interpreters;
  618. /* We completely serialize creation of multiple interpreters, since
  619. it simplifies things here and blocking concurrent calls isn't a problem.
  620. Regardless, we must fully block subinterpreter creation until
  621. after the main interpreter is created. */
  622. HEAD_LOCK(runtime);
  623. int64_t id = interpreters->next_id;
  624. interpreters->next_id += 1;
  625. // Allocate the interpreter and add it to the runtime state.
  626. PyInterpreterState *old_head = interpreters->head;
  627. if (old_head == NULL) {
  628. // We are creating the main interpreter.
  629. assert(interpreters->main == NULL);
  630. assert(id == 0);
  631. interp = &runtime->_main_interpreter;
  632. assert(interp->id == 0);
  633. assert(interp->next == NULL);
  634. interpreters->main = interp;
  635. }
  636. else {
  637. assert(interpreters->main != NULL);
  638. assert(id != 0);
  639. interp = alloc_interpreter();
  640. if (interp == NULL) {
  641. goto error;
  642. }
  643. // Set to _PyInterpreterState_INIT.
  644. memcpy(interp, &initial._main_interpreter,
  645. sizeof(*interp));
  646. if (id < 0) {
  647. /* overflow or Py_Initialize() not called yet! */
  648. if (tstate != NULL) {
  649. _PyErr_SetString(tstate, PyExc_RuntimeError,
  650. "failed to get an interpreter ID");
  651. }
  652. goto error;
  653. }
  654. }
  655. interpreters->head = interp;
  656. init_interpreter(interp, runtime, id, old_head, pending_lock);
  657. HEAD_UNLOCK(runtime);
  658. return interp;
  659. error:
  660. HEAD_UNLOCK(runtime);
  661. PyThread_free_lock(pending_lock);
  662. if (interp != NULL) {
  663. free_interpreter(interp);
  664. }
  665. return NULL;
  666. }
  667. static void
  668. interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
  669. {
  670. assert(interp != NULL);
  671. assert(tstate != NULL);
  672. _PyRuntimeState *runtime = interp->runtime;
  673. /* XXX Conditions we need to enforce:
  674. * the GIL must be held by the current thread
  675. * tstate must be the "current" thread state (current_fast_get())
  676. * tstate->interp must be interp
  677. * for the main interpreter, tstate must be the main thread
  678. */
  679. // XXX Ideally, we would not rely on any thread state in this function
  680. // (and we would drop the "tstate" argument).
  681. if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
  682. _PyErr_Clear(tstate);
  683. }
  684. // Clear the current/main thread state last.
  685. HEAD_LOCK(runtime);
  686. PyThreadState *p = interp->threads.head;
  687. HEAD_UNLOCK(runtime);
  688. while (p != NULL) {
  689. // See https://github.com/python/cpython/issues/102126
  690. // Must be called without HEAD_LOCK held as it can deadlock
  691. // if any finalizer tries to acquire that lock.
  692. PyThreadState_Clear(p);
  693. HEAD_LOCK(runtime);
  694. p = p->next;
  695. HEAD_UNLOCK(runtime);
  696. }
  697. if (tstate->interp == interp) {
  698. /* We fix tstate->_status below when we for sure aren't using it
  699. (e.g. no longer need the GIL). */
  700. // XXX Eliminate the need to do this.
  701. tstate->_status.cleared = 0;
  702. }
  703. /* It is possible that any of the objects below have a finalizer
  704. that runs Python code or otherwise relies on a thread state
  705. or even the interpreter state. For now we trust that isn't
  706. a problem.
  707. */
  708. // XXX Make sure we properly deal with problematic finalizers.
  709. Py_CLEAR(interp->audit_hooks);
  710. for (int i = 0; i < _PY_MONITORING_UNGROUPED_EVENTS; i++) {
  711. interp->monitors.tools[i] = 0;
  712. }
  713. for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
  714. for (int e = 0; e < _PY_MONITORING_EVENTS; e++) {
  715. Py_CLEAR(interp->monitoring_callables[t][e]);
  716. }
  717. }
  718. interp->sys_profile_initialized = false;
  719. interp->sys_trace_initialized = false;
  720. for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
  721. Py_CLEAR(interp->monitoring_tool_names[t]);
  722. }
  723. PyConfig_Clear(&interp->config);
  724. Py_CLEAR(interp->codec_search_path);
  725. Py_CLEAR(interp->codec_search_cache);
  726. Py_CLEAR(interp->codec_error_registry);
  727. assert(interp->imports.modules == NULL);
  728. assert(interp->imports.modules_by_index == NULL);
  729. assert(interp->imports.importlib == NULL);
  730. assert(interp->imports.import_func == NULL);
  731. Py_CLEAR(interp->sysdict_copy);
  732. Py_CLEAR(interp->builtins_copy);
  733. Py_CLEAR(interp->dict);
  734. #ifdef HAVE_FORK
  735. Py_CLEAR(interp->before_forkers);
  736. Py_CLEAR(interp->after_forkers_parent);
  737. Py_CLEAR(interp->after_forkers_child);
  738. #endif
  739. _PyAST_Fini(interp);
  740. _PyWarnings_Fini(interp);
  741. _PyAtExit_Fini(interp);
  742. // All Python types must be destroyed before the last GC collection. Python
  743. // types create a reference cycle to themselves in their in their
  744. // PyTypeObject.tp_mro member (the tuple contains the type).
  745. /* Last garbage collection on this interpreter */
  746. _PyGC_CollectNoFail(tstate);
  747. _PyGC_Fini(interp);
  748. /* We don't clear sysdict and builtins until the end of this function.
  749. Because clearing other attributes can execute arbitrary Python code
  750. which requires sysdict and builtins. */
  751. PyDict_Clear(interp->sysdict);
  752. PyDict_Clear(interp->builtins);
  753. Py_CLEAR(interp->sysdict);
  754. Py_CLEAR(interp->builtins);
  755. Py_CLEAR(interp->interpreter_trampoline);
  756. _xidregistry_clear(&interp->xidregistry);
  757. /* The lock is owned by the runtime, so we don't free it here. */
  758. interp->xidregistry.mutex = NULL;
  759. if (tstate->interp == interp) {
  760. /* We are now safe to fix tstate->_status.cleared. */
  761. // XXX Do this (much) earlier?
  762. tstate->_status.cleared = 1;
  763. }
  764. for (int i=0; i < DICT_MAX_WATCHERS; i++) {
  765. interp->dict_state.watchers[i] = NULL;
  766. }
  767. for (int i=0; i < TYPE_MAX_WATCHERS; i++) {
  768. interp->type_watchers[i] = NULL;
  769. }
  770. for (int i=0; i < FUNC_MAX_WATCHERS; i++) {
  771. interp->func_watchers[i] = NULL;
  772. }
  773. interp->active_func_watchers = 0;
  774. for (int i=0; i < CODE_MAX_WATCHERS; i++) {
  775. interp->code_watchers[i] = NULL;
  776. }
  777. interp->active_code_watchers = 0;
  778. interp->f_opcode_trace_set = false;
  779. // XXX Once we have one allocator per interpreter (i.e.
  780. // per-interpreter GC) we must ensure that all of the interpreter's
  781. // objects have been cleaned up at the point.
  782. }
  783. void
  784. PyInterpreterState_Clear(PyInterpreterState *interp)
  785. {
  786. // Use the current Python thread state to call audit hooks and to collect
  787. // garbage. It can be different than the current Python thread state
  788. // of 'interp'.
  789. PyThreadState *current_tstate = current_fast_get(interp->runtime);
  790. _PyImport_ClearCore(interp);
  791. interpreter_clear(interp, current_tstate);
  792. }
  793. void
  794. _PyInterpreterState_Clear(PyThreadState *tstate)
  795. {
  796. _PyImport_ClearCore(tstate->interp);
  797. interpreter_clear(tstate->interp, tstate);
  798. }
  799. static inline void tstate_deactivate(PyThreadState *tstate);
  800. static void zapthreads(PyInterpreterState *interp);
  801. void
  802. PyInterpreterState_Delete(PyInterpreterState *interp)
  803. {
  804. _PyRuntimeState *runtime = interp->runtime;
  805. struct pyinterpreters *interpreters = &runtime->interpreters;
  806. // XXX Clearing the "current" thread state should happen before
  807. // we start finalizing the interpreter (or the current thread state).
  808. PyThreadState *tcur = current_fast_get(runtime);
  809. if (tcur != NULL && interp == tcur->interp) {
  810. /* Unset current thread. After this, many C API calls become crashy. */
  811. current_fast_clear(runtime);
  812. tstate_deactivate(tcur);
  813. _PyEval_ReleaseLock(interp, NULL);
  814. }
  815. zapthreads(interp);
  816. _PyEval_FiniState(&interp->ceval);
  817. // XXX These two calls should be done at the end of clear_interpreter(),
  818. // but currently some objects get decref'ed after that.
  819. #ifdef Py_REF_DEBUG
  820. _PyInterpreterState_FinalizeRefTotal(interp);
  821. #endif
  822. _PyInterpreterState_FinalizeAllocatedBlocks(interp);
  823. HEAD_LOCK(runtime);
  824. PyInterpreterState **p;
  825. for (p = &interpreters->head; ; p = &(*p)->next) {
  826. if (*p == NULL) {
  827. Py_FatalError("NULL interpreter");
  828. }
  829. if (*p == interp) {
  830. break;
  831. }
  832. }
  833. if (interp->threads.head != NULL) {
  834. Py_FatalError("remaining threads");
  835. }
  836. *p = interp->next;
  837. if (interpreters->main == interp) {
  838. interpreters->main = NULL;
  839. if (interpreters->head != NULL) {
  840. Py_FatalError("remaining subinterpreters");
  841. }
  842. }
  843. HEAD_UNLOCK(runtime);
  844. if (interp->id_mutex != NULL) {
  845. PyThread_free_lock(interp->id_mutex);
  846. }
  847. free_interpreter(interp);
  848. }
  849. #ifdef HAVE_FORK
  850. /*
  851. * Delete all interpreter states except the main interpreter. If there
  852. * is a current interpreter state, it *must* be the main interpreter.
  853. */
  854. PyStatus
  855. _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
  856. {
  857. struct pyinterpreters *interpreters = &runtime->interpreters;
  858. PyThreadState *tstate = _PyThreadState_Swap(runtime, NULL);
  859. if (tstate != NULL && tstate->interp != interpreters->main) {
  860. return _PyStatus_ERR("not main interpreter");
  861. }
  862. HEAD_LOCK(runtime);
  863. PyInterpreterState *interp = interpreters->head;
  864. interpreters->head = NULL;
  865. while (interp != NULL) {
  866. if (interp == interpreters->main) {
  867. interpreters->main->next = NULL;
  868. interpreters->head = interp;
  869. interp = interp->next;
  870. continue;
  871. }
  872. // XXX Won't this fail since PyInterpreterState_Clear() requires
  873. // the "current" tstate to be set?
  874. PyInterpreterState_Clear(interp); // XXX must activate?
  875. zapthreads(interp);
  876. if (interp->id_mutex != NULL) {
  877. PyThread_free_lock(interp->id_mutex);
  878. }
  879. PyInterpreterState *prev_interp = interp;
  880. interp = interp->next;
  881. free_interpreter(prev_interp);
  882. }
  883. HEAD_UNLOCK(runtime);
  884. if (interpreters->head == NULL) {
  885. return _PyStatus_ERR("missing main interpreter");
  886. }
  887. _PyThreadState_Swap(runtime, tstate);
  888. return _PyStatus_OK();
  889. }
  890. #endif
  891. int
  892. _PyInterpreterState_SetRunningMain(PyInterpreterState *interp)
  893. {
  894. if (interp->threads_main != NULL) {
  895. PyErr_SetString(PyExc_RuntimeError,
  896. "interpreter already running");
  897. return -1;
  898. }
  899. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  900. _Py_EnsureTstateNotNULL(tstate);
  901. if (tstate->interp != interp) {
  902. PyErr_SetString(PyExc_RuntimeError,
  903. "current tstate has wrong interpreter");
  904. return -1;
  905. }
  906. interp->threads_main = tstate;
  907. return 0;
  908. }
  909. void
  910. _PyInterpreterState_SetNotRunningMain(PyInterpreterState *interp)
  911. {
  912. assert(interp->threads_main == current_fast_get(&_PyRuntime));
  913. interp->threads_main = NULL;
  914. }
  915. int
  916. _PyInterpreterState_IsRunningMain(PyInterpreterState *interp)
  917. {
  918. return (interp->threads_main != NULL);
  919. }
  920. //----------
  921. // accessors
  922. //----------
  923. int64_t
  924. PyInterpreterState_GetID(PyInterpreterState *interp)
  925. {
  926. if (interp == NULL) {
  927. PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
  928. return -1;
  929. }
  930. return interp->id;
  931. }
  932. int
  933. _PyInterpreterState_IDInitref(PyInterpreterState *interp)
  934. {
  935. if (interp->id_mutex != NULL) {
  936. return 0;
  937. }
  938. interp->id_mutex = PyThread_allocate_lock();
  939. if (interp->id_mutex == NULL) {
  940. PyErr_SetString(PyExc_RuntimeError,
  941. "failed to create init interpreter ID mutex");
  942. return -1;
  943. }
  944. interp->id_refcount = 0;
  945. return 0;
  946. }
  947. int
  948. _PyInterpreterState_IDIncref(PyInterpreterState *interp)
  949. {
  950. if (_PyInterpreterState_IDInitref(interp) < 0) {
  951. return -1;
  952. }
  953. PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
  954. interp->id_refcount += 1;
  955. PyThread_release_lock(interp->id_mutex);
  956. return 0;
  957. }
  958. void
  959. _PyInterpreterState_IDDecref(PyInterpreterState *interp)
  960. {
  961. assert(interp->id_mutex != NULL);
  962. _PyRuntimeState *runtime = interp->runtime;
  963. PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
  964. assert(interp->id_refcount != 0);
  965. interp->id_refcount -= 1;
  966. int64_t refcount = interp->id_refcount;
  967. PyThread_release_lock(interp->id_mutex);
  968. if (refcount == 0 && interp->requires_idref) {
  969. // XXX Using the "head" thread isn't strictly correct.
  970. PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
  971. // XXX Possible GILState issues?
  972. PyThreadState *save_tstate = _PyThreadState_Swap(runtime, tstate);
  973. Py_EndInterpreter(tstate);
  974. _PyThreadState_Swap(runtime, save_tstate);
  975. }
  976. }
  977. int
  978. _PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
  979. {
  980. return interp->requires_idref;
  981. }
  982. void
  983. _PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
  984. {
  985. interp->requires_idref = required ? 1 : 0;
  986. }
  987. PyObject *
  988. _PyInterpreterState_GetMainModule(PyInterpreterState *interp)
  989. {
  990. PyObject *modules = _PyImport_GetModules(interp);
  991. if (modules == NULL) {
  992. PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
  993. return NULL;
  994. }
  995. return PyMapping_GetItemString(modules, "__main__");
  996. }
  997. PyObject *
  998. PyInterpreterState_GetDict(PyInterpreterState *interp)
  999. {
  1000. if (interp->dict == NULL) {
  1001. interp->dict = PyDict_New();
  1002. if (interp->dict == NULL) {
  1003. PyErr_Clear();
  1004. }
  1005. }
  1006. /* Returning NULL means no per-interpreter dict is available. */
  1007. return interp->dict;
  1008. }
  1009. //-----------------------------
  1010. // look up an interpreter state
  1011. //-----------------------------
  1012. /* Return the interpreter associated with the current OS thread.
  1013. The GIL must be held.
  1014. */
  1015. PyInterpreterState *
  1016. PyInterpreterState_Get(void)
  1017. {
  1018. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1019. _Py_EnsureTstateNotNULL(tstate);
  1020. PyInterpreterState *interp = tstate->interp;
  1021. if (interp == NULL) {
  1022. Py_FatalError("no current interpreter");
  1023. }
  1024. return interp;
  1025. }
  1026. static PyInterpreterState *
  1027. interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
  1028. {
  1029. PyInterpreterState *interp = runtime->interpreters.head;
  1030. while (interp != NULL) {
  1031. int64_t id = PyInterpreterState_GetID(interp);
  1032. if (id < 0) {
  1033. return NULL;
  1034. }
  1035. if (requested_id == id) {
  1036. return interp;
  1037. }
  1038. interp = PyInterpreterState_Next(interp);
  1039. }
  1040. return NULL;
  1041. }
  1042. /* Return the interpreter state with the given ID.
  1043. Fail with RuntimeError if the interpreter is not found. */
  1044. PyInterpreterState *
  1045. _PyInterpreterState_LookUpID(int64_t requested_id)
  1046. {
  1047. PyInterpreterState *interp = NULL;
  1048. if (requested_id >= 0) {
  1049. _PyRuntimeState *runtime = &_PyRuntime;
  1050. HEAD_LOCK(runtime);
  1051. interp = interp_look_up_id(runtime, requested_id);
  1052. HEAD_UNLOCK(runtime);
  1053. }
  1054. if (interp == NULL && !PyErr_Occurred()) {
  1055. PyErr_Format(PyExc_RuntimeError,
  1056. "unrecognized interpreter ID %lld", requested_id);
  1057. }
  1058. return interp;
  1059. }
  1060. /********************************/
  1061. /* the per-thread runtime state */
  1062. /********************************/
  1063. #ifndef NDEBUG
  1064. static inline int
  1065. tstate_is_alive(PyThreadState *tstate)
  1066. {
  1067. return (tstate->_status.initialized &&
  1068. !tstate->_status.finalized &&
  1069. !tstate->_status.cleared &&
  1070. !tstate->_status.finalizing);
  1071. }
  1072. #endif
  1073. //----------
  1074. // lifecycle
  1075. //----------
  1076. /* Minimum size of data stack chunk */
  1077. #define DATA_STACK_CHUNK_SIZE (16*1024)
  1078. static _PyStackChunk*
  1079. allocate_chunk(int size_in_bytes, _PyStackChunk* previous)
  1080. {
  1081. assert(size_in_bytes % sizeof(PyObject **) == 0);
  1082. _PyStackChunk *res = _PyObject_VirtualAlloc(size_in_bytes);
  1083. if (res == NULL) {
  1084. return NULL;
  1085. }
  1086. res->previous = previous;
  1087. res->size = size_in_bytes;
  1088. res->top = 0;
  1089. return res;
  1090. }
  1091. static PyThreadState *
  1092. alloc_threadstate(void)
  1093. {
  1094. return PyMem_RawCalloc(1, sizeof(PyThreadState));
  1095. }
  1096. static void
  1097. free_threadstate(PyThreadState *tstate)
  1098. {
  1099. // The initial thread state of the interpreter is allocated
  1100. // as part of the interpreter state so should not be freed.
  1101. if (tstate != &tstate->interp->_initial_thread) {
  1102. PyMem_RawFree(tstate);
  1103. }
  1104. }
  1105. /* Get the thread state to a minimal consistent state.
  1106. Further init happens in pylifecycle.c before it can be used.
  1107. All fields not initialized here are expected to be zeroed out,
  1108. e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized.
  1109. The interpreter state is not manipulated. Instead it is assumed that
  1110. the thread is getting added to the interpreter.
  1111. */
  1112. static void
  1113. init_threadstate(PyThreadState *tstate,
  1114. PyInterpreterState *interp, uint64_t id)
  1115. {
  1116. if (tstate->_status.initialized) {
  1117. Py_FatalError("thread state already initialized");
  1118. }
  1119. assert(interp != NULL);
  1120. tstate->interp = interp;
  1121. // next/prev are set in add_threadstate().
  1122. assert(tstate->next == NULL);
  1123. assert(tstate->prev == NULL);
  1124. assert(id > 0);
  1125. tstate->id = id;
  1126. // thread_id and native_thread_id are set in bind_tstate().
  1127. tstate->py_recursion_limit = interp->ceval.recursion_limit,
  1128. tstate->py_recursion_remaining = interp->ceval.recursion_limit,
  1129. tstate->c_recursion_remaining = C_RECURSION_LIMIT;
  1130. tstate->exc_info = &tstate->exc_state;
  1131. // PyGILState_Release must not try to delete this thread state.
  1132. // This is cleared when PyGILState_Ensure() creates the thread state.
  1133. tstate->gilstate_counter = 1;
  1134. tstate->cframe = &tstate->root_cframe;
  1135. tstate->datastack_chunk = NULL;
  1136. tstate->datastack_top = NULL;
  1137. tstate->datastack_limit = NULL;
  1138. tstate->what_event = -1;
  1139. tstate->_status.initialized = 1;
  1140. }
  1141. static void
  1142. add_threadstate(PyInterpreterState *interp, PyThreadState *tstate,
  1143. PyThreadState *next)
  1144. {
  1145. assert(interp->threads.head != tstate);
  1146. assert((next != NULL && tstate->id != 1) ||
  1147. (next == NULL && tstate->id == 1));
  1148. if (next != NULL) {
  1149. assert(next->prev == NULL || next->prev == tstate);
  1150. next->prev = tstate;
  1151. }
  1152. tstate->next = next;
  1153. assert(tstate->prev == NULL);
  1154. interp->threads.head = tstate;
  1155. }
  1156. static PyThreadState *
  1157. new_threadstate(PyInterpreterState *interp)
  1158. {
  1159. PyThreadState *tstate;
  1160. _PyRuntimeState *runtime = interp->runtime;
  1161. // We don't need to allocate a thread state for the main interpreter
  1162. // (the common case), but doing it later for the other case revealed a
  1163. // reentrancy problem (deadlock). So for now we always allocate before
  1164. // taking the interpreters lock. See GH-96071.
  1165. PyThreadState *new_tstate = alloc_threadstate();
  1166. int used_newtstate;
  1167. if (new_tstate == NULL) {
  1168. return NULL;
  1169. }
  1170. /* We serialize concurrent creation to protect global state. */
  1171. HEAD_LOCK(runtime);
  1172. interp->threads.next_unique_id += 1;
  1173. uint64_t id = interp->threads.next_unique_id;
  1174. // Allocate the thread state and add it to the interpreter.
  1175. PyThreadState *old_head = interp->threads.head;
  1176. if (old_head == NULL) {
  1177. // It's the interpreter's initial thread state.
  1178. assert(id == 1);
  1179. used_newtstate = 0;
  1180. tstate = &interp->_initial_thread;
  1181. }
  1182. else {
  1183. // Every valid interpreter must have at least one thread.
  1184. assert(id > 1);
  1185. assert(old_head->prev == NULL);
  1186. used_newtstate = 1;
  1187. tstate = new_tstate;
  1188. // Set to _PyThreadState_INIT.
  1189. memcpy(tstate,
  1190. &initial._main_interpreter._initial_thread,
  1191. sizeof(*tstate));
  1192. }
  1193. init_threadstate(tstate, interp, id);
  1194. add_threadstate(interp, tstate, old_head);
  1195. HEAD_UNLOCK(runtime);
  1196. if (!used_newtstate) {
  1197. // Must be called with lock unlocked to avoid re-entrancy deadlock.
  1198. PyMem_RawFree(new_tstate);
  1199. }
  1200. return tstate;
  1201. }
  1202. PyThreadState *
  1203. PyThreadState_New(PyInterpreterState *interp)
  1204. {
  1205. PyThreadState *tstate = new_threadstate(interp);
  1206. if (tstate) {
  1207. bind_tstate(tstate);
  1208. // This makes sure there's a gilstate tstate bound
  1209. // as soon as possible.
  1210. if (gilstate_tss_get(tstate->interp->runtime) == NULL) {
  1211. bind_gilstate_tstate(tstate);
  1212. }
  1213. }
  1214. return tstate;
  1215. }
  1216. // This must be followed by a call to _PyThreadState_Bind();
  1217. PyThreadState *
  1218. _PyThreadState_New(PyInterpreterState *interp)
  1219. {
  1220. return new_threadstate(interp);
  1221. }
  1222. // We keep this for stable ABI compabibility.
  1223. PyThreadState *
  1224. _PyThreadState_Prealloc(PyInterpreterState *interp)
  1225. {
  1226. return _PyThreadState_New(interp);
  1227. }
  1228. // We keep this around for (accidental) stable ABI compatibility.
  1229. // Realistically, no extensions are using it.
  1230. void
  1231. _PyThreadState_Init(PyThreadState *tstate)
  1232. {
  1233. Py_FatalError("_PyThreadState_Init() is for internal use only");
  1234. }
  1235. static void
  1236. clear_datastack(PyThreadState *tstate)
  1237. {
  1238. _PyStackChunk *chunk = tstate->datastack_chunk;
  1239. tstate->datastack_chunk = NULL;
  1240. while (chunk != NULL) {
  1241. _PyStackChunk *prev = chunk->previous;
  1242. _PyObject_VirtualFree(chunk, chunk->size);
  1243. chunk = prev;
  1244. }
  1245. }
  1246. void
  1247. PyThreadState_Clear(PyThreadState *tstate)
  1248. {
  1249. assert(tstate->_status.initialized && !tstate->_status.cleared);
  1250. // XXX assert(!tstate->_status.bound || tstate->_status.unbound);
  1251. tstate->_status.finalizing = 1; // just in case
  1252. /* XXX Conditions we need to enforce:
  1253. * the GIL must be held by the current thread
  1254. * current_fast_get()->interp must match tstate->interp
  1255. * for the main interpreter, current_fast_get() must be the main thread
  1256. */
  1257. int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
  1258. if (verbose && tstate->cframe->current_frame != NULL) {
  1259. /* bpo-20526: After the main thread calls
  1260. _PyInterpreterState_SetFinalizing() in Py_FinalizeEx()
  1261. (or in Py_EndInterpreter() for subinterpreters),
  1262. threads must exit when trying to take the GIL.
  1263. If a thread exit in the middle of _PyEval_EvalFrameDefault(),
  1264. tstate->frame is not reset to its previous value.
  1265. It is more likely with daemon threads, but it can happen
  1266. with regular threads if threading._shutdown() fails
  1267. (ex: interrupted by CTRL+C). */
  1268. fprintf(stderr,
  1269. "PyThreadState_Clear: warning: thread still has a frame\n");
  1270. }
  1271. /* At this point tstate shouldn't be used any more,
  1272. neither to run Python code nor for other uses.
  1273. This is tricky when current_fast_get() == tstate, in the same way
  1274. as noted in interpreter_clear() above. The below finalizers
  1275. can possibly run Python code or otherwise use the partially
  1276. cleared thread state. For now we trust that isn't a problem
  1277. in practice.
  1278. */
  1279. // XXX Deal with the possibility of problematic finalizers.
  1280. /* Don't clear tstate->pyframe: it is a borrowed reference */
  1281. Py_CLEAR(tstate->dict);
  1282. Py_CLEAR(tstate->async_exc);
  1283. Py_CLEAR(tstate->current_exception);
  1284. Py_CLEAR(tstate->exc_state.exc_value);
  1285. /* The stack of exception states should contain just this thread. */
  1286. if (verbose && tstate->exc_info != &tstate->exc_state) {
  1287. fprintf(stderr,
  1288. "PyThreadState_Clear: warning: thread still has a generator\n");
  1289. }
  1290. if (tstate->c_profilefunc != NULL) {
  1291. tstate->interp->sys_profiling_threads--;
  1292. tstate->c_profilefunc = NULL;
  1293. }
  1294. if (tstate->c_tracefunc != NULL) {
  1295. tstate->interp->sys_tracing_threads--;
  1296. tstate->c_tracefunc = NULL;
  1297. }
  1298. Py_CLEAR(tstate->c_profileobj);
  1299. Py_CLEAR(tstate->c_traceobj);
  1300. Py_CLEAR(tstate->async_gen_firstiter);
  1301. Py_CLEAR(tstate->async_gen_finalizer);
  1302. Py_CLEAR(tstate->context);
  1303. if (tstate->on_delete != NULL) {
  1304. tstate->on_delete(tstate->on_delete_data);
  1305. }
  1306. tstate->_status.cleared = 1;
  1307. // XXX Call _PyThreadStateSwap(runtime, NULL) here if "current".
  1308. // XXX Do it as early in the function as possible.
  1309. }
  1310. /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
  1311. static void
  1312. tstate_delete_common(PyThreadState *tstate)
  1313. {
  1314. assert(tstate->_status.cleared && !tstate->_status.finalized);
  1315. PyInterpreterState *interp = tstate->interp;
  1316. if (interp == NULL) {
  1317. Py_FatalError("NULL interpreter");
  1318. }
  1319. _PyRuntimeState *runtime = interp->runtime;
  1320. HEAD_LOCK(runtime);
  1321. if (tstate->prev) {
  1322. tstate->prev->next = tstate->next;
  1323. }
  1324. else {
  1325. interp->threads.head = tstate->next;
  1326. }
  1327. if (tstate->next) {
  1328. tstate->next->prev = tstate->prev;
  1329. }
  1330. HEAD_UNLOCK(runtime);
  1331. // XXX Unbind in PyThreadState_Clear(), or earlier
  1332. // (and assert not-equal here)?
  1333. if (tstate->_status.bound_gilstate) {
  1334. unbind_gilstate_tstate(tstate);
  1335. }
  1336. unbind_tstate(tstate);
  1337. // XXX Move to PyThreadState_Clear()?
  1338. clear_datastack(tstate);
  1339. tstate->_status.finalized = 1;
  1340. }
  1341. static void
  1342. zapthreads(PyInterpreterState *interp)
  1343. {
  1344. PyThreadState *tstate;
  1345. /* No need to lock the mutex here because this should only happen
  1346. when the threads are all really dead (XXX famous last words). */
  1347. while ((tstate = interp->threads.head) != NULL) {
  1348. tstate_verify_not_active(tstate);
  1349. tstate_delete_common(tstate);
  1350. free_threadstate(tstate);
  1351. }
  1352. }
  1353. void
  1354. PyThreadState_Delete(PyThreadState *tstate)
  1355. {
  1356. _Py_EnsureTstateNotNULL(tstate);
  1357. tstate_verify_not_active(tstate);
  1358. tstate_delete_common(tstate);
  1359. free_threadstate(tstate);
  1360. }
  1361. void
  1362. _PyThreadState_DeleteCurrent(PyThreadState *tstate)
  1363. {
  1364. _Py_EnsureTstateNotNULL(tstate);
  1365. tstate_delete_common(tstate);
  1366. current_fast_clear(tstate->interp->runtime);
  1367. _PyEval_ReleaseLock(tstate->interp, NULL);
  1368. free_threadstate(tstate);
  1369. }
  1370. void
  1371. PyThreadState_DeleteCurrent(void)
  1372. {
  1373. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1374. _PyThreadState_DeleteCurrent(tstate);
  1375. }
  1376. /*
  1377. * Delete all thread states except the one passed as argument.
  1378. * Note that, if there is a current thread state, it *must* be the one
  1379. * passed as argument. Also, this won't touch any other interpreters
  1380. * than the current one, since we don't know which thread state should
  1381. * be kept in those other interpreters.
  1382. */
  1383. void
  1384. _PyThreadState_DeleteExcept(PyThreadState *tstate)
  1385. {
  1386. assert(tstate != NULL);
  1387. PyInterpreterState *interp = tstate->interp;
  1388. _PyRuntimeState *runtime = interp->runtime;
  1389. HEAD_LOCK(runtime);
  1390. /* Remove all thread states, except tstate, from the linked list of
  1391. thread states. This will allow calling PyThreadState_Clear()
  1392. without holding the lock. */
  1393. PyThreadState *list = interp->threads.head;
  1394. if (list == tstate) {
  1395. list = tstate->next;
  1396. }
  1397. if (tstate->prev) {
  1398. tstate->prev->next = tstate->next;
  1399. }
  1400. if (tstate->next) {
  1401. tstate->next->prev = tstate->prev;
  1402. }
  1403. tstate->prev = tstate->next = NULL;
  1404. interp->threads.head = tstate;
  1405. HEAD_UNLOCK(runtime);
  1406. /* Clear and deallocate all stale thread states. Even if this
  1407. executes Python code, we should be safe since it executes
  1408. in the current thread, not one of the stale threads. */
  1409. PyThreadState *p, *next;
  1410. for (p = list; p; p = next) {
  1411. next = p->next;
  1412. PyThreadState_Clear(p);
  1413. free_threadstate(p);
  1414. }
  1415. }
  1416. //----------
  1417. // accessors
  1418. //----------
  1419. /* An extension mechanism to store arbitrary additional per-thread state.
  1420. PyThreadState_GetDict() returns a dictionary that can be used to hold such
  1421. state; the caller should pick a unique key and store its state there. If
  1422. PyThreadState_GetDict() returns NULL, an exception has *not* been raised
  1423. and the caller should assume no per-thread state is available. */
  1424. PyObject *
  1425. _PyThreadState_GetDict(PyThreadState *tstate)
  1426. {
  1427. assert(tstate != NULL);
  1428. if (tstate->dict == NULL) {
  1429. tstate->dict = PyDict_New();
  1430. if (tstate->dict == NULL) {
  1431. _PyErr_Clear(tstate);
  1432. }
  1433. }
  1434. return tstate->dict;
  1435. }
  1436. PyObject *
  1437. PyThreadState_GetDict(void)
  1438. {
  1439. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1440. if (tstate == NULL) {
  1441. return NULL;
  1442. }
  1443. return _PyThreadState_GetDict(tstate);
  1444. }
  1445. PyInterpreterState *
  1446. PyThreadState_GetInterpreter(PyThreadState *tstate)
  1447. {
  1448. assert(tstate != NULL);
  1449. return tstate->interp;
  1450. }
  1451. PyFrameObject*
  1452. PyThreadState_GetFrame(PyThreadState *tstate)
  1453. {
  1454. assert(tstate != NULL);
  1455. _PyInterpreterFrame *f = _PyThreadState_GetFrame(tstate);
  1456. if (f == NULL) {
  1457. return NULL;
  1458. }
  1459. PyFrameObject *frame = _PyFrame_GetFrameObject(f);
  1460. if (frame == NULL) {
  1461. PyErr_Clear();
  1462. }
  1463. return (PyFrameObject*)Py_XNewRef(frame);
  1464. }
  1465. uint64_t
  1466. PyThreadState_GetID(PyThreadState *tstate)
  1467. {
  1468. assert(tstate != NULL);
  1469. return tstate->id;
  1470. }
  1471. static inline void
  1472. tstate_activate(PyThreadState *tstate)
  1473. {
  1474. assert(tstate != NULL);
  1475. // XXX assert(tstate_is_alive(tstate));
  1476. assert(tstate_is_bound(tstate));
  1477. assert(!tstate->_status.active);
  1478. assert(!tstate->_status.bound_gilstate ||
  1479. tstate == gilstate_tss_get((tstate->interp->runtime)));
  1480. if (!tstate->_status.bound_gilstate) {
  1481. bind_gilstate_tstate(tstate);
  1482. }
  1483. tstate->_status.active = 1;
  1484. }
  1485. static inline void
  1486. tstate_deactivate(PyThreadState *tstate)
  1487. {
  1488. assert(tstate != NULL);
  1489. // XXX assert(tstate_is_alive(tstate));
  1490. assert(tstate_is_bound(tstate));
  1491. assert(tstate->_status.active);
  1492. tstate->_status.active = 0;
  1493. // We do not unbind the gilstate tstate here.
  1494. // It will still be used in PyGILState_Ensure().
  1495. }
  1496. //----------
  1497. // other API
  1498. //----------
  1499. /* Asynchronously raise an exception in a thread.
  1500. Requested by Just van Rossum and Alex Martelli.
  1501. To prevent naive misuse, you must write your own extension
  1502. to call this, or use ctypes. Must be called with the GIL held.
  1503. Returns the number of tstates modified (normally 1, but 0 if `id` didn't
  1504. match any known thread id). Can be called with exc=NULL to clear an
  1505. existing async exception. This raises no exceptions. */
  1506. // XXX Move this to Python/ceval_gil.c?
  1507. // XXX Deprecate this.
  1508. int
  1509. PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
  1510. {
  1511. _PyRuntimeState *runtime = &_PyRuntime;
  1512. PyInterpreterState *interp = _PyInterpreterState_GET();
  1513. /* Although the GIL is held, a few C API functions can be called
  1514. * without the GIL held, and in particular some that create and
  1515. * destroy thread and interpreter states. Those can mutate the
  1516. * list of thread states we're traversing, so to prevent that we lock
  1517. * head_mutex for the duration.
  1518. */
  1519. HEAD_LOCK(runtime);
  1520. for (PyThreadState *tstate = interp->threads.head; tstate != NULL; tstate = tstate->next) {
  1521. if (tstate->thread_id != id) {
  1522. continue;
  1523. }
  1524. /* Tricky: we need to decref the current value
  1525. * (if any) in tstate->async_exc, but that can in turn
  1526. * allow arbitrary Python code to run, including
  1527. * perhaps calls to this function. To prevent
  1528. * deadlock, we need to release head_mutex before
  1529. * the decref.
  1530. */
  1531. PyObject *old_exc = tstate->async_exc;
  1532. tstate->async_exc = Py_XNewRef(exc);
  1533. HEAD_UNLOCK(runtime);
  1534. Py_XDECREF(old_exc);
  1535. _PyEval_SignalAsyncExc(tstate->interp);
  1536. return 1;
  1537. }
  1538. HEAD_UNLOCK(runtime);
  1539. return 0;
  1540. }
  1541. //---------------------------------
  1542. // API for the current thread state
  1543. //---------------------------------
  1544. PyThreadState *
  1545. _PyThreadState_UncheckedGet(void)
  1546. {
  1547. return current_fast_get(&_PyRuntime);
  1548. }
  1549. PyThreadState *
  1550. PyThreadState_Get(void)
  1551. {
  1552. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1553. _Py_EnsureTstateNotNULL(tstate);
  1554. return tstate;
  1555. }
  1556. static void
  1557. _swap_thread_states(_PyRuntimeState *runtime,
  1558. PyThreadState *oldts, PyThreadState *newts)
  1559. {
  1560. // XXX Do this only if oldts != NULL?
  1561. current_fast_clear(runtime);
  1562. if (oldts != NULL) {
  1563. // XXX assert(tstate_is_alive(oldts) && tstate_is_bound(oldts));
  1564. tstate_deactivate(oldts);
  1565. }
  1566. if (newts != NULL) {
  1567. // XXX assert(tstate_is_alive(newts));
  1568. assert(tstate_is_bound(newts));
  1569. current_fast_set(runtime, newts);
  1570. tstate_activate(newts);
  1571. }
  1572. }
  1573. PyThreadState *
  1574. _PyThreadState_SwapNoGIL(PyThreadState *newts)
  1575. {
  1576. #if defined(Py_DEBUG)
  1577. /* This can be called from PyEval_RestoreThread(). Similar
  1578. to it, we need to ensure errno doesn't change.
  1579. */
  1580. int err = errno;
  1581. #endif
  1582. PyThreadState *oldts = current_fast_get(&_PyRuntime);
  1583. _swap_thread_states(&_PyRuntime, oldts, newts);
  1584. #if defined(Py_DEBUG)
  1585. errno = err;
  1586. #endif
  1587. return oldts;
  1588. }
  1589. PyThreadState *
  1590. _PyThreadState_Swap(_PyRuntimeState *runtime, PyThreadState *newts)
  1591. {
  1592. PyThreadState *oldts = current_fast_get(runtime);
  1593. if (oldts != NULL) {
  1594. _PyEval_ReleaseLock(oldts->interp, oldts);
  1595. }
  1596. _swap_thread_states(runtime, oldts, newts);
  1597. if (newts != NULL) {
  1598. _PyEval_AcquireLock(newts);
  1599. }
  1600. return oldts;
  1601. }
  1602. PyThreadState *
  1603. PyThreadState_Swap(PyThreadState *newts)
  1604. {
  1605. return _PyThreadState_Swap(&_PyRuntime, newts);
  1606. }
  1607. void
  1608. _PyThreadState_Bind(PyThreadState *tstate)
  1609. {
  1610. // gh-104690: If Python is being finalized and PyInterpreterState_Delete()
  1611. // was called, tstate becomes a dangling pointer.
  1612. assert(_PyThreadState_CheckConsistency(tstate));
  1613. bind_tstate(tstate);
  1614. // This makes sure there's a gilstate tstate bound
  1615. // as soon as possible.
  1616. if (gilstate_tss_get(tstate->interp->runtime) == NULL) {
  1617. bind_gilstate_tstate(tstate);
  1618. }
  1619. }
  1620. /***********************************/
  1621. /* routines for advanced debuggers */
  1622. /***********************************/
  1623. // (requested by David Beazley)
  1624. // Don't use unless you know what you are doing!
  1625. PyInterpreterState *
  1626. PyInterpreterState_Head(void)
  1627. {
  1628. return _PyRuntime.interpreters.head;
  1629. }
  1630. PyInterpreterState *
  1631. PyInterpreterState_Main(void)
  1632. {
  1633. return _PyInterpreterState_Main();
  1634. }
  1635. PyInterpreterState *
  1636. PyInterpreterState_Next(PyInterpreterState *interp) {
  1637. return interp->next;
  1638. }
  1639. PyThreadState *
  1640. PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
  1641. return interp->threads.head;
  1642. }
  1643. PyThreadState *
  1644. PyThreadState_Next(PyThreadState *tstate) {
  1645. return tstate->next;
  1646. }
  1647. /********************************************/
  1648. /* reporting execution state of all threads */
  1649. /********************************************/
  1650. /* The implementation of sys._current_frames(). This is intended to be
  1651. called with the GIL held, as it will be when called via
  1652. sys._current_frames(). It's possible it would work fine even without
  1653. the GIL held, but haven't thought enough about that.
  1654. */
  1655. PyObject *
  1656. _PyThread_CurrentFrames(void)
  1657. {
  1658. _PyRuntimeState *runtime = &_PyRuntime;
  1659. PyThreadState *tstate = current_fast_get(runtime);
  1660. if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
  1661. return NULL;
  1662. }
  1663. PyObject *result = PyDict_New();
  1664. if (result == NULL) {
  1665. return NULL;
  1666. }
  1667. /* for i in all interpreters:
  1668. * for t in all of i's thread states:
  1669. * if t's frame isn't NULL, map t's id to its frame
  1670. * Because these lists can mutate even when the GIL is held, we
  1671. * need to grab head_mutex for the duration.
  1672. */
  1673. HEAD_LOCK(runtime);
  1674. PyInterpreterState *i;
  1675. for (i = runtime->interpreters.head; i != NULL; i = i->next) {
  1676. PyThreadState *t;
  1677. for (t = i->threads.head; t != NULL; t = t->next) {
  1678. _PyInterpreterFrame *frame = t->cframe->current_frame;
  1679. frame = _PyFrame_GetFirstComplete(frame);
  1680. if (frame == NULL) {
  1681. continue;
  1682. }
  1683. PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
  1684. if (id == NULL) {
  1685. goto fail;
  1686. }
  1687. PyObject *frameobj = (PyObject *)_PyFrame_GetFrameObject(frame);
  1688. if (frameobj == NULL) {
  1689. Py_DECREF(id);
  1690. goto fail;
  1691. }
  1692. int stat = PyDict_SetItem(result, id, frameobj);
  1693. Py_DECREF(id);
  1694. if (stat < 0) {
  1695. goto fail;
  1696. }
  1697. }
  1698. }
  1699. goto done;
  1700. fail:
  1701. Py_CLEAR(result);
  1702. done:
  1703. HEAD_UNLOCK(runtime);
  1704. return result;
  1705. }
  1706. /* The implementation of sys._current_exceptions(). This is intended to be
  1707. called with the GIL held, as it will be when called via
  1708. sys._current_exceptions(). It's possible it would work fine even without
  1709. the GIL held, but haven't thought enough about that.
  1710. */
  1711. PyObject *
  1712. _PyThread_CurrentExceptions(void)
  1713. {
  1714. _PyRuntimeState *runtime = &_PyRuntime;
  1715. PyThreadState *tstate = current_fast_get(runtime);
  1716. _Py_EnsureTstateNotNULL(tstate);
  1717. if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
  1718. return NULL;
  1719. }
  1720. PyObject *result = PyDict_New();
  1721. if (result == NULL) {
  1722. return NULL;
  1723. }
  1724. /* for i in all interpreters:
  1725. * for t in all of i's thread states:
  1726. * if t's frame isn't NULL, map t's id to its frame
  1727. * Because these lists can mutate even when the GIL is held, we
  1728. * need to grab head_mutex for the duration.
  1729. */
  1730. HEAD_LOCK(runtime);
  1731. PyInterpreterState *i;
  1732. for (i = runtime->interpreters.head; i != NULL; i = i->next) {
  1733. PyThreadState *t;
  1734. for (t = i->threads.head; t != NULL; t = t->next) {
  1735. _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
  1736. if (err_info == NULL) {
  1737. continue;
  1738. }
  1739. PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
  1740. if (id == NULL) {
  1741. goto fail;
  1742. }
  1743. PyObject *exc = err_info->exc_value;
  1744. assert(exc == NULL ||
  1745. exc == Py_None ||
  1746. PyExceptionInstance_Check(exc));
  1747. int stat = PyDict_SetItem(result, id, exc == NULL ? Py_None : exc);
  1748. Py_DECREF(id);
  1749. if (stat < 0) {
  1750. goto fail;
  1751. }
  1752. }
  1753. }
  1754. goto done;
  1755. fail:
  1756. Py_CLEAR(result);
  1757. done:
  1758. HEAD_UNLOCK(runtime);
  1759. return result;
  1760. }
  1761. /***********************************/
  1762. /* Python "auto thread state" API. */
  1763. /***********************************/
  1764. /* Internal initialization/finalization functions called by
  1765. Py_Initialize/Py_FinalizeEx
  1766. */
  1767. PyStatus
  1768. _PyGILState_Init(PyInterpreterState *interp)
  1769. {
  1770. if (!_Py_IsMainInterpreter(interp)) {
  1771. /* Currently, PyGILState is shared by all interpreters. The main
  1772. * interpreter is responsible to initialize it. */
  1773. return _PyStatus_OK();
  1774. }
  1775. _PyRuntimeState *runtime = interp->runtime;
  1776. assert(gilstate_tss_get(runtime) == NULL);
  1777. assert(runtime->gilstate.autoInterpreterState == NULL);
  1778. runtime->gilstate.autoInterpreterState = interp;
  1779. return _PyStatus_OK();
  1780. }
  1781. void
  1782. _PyGILState_Fini(PyInterpreterState *interp)
  1783. {
  1784. if (!_Py_IsMainInterpreter(interp)) {
  1785. /* Currently, PyGILState is shared by all interpreters. The main
  1786. * interpreter is responsible to initialize it. */
  1787. return;
  1788. }
  1789. interp->runtime->gilstate.autoInterpreterState = NULL;
  1790. }
  1791. // XXX Drop this.
  1792. PyStatus
  1793. _PyGILState_SetTstate(PyThreadState *tstate)
  1794. {
  1795. /* must init with valid states */
  1796. assert(tstate != NULL);
  1797. assert(tstate->interp != NULL);
  1798. if (!_Py_IsMainInterpreter(tstate->interp)) {
  1799. /* Currently, PyGILState is shared by all interpreters. The main
  1800. * interpreter is responsible to initialize it. */
  1801. return _PyStatus_OK();
  1802. }
  1803. #ifndef NDEBUG
  1804. _PyRuntimeState *runtime = tstate->interp->runtime;
  1805. assert(runtime->gilstate.autoInterpreterState == tstate->interp);
  1806. assert(gilstate_tss_get(runtime) == tstate);
  1807. assert(tstate->gilstate_counter == 1);
  1808. #endif
  1809. return _PyStatus_OK();
  1810. }
  1811. PyInterpreterState *
  1812. _PyGILState_GetInterpreterStateUnsafe(void)
  1813. {
  1814. return _PyRuntime.gilstate.autoInterpreterState;
  1815. }
  1816. /* The public functions */
  1817. PyThreadState *
  1818. PyGILState_GetThisThreadState(void)
  1819. {
  1820. _PyRuntimeState *runtime = &_PyRuntime;
  1821. if (!gilstate_tss_initialized(runtime)) {
  1822. return NULL;
  1823. }
  1824. return gilstate_tss_get(runtime);
  1825. }
  1826. int
  1827. PyGILState_Check(void)
  1828. {
  1829. _PyRuntimeState *runtime = &_PyRuntime;
  1830. if (!runtime->gilstate.check_enabled) {
  1831. return 1;
  1832. }
  1833. if (!gilstate_tss_initialized(runtime)) {
  1834. return 1;
  1835. }
  1836. PyThreadState *tstate = current_fast_get(runtime);
  1837. if (tstate == NULL) {
  1838. return 0;
  1839. }
  1840. return (tstate == gilstate_tss_get(runtime));
  1841. }
  1842. PyGILState_STATE
  1843. PyGILState_Ensure(void)
  1844. {
  1845. _PyRuntimeState *runtime = &_PyRuntime;
  1846. /* Note that we do not auto-init Python here - apart from
  1847. potential races with 2 threads auto-initializing, pep-311
  1848. spells out other issues. Embedders are expected to have
  1849. called Py_Initialize(). */
  1850. /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
  1851. called by Py_Initialize() */
  1852. assert(_PyEval_ThreadsInitialized());
  1853. assert(gilstate_tss_initialized(runtime));
  1854. assert(runtime->gilstate.autoInterpreterState != NULL);
  1855. PyThreadState *tcur = gilstate_tss_get(runtime);
  1856. int has_gil;
  1857. if (tcur == NULL) {
  1858. /* Create a new Python thread state for this thread */
  1859. tcur = new_threadstate(runtime->gilstate.autoInterpreterState);
  1860. if (tcur == NULL) {
  1861. Py_FatalError("Couldn't create thread-state for new thread");
  1862. }
  1863. bind_tstate(tcur);
  1864. bind_gilstate_tstate(tcur);
  1865. /* This is our thread state! We'll need to delete it in the
  1866. matching call to PyGILState_Release(). */
  1867. assert(tcur->gilstate_counter == 1);
  1868. tcur->gilstate_counter = 0;
  1869. has_gil = 0; /* new thread state is never current */
  1870. }
  1871. else {
  1872. has_gil = holds_gil(tcur);
  1873. }
  1874. if (!has_gil) {
  1875. PyEval_RestoreThread(tcur);
  1876. }
  1877. /* Update our counter in the thread-state - no need for locks:
  1878. - tcur will remain valid as we hold the GIL.
  1879. - the counter is safe as we are the only thread "allowed"
  1880. to modify this value
  1881. */
  1882. ++tcur->gilstate_counter;
  1883. return has_gil ? PyGILState_LOCKED : PyGILState_UNLOCKED;
  1884. }
  1885. void
  1886. PyGILState_Release(PyGILState_STATE oldstate)
  1887. {
  1888. _PyRuntimeState *runtime = &_PyRuntime;
  1889. PyThreadState *tstate = gilstate_tss_get(runtime);
  1890. if (tstate == NULL) {
  1891. Py_FatalError("auto-releasing thread-state, "
  1892. "but no thread-state for this thread");
  1893. }
  1894. /* We must hold the GIL and have our thread state current */
  1895. /* XXX - remove the check - the assert should be fine,
  1896. but while this is very new (April 2003), the extra check
  1897. by release-only users can't hurt.
  1898. */
  1899. if (!holds_gil(tstate)) {
  1900. _Py_FatalErrorFormat(__func__,
  1901. "thread state %p must be current when releasing",
  1902. tstate);
  1903. }
  1904. assert(holds_gil(tstate));
  1905. --tstate->gilstate_counter;
  1906. assert(tstate->gilstate_counter >= 0); /* illegal counter value */
  1907. /* If we're going to destroy this thread-state, we must
  1908. * clear it while the GIL is held, as destructors may run.
  1909. */
  1910. if (tstate->gilstate_counter == 0) {
  1911. /* can't have been locked when we created it */
  1912. assert(oldstate == PyGILState_UNLOCKED);
  1913. // XXX Unbind tstate here.
  1914. PyThreadState_Clear(tstate);
  1915. /* Delete the thread-state. Note this releases the GIL too!
  1916. * It's vital that the GIL be held here, to avoid shutdown
  1917. * races; see bugs 225673 and 1061968 (that nasty bug has a
  1918. * habit of coming back).
  1919. */
  1920. assert(current_fast_get(runtime) == tstate);
  1921. _PyThreadState_DeleteCurrent(tstate);
  1922. }
  1923. /* Release the lock if necessary */
  1924. else if (oldstate == PyGILState_UNLOCKED) {
  1925. PyEval_SaveThread();
  1926. }
  1927. }
  1928. /**************************/
  1929. /* cross-interpreter data */
  1930. /**************************/
  1931. /* cross-interpreter data */
  1932. static inline void
  1933. _xidata_init(_PyCrossInterpreterData *data)
  1934. {
  1935. // If the value is being reused
  1936. // then _xidata_clear() should have been called already.
  1937. assert(data->data == NULL);
  1938. assert(data->obj == NULL);
  1939. *data = (_PyCrossInterpreterData){0};
  1940. data->interp = -1;
  1941. }
  1942. static inline void
  1943. _xidata_clear(_PyCrossInterpreterData *data)
  1944. {
  1945. // _PyCrossInterpreterData only has two members that need to be
  1946. // cleaned up, if set: "data" must be freed and "obj" must be decref'ed.
  1947. // In both cases the original (owning) interpreter must be used,
  1948. // which is the caller's responsibility to ensure.
  1949. if (data->data != NULL) {
  1950. if (data->free != NULL) {
  1951. data->free(data->data);
  1952. }
  1953. data->data = NULL;
  1954. }
  1955. Py_CLEAR(data->obj);
  1956. }
  1957. void
  1958. _PyCrossInterpreterData_Init(_PyCrossInterpreterData *data,
  1959. PyInterpreterState *interp,
  1960. void *shared, PyObject *obj,
  1961. xid_newobjectfunc new_object)
  1962. {
  1963. assert(data != NULL);
  1964. assert(new_object != NULL);
  1965. _xidata_init(data);
  1966. data->data = shared;
  1967. if (obj != NULL) {
  1968. assert(interp != NULL);
  1969. // released in _PyCrossInterpreterData_Clear()
  1970. data->obj = Py_NewRef(obj);
  1971. }
  1972. // Ideally every object would know its owning interpreter.
  1973. // Until then, we have to rely on the caller to identify it
  1974. // (but we don't need it in all cases).
  1975. data->interp = (interp != NULL) ? interp->id : -1;
  1976. data->new_object = new_object;
  1977. }
  1978. int
  1979. _PyCrossInterpreterData_InitWithSize(_PyCrossInterpreterData *data,
  1980. PyInterpreterState *interp,
  1981. const size_t size, PyObject *obj,
  1982. xid_newobjectfunc new_object)
  1983. {
  1984. assert(size > 0);
  1985. // For now we always free the shared data in the same interpreter
  1986. // where it was allocated, so the interpreter is required.
  1987. assert(interp != NULL);
  1988. _PyCrossInterpreterData_Init(data, interp, NULL, obj, new_object);
  1989. data->data = PyMem_RawMalloc(size);
  1990. if (data->data == NULL) {
  1991. return -1;
  1992. }
  1993. data->free = PyMem_RawFree;
  1994. return 0;
  1995. }
  1996. void
  1997. _PyCrossInterpreterData_Clear(PyInterpreterState *interp,
  1998. _PyCrossInterpreterData *data)
  1999. {
  2000. assert(data != NULL);
  2001. // This must be called in the owning interpreter.
  2002. assert(interp == NULL || data->interp == interp->id);
  2003. _xidata_clear(data);
  2004. }
  2005. static int
  2006. _check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
  2007. {
  2008. // data->data can be anything, including NULL, so we don't check it.
  2009. // data->obj may be NULL, so we don't check it.
  2010. if (data->interp < 0) {
  2011. _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
  2012. return -1;
  2013. }
  2014. if (data->new_object == NULL) {
  2015. _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
  2016. return -1;
  2017. }
  2018. // data->free may be NULL, so we don't check it.
  2019. return 0;
  2020. }
  2021. crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
  2022. /* This is a separate func from _PyCrossInterpreterData_Lookup in order
  2023. to keep the registry code separate. */
  2024. static crossinterpdatafunc
  2025. _lookup_getdata(PyObject *obj)
  2026. {
  2027. crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
  2028. if (getdata == NULL && PyErr_Occurred() == 0)
  2029. PyErr_Format(PyExc_ValueError,
  2030. "%S does not support cross-interpreter data", obj);
  2031. return getdata;
  2032. }
  2033. int
  2034. _PyObject_CheckCrossInterpreterData(PyObject *obj)
  2035. {
  2036. crossinterpdatafunc getdata = _lookup_getdata(obj);
  2037. if (getdata == NULL) {
  2038. return -1;
  2039. }
  2040. return 0;
  2041. }
  2042. int
  2043. _PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
  2044. {
  2045. _PyRuntimeState *runtime = &_PyRuntime;
  2046. PyThreadState *tstate = current_fast_get(runtime);
  2047. #ifdef Py_DEBUG
  2048. // The caller must hold the GIL
  2049. _Py_EnsureTstateNotNULL(tstate);
  2050. #endif
  2051. PyInterpreterState *interp = tstate->interp;
  2052. // Reset data before re-populating.
  2053. *data = (_PyCrossInterpreterData){0};
  2054. data->interp = -1;
  2055. // Call the "getdata" func for the object.
  2056. Py_INCREF(obj);
  2057. crossinterpdatafunc getdata = _lookup_getdata(obj);
  2058. if (getdata == NULL) {
  2059. Py_DECREF(obj);
  2060. return -1;
  2061. }
  2062. int res = getdata(tstate, obj, data);
  2063. Py_DECREF(obj);
  2064. if (res != 0) {
  2065. return -1;
  2066. }
  2067. // Fill in the blanks and validate the result.
  2068. data->interp = interp->id;
  2069. if (_check_xidata(tstate, data) != 0) {
  2070. (void)_PyCrossInterpreterData_Release(data);
  2071. return -1;
  2072. }
  2073. return 0;
  2074. }
  2075. PyObject *
  2076. _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
  2077. {
  2078. return data->new_object(data);
  2079. }
  2080. static int
  2081. _release_xidata_pending(void *data)
  2082. {
  2083. _xidata_clear((_PyCrossInterpreterData *)data);
  2084. return 0;
  2085. }
  2086. static int
  2087. _xidata_release_and_rawfree_pending(void *data)
  2088. {
  2089. _xidata_clear((_PyCrossInterpreterData *)data);
  2090. PyMem_RawFree(data);
  2091. return 0;
  2092. }
  2093. static int
  2094. _xidata_release(_PyCrossInterpreterData *data, int rawfree)
  2095. {
  2096. if ((data->data == NULL || data->free == NULL) && data->obj == NULL) {
  2097. // Nothing to release!
  2098. if (rawfree) {
  2099. PyMem_RawFree(data);
  2100. }
  2101. else {
  2102. data->data = NULL;
  2103. }
  2104. return 0;
  2105. }
  2106. // Switch to the original interpreter.
  2107. PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
  2108. if (interp == NULL) {
  2109. // The interpreter was already destroyed.
  2110. // This function shouldn't have been called.
  2111. // XXX Someone leaked some memory...
  2112. assert(PyErr_Occurred());
  2113. if (rawfree) {
  2114. PyMem_RawFree(data);
  2115. }
  2116. return -1;
  2117. }
  2118. // "Release" the data and/or the object.
  2119. if (interp == current_fast_get(interp->runtime)->interp) {
  2120. _xidata_clear(data);
  2121. if (rawfree) {
  2122. PyMem_RawFree(data);
  2123. }
  2124. }
  2125. else {
  2126. int (*func)(void *) = _release_xidata_pending;
  2127. if (rawfree) {
  2128. func = _xidata_release_and_rawfree_pending;
  2129. }
  2130. // XXX Emit a warning if this fails?
  2131. _PyEval_AddPendingCall(interp, func, data, 0);
  2132. }
  2133. return 0;
  2134. }
  2135. int
  2136. _PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
  2137. {
  2138. return _xidata_release(data, 0);
  2139. }
  2140. int
  2141. _PyCrossInterpreterData_ReleaseAndRawFree(_PyCrossInterpreterData *data)
  2142. {
  2143. return _xidata_release(data, 1);
  2144. }
  2145. /* registry of {type -> crossinterpdatafunc} */
  2146. /* For now we use a global registry of shareable classes. An
  2147. alternative would be to add a tp_* slot for a class's
  2148. crossinterpdatafunc. It would be simpler and more efficient. */
  2149. static int
  2150. _xidregistry_add_type(struct _xidregistry *xidregistry,
  2151. PyTypeObject *cls, crossinterpdatafunc getdata)
  2152. {
  2153. struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
  2154. if (newhead == NULL) {
  2155. return -1;
  2156. }
  2157. *newhead = (struct _xidregitem){
  2158. // We do not keep a reference, to avoid keeping the class alive.
  2159. .cls = cls,
  2160. .refcount = 1,
  2161. .getdata = getdata,
  2162. };
  2163. if (cls->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  2164. // XXX Assign a callback to clear the entry from the registry?
  2165. newhead->weakref = PyWeakref_NewRef((PyObject *)cls, NULL);
  2166. if (newhead->weakref == NULL) {
  2167. PyMem_RawFree(newhead);
  2168. return -1;
  2169. }
  2170. }
  2171. newhead->next = xidregistry->head;
  2172. if (newhead->next != NULL) {
  2173. newhead->next->prev = newhead;
  2174. }
  2175. xidregistry->head = newhead;
  2176. return 0;
  2177. }
  2178. static struct _xidregitem *
  2179. _xidregistry_remove_entry(struct _xidregistry *xidregistry,
  2180. struct _xidregitem *entry)
  2181. {
  2182. struct _xidregitem *next = entry->next;
  2183. if (entry->prev != NULL) {
  2184. assert(entry->prev->next == entry);
  2185. entry->prev->next = next;
  2186. }
  2187. else {
  2188. assert(xidregistry->head == entry);
  2189. xidregistry->head = next;
  2190. }
  2191. if (next != NULL) {
  2192. next->prev = entry->prev;
  2193. }
  2194. Py_XDECREF(entry->weakref);
  2195. PyMem_RawFree(entry);
  2196. return next;
  2197. }
  2198. static void
  2199. _xidregistry_clear(struct _xidregistry *xidregistry)
  2200. {
  2201. struct _xidregitem *cur = xidregistry->head;
  2202. xidregistry->head = NULL;
  2203. while (cur != NULL) {
  2204. struct _xidregitem *next = cur->next;
  2205. Py_XDECREF(cur->weakref);
  2206. PyMem_RawFree(cur);
  2207. cur = next;
  2208. }
  2209. }
  2210. static struct _xidregitem *
  2211. _xidregistry_find_type(struct _xidregistry *xidregistry, PyTypeObject *cls)
  2212. {
  2213. struct _xidregitem *cur = xidregistry->head;
  2214. while (cur != NULL) {
  2215. if (cur->weakref != NULL) {
  2216. // cur is/was a heap type.
  2217. PyObject *registered = PyWeakref_GetObject(cur->weakref);
  2218. assert(registered != NULL);
  2219. if (registered == Py_None) {
  2220. // The weakly ref'ed object was freed.
  2221. cur = _xidregistry_remove_entry(xidregistry, cur);
  2222. continue;
  2223. }
  2224. assert(PyType_Check(registered));
  2225. assert(cur->cls == (PyTypeObject *)registered);
  2226. assert(cur->cls->tp_flags & Py_TPFLAGS_HEAPTYPE);
  2227. //Py_DECREF(registered);
  2228. }
  2229. if (cur->cls == cls) {
  2230. return cur;
  2231. }
  2232. cur = cur->next;
  2233. }
  2234. return NULL;
  2235. }
  2236. static inline struct _xidregistry *
  2237. _get_xidregistry(PyInterpreterState *interp, PyTypeObject *cls)
  2238. {
  2239. struct _xidregistry *xidregistry = &interp->runtime->xidregistry;
  2240. if (cls->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  2241. assert(interp->xidregistry.mutex == xidregistry->mutex);
  2242. xidregistry = &interp->xidregistry;
  2243. }
  2244. return xidregistry;
  2245. }
  2246. static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
  2247. static inline void
  2248. _ensure_builtins_xid(PyInterpreterState *interp, struct _xidregistry *xidregistry)
  2249. {
  2250. if (xidregistry != &interp->xidregistry) {
  2251. assert(xidregistry == &interp->runtime->xidregistry);
  2252. if (xidregistry->head == NULL) {
  2253. _register_builtins_for_crossinterpreter_data(xidregistry);
  2254. }
  2255. }
  2256. }
  2257. int
  2258. _PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
  2259. crossinterpdatafunc getdata)
  2260. {
  2261. if (!PyType_Check(cls)) {
  2262. PyErr_Format(PyExc_ValueError, "only classes may be registered");
  2263. return -1;
  2264. }
  2265. if (getdata == NULL) {
  2266. PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
  2267. return -1;
  2268. }
  2269. int res = 0;
  2270. PyInterpreterState *interp = _PyInterpreterState_GET();
  2271. struct _xidregistry *xidregistry = _get_xidregistry(interp, cls);
  2272. PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
  2273. _ensure_builtins_xid(interp, xidregistry);
  2274. struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
  2275. if (matched != NULL) {
  2276. assert(matched->getdata == getdata);
  2277. matched->refcount += 1;
  2278. goto finally;
  2279. }
  2280. res = _xidregistry_add_type(xidregistry, cls, getdata);
  2281. finally:
  2282. PyThread_release_lock(xidregistry->mutex);
  2283. return res;
  2284. }
  2285. int
  2286. _PyCrossInterpreterData_UnregisterClass(PyTypeObject *cls)
  2287. {
  2288. int res = 0;
  2289. PyInterpreterState *interp = _PyInterpreterState_GET();
  2290. struct _xidregistry *xidregistry = _get_xidregistry(interp, cls);
  2291. PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
  2292. struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
  2293. if (matched != NULL) {
  2294. assert(matched->refcount > 0);
  2295. matched->refcount -= 1;
  2296. if (matched->refcount == 0) {
  2297. (void)_xidregistry_remove_entry(xidregistry, matched);
  2298. }
  2299. res = 1;
  2300. }
  2301. PyThread_release_lock(xidregistry->mutex);
  2302. return res;
  2303. }
  2304. /* Cross-interpreter objects are looked up by exact match on the class.
  2305. We can reassess this policy when we move from a global registry to a
  2306. tp_* slot. */
  2307. crossinterpdatafunc
  2308. _PyCrossInterpreterData_Lookup(PyObject *obj)
  2309. {
  2310. PyTypeObject *cls = Py_TYPE(obj);
  2311. PyInterpreterState *interp = _PyInterpreterState_GET();
  2312. struct _xidregistry *xidregistry = _get_xidregistry(interp, cls);
  2313. PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
  2314. _ensure_builtins_xid(interp, xidregistry);
  2315. struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
  2316. crossinterpdatafunc func = matched != NULL ? matched->getdata : NULL;
  2317. PyThread_release_lock(xidregistry->mutex);
  2318. return func;
  2319. }
  2320. /* cross-interpreter data for builtin types */
  2321. struct _shared_bytes_data {
  2322. char *bytes;
  2323. Py_ssize_t len;
  2324. };
  2325. static PyObject *
  2326. _new_bytes_object(_PyCrossInterpreterData *data)
  2327. {
  2328. struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
  2329. return PyBytes_FromStringAndSize(shared->bytes, shared->len);
  2330. }
  2331. static int
  2332. _bytes_shared(PyThreadState *tstate, PyObject *obj,
  2333. _PyCrossInterpreterData *data)
  2334. {
  2335. if (_PyCrossInterpreterData_InitWithSize(
  2336. data, tstate->interp, sizeof(struct _shared_bytes_data), obj,
  2337. _new_bytes_object
  2338. ) < 0)
  2339. {
  2340. return -1;
  2341. }
  2342. struct _shared_bytes_data *shared = (struct _shared_bytes_data *)data->data;
  2343. if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
  2344. _PyCrossInterpreterData_Clear(tstate->interp, data);
  2345. return -1;
  2346. }
  2347. return 0;
  2348. }
  2349. struct _shared_str_data {
  2350. int kind;
  2351. const void *buffer;
  2352. Py_ssize_t len;
  2353. };
  2354. static PyObject *
  2355. _new_str_object(_PyCrossInterpreterData *data)
  2356. {
  2357. struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
  2358. return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
  2359. }
  2360. static int
  2361. _str_shared(PyThreadState *tstate, PyObject *obj,
  2362. _PyCrossInterpreterData *data)
  2363. {
  2364. if (_PyCrossInterpreterData_InitWithSize(
  2365. data, tstate->interp, sizeof(struct _shared_str_data), obj,
  2366. _new_str_object
  2367. ) < 0)
  2368. {
  2369. return -1;
  2370. }
  2371. struct _shared_str_data *shared = (struct _shared_str_data *)data->data;
  2372. shared->kind = PyUnicode_KIND(obj);
  2373. shared->buffer = PyUnicode_DATA(obj);
  2374. shared->len = PyUnicode_GET_LENGTH(obj);
  2375. return 0;
  2376. }
  2377. static PyObject *
  2378. _new_long_object(_PyCrossInterpreterData *data)
  2379. {
  2380. return PyLong_FromSsize_t((Py_ssize_t)(data->data));
  2381. }
  2382. static int
  2383. _long_shared(PyThreadState *tstate, PyObject *obj,
  2384. _PyCrossInterpreterData *data)
  2385. {
  2386. /* Note that this means the size of shareable ints is bounded by
  2387. * sys.maxsize. Hence on 32-bit architectures that is half the
  2388. * size of maximum shareable ints on 64-bit.
  2389. */
  2390. Py_ssize_t value = PyLong_AsSsize_t(obj);
  2391. if (value == -1 && PyErr_Occurred()) {
  2392. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  2393. PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
  2394. }
  2395. return -1;
  2396. }
  2397. _PyCrossInterpreterData_Init(data, tstate->interp, (void *)value, NULL,
  2398. _new_long_object);
  2399. // data->obj and data->free remain NULL
  2400. return 0;
  2401. }
  2402. static PyObject *
  2403. _new_none_object(_PyCrossInterpreterData *data)
  2404. {
  2405. // XXX Singleton refcounts are problematic across interpreters...
  2406. return Py_NewRef(Py_None);
  2407. }
  2408. static int
  2409. _none_shared(PyThreadState *tstate, PyObject *obj,
  2410. _PyCrossInterpreterData *data)
  2411. {
  2412. _PyCrossInterpreterData_Init(data, tstate->interp, NULL, NULL,
  2413. _new_none_object);
  2414. // data->data, data->obj and data->free remain NULL
  2415. return 0;
  2416. }
  2417. static void
  2418. _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
  2419. {
  2420. // None
  2421. if (_xidregistry_add_type(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
  2422. Py_FatalError("could not register None for cross-interpreter sharing");
  2423. }
  2424. // int
  2425. if (_xidregistry_add_type(xidregistry, &PyLong_Type, _long_shared) != 0) {
  2426. Py_FatalError("could not register int for cross-interpreter sharing");
  2427. }
  2428. // bytes
  2429. if (_xidregistry_add_type(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
  2430. Py_FatalError("could not register bytes for cross-interpreter sharing");
  2431. }
  2432. // str
  2433. if (_xidregistry_add_type(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
  2434. Py_FatalError("could not register str for cross-interpreter sharing");
  2435. }
  2436. }
  2437. /*************/
  2438. /* Other API */
  2439. /*************/
  2440. _PyFrameEvalFunction
  2441. _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
  2442. {
  2443. if (interp->eval_frame == NULL) {
  2444. return _PyEval_EvalFrameDefault;
  2445. }
  2446. return interp->eval_frame;
  2447. }
  2448. void
  2449. _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
  2450. _PyFrameEvalFunction eval_frame)
  2451. {
  2452. if (eval_frame == _PyEval_EvalFrameDefault) {
  2453. interp->eval_frame = NULL;
  2454. }
  2455. else {
  2456. interp->eval_frame = eval_frame;
  2457. }
  2458. }
  2459. const PyConfig*
  2460. _PyInterpreterState_GetConfig(PyInterpreterState *interp)
  2461. {
  2462. return &interp->config;
  2463. }
  2464. int
  2465. _PyInterpreterState_GetConfigCopy(PyConfig *config)
  2466. {
  2467. PyInterpreterState *interp = PyInterpreterState_Get();
  2468. PyStatus status = _PyConfig_Copy(config, &interp->config);
  2469. if (PyStatus_Exception(status)) {
  2470. _PyErr_SetFromPyStatus(status);
  2471. return -1;
  2472. }
  2473. return 0;
  2474. }
  2475. const PyConfig*
  2476. _Py_GetConfig(void)
  2477. {
  2478. _PyRuntimeState *runtime = &_PyRuntime;
  2479. assert(PyGILState_Check());
  2480. PyThreadState *tstate = current_fast_get(runtime);
  2481. _Py_EnsureTstateNotNULL(tstate);
  2482. return _PyInterpreterState_GetConfig(tstate->interp);
  2483. }
  2484. int
  2485. _PyInterpreterState_HasFeature(PyInterpreterState *interp, unsigned long feature)
  2486. {
  2487. return ((interp->feature_flags & feature) != 0);
  2488. }
  2489. #define MINIMUM_OVERHEAD 1000
  2490. static PyObject **
  2491. push_chunk(PyThreadState *tstate, int size)
  2492. {
  2493. int allocate_size = DATA_STACK_CHUNK_SIZE;
  2494. while (allocate_size < (int)sizeof(PyObject*)*(size + MINIMUM_OVERHEAD)) {
  2495. allocate_size *= 2;
  2496. }
  2497. _PyStackChunk *new = allocate_chunk(allocate_size, tstate->datastack_chunk);
  2498. if (new == NULL) {
  2499. return NULL;
  2500. }
  2501. if (tstate->datastack_chunk) {
  2502. tstate->datastack_chunk->top = tstate->datastack_top -
  2503. &tstate->datastack_chunk->data[0];
  2504. }
  2505. tstate->datastack_chunk = new;
  2506. tstate->datastack_limit = (PyObject **)(((char *)new) + allocate_size);
  2507. // When new is the "root" chunk (i.e. new->previous == NULL), we can keep
  2508. // _PyThreadState_PopFrame from freeing it later by "skipping" over the
  2509. // first element:
  2510. PyObject **res = &new->data[new->previous == NULL];
  2511. tstate->datastack_top = res + size;
  2512. return res;
  2513. }
  2514. _PyInterpreterFrame *
  2515. _PyThreadState_PushFrame(PyThreadState *tstate, size_t size)
  2516. {
  2517. assert(size < INT_MAX/sizeof(PyObject *));
  2518. if (_PyThreadState_HasStackSpace(tstate, (int)size)) {
  2519. _PyInterpreterFrame *res = (_PyInterpreterFrame *)tstate->datastack_top;
  2520. tstate->datastack_top += size;
  2521. return res;
  2522. }
  2523. return (_PyInterpreterFrame *)push_chunk(tstate, (int)size);
  2524. }
  2525. void
  2526. _PyThreadState_PopFrame(PyThreadState *tstate, _PyInterpreterFrame * frame)
  2527. {
  2528. assert(tstate->datastack_chunk);
  2529. PyObject **base = (PyObject **)frame;
  2530. if (base == &tstate->datastack_chunk->data[0]) {
  2531. _PyStackChunk *chunk = tstate->datastack_chunk;
  2532. _PyStackChunk *previous = chunk->previous;
  2533. // push_chunk ensures that the root chunk is never popped:
  2534. assert(previous);
  2535. tstate->datastack_top = &previous->data[previous->top];
  2536. tstate->datastack_chunk = previous;
  2537. _PyObject_VirtualFree(chunk, chunk->size);
  2538. tstate->datastack_limit = (PyObject **)(((char *)previous) + previous->size);
  2539. }
  2540. else {
  2541. assert(tstate->datastack_top);
  2542. assert(tstate->datastack_top >= base);
  2543. tstate->datastack_top = base;
  2544. }
  2545. }
  2546. #ifndef NDEBUG
  2547. // Check that a Python thread state valid. In practice, this function is used
  2548. // on a Python debug build to check if 'tstate' is a dangling pointer, if the
  2549. // PyThreadState memory has been freed.
  2550. //
  2551. // Usage:
  2552. //
  2553. // assert(_PyThreadState_CheckConsistency(tstate));
  2554. int
  2555. _PyThreadState_CheckConsistency(PyThreadState *tstate)
  2556. {
  2557. assert(!_PyMem_IsPtrFreed(tstate));
  2558. assert(!_PyMem_IsPtrFreed(tstate->interp));
  2559. return 1;
  2560. }
  2561. #endif
  2562. // Check if a Python thread must exit immediately, rather than taking the GIL
  2563. // if Py_Finalize() has been called.
  2564. //
  2565. // When this function is called by a daemon thread after Py_Finalize() has been
  2566. // called, the GIL does no longer exist.
  2567. //
  2568. // tstate can be a dangling pointer (point to freed memory): only tstate value
  2569. // is used, the pointer is not deferenced.
  2570. //
  2571. // tstate must be non-NULL.
  2572. int
  2573. _PyThreadState_MustExit(PyThreadState *tstate)
  2574. {
  2575. /* bpo-39877: Access _PyRuntime directly rather than using
  2576. tstate->interp->runtime to support calls from Python daemon threads.
  2577. After Py_Finalize() has been called, tstate can be a dangling pointer:
  2578. point to PyThreadState freed memory. */
  2579. unsigned long finalizing_id = _PyRuntimeState_GetFinalizingID(&_PyRuntime);
  2580. PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(&_PyRuntime);
  2581. if (finalizing == NULL) {
  2582. // XXX This isn't completely safe from daemon thraeds,
  2583. // since tstate might be a dangling pointer.
  2584. finalizing = _PyInterpreterState_GetFinalizing(tstate->interp);
  2585. finalizing_id = _PyInterpreterState_GetFinalizingID(tstate->interp);
  2586. }
  2587. // XXX else check &_PyRuntime._main_interpreter._initial_thread
  2588. if (finalizing == NULL) {
  2589. return 0;
  2590. }
  2591. else if (finalizing == tstate) {
  2592. return 0;
  2593. }
  2594. else if (finalizing_id == PyThread_get_thread_ident()) {
  2595. /* gh-109793: we must have switched interpreters. */
  2596. return 0;
  2597. }
  2598. return 1;
  2599. }
  2600. #ifdef __cplusplus
  2601. }
  2602. #endif