pystate.c 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078
  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 PyGILState_Check();
  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. // We would call _PyObject_InitState() at this point
  575. // if interp->feature_flags were alredy set.
  576. _PyEval_InitState(interp, pending_lock);
  577. _PyGC_InitState(&interp->gc);
  578. PyConfig_InitPythonConfig(&interp->config);
  579. _PyType_InitCache(interp);
  580. for (int i = 0; i < _PY_MONITORING_UNGROUPED_EVENTS; i++) {
  581. interp->monitors.tools[i] = 0;
  582. }
  583. for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
  584. for (int e = 0; e < _PY_MONITORING_EVENTS; e++) {
  585. interp->monitoring_callables[t][e] = NULL;
  586. }
  587. }
  588. interp->sys_profile_initialized = false;
  589. interp->sys_trace_initialized = false;
  590. if (interp != &runtime->_main_interpreter) {
  591. /* Fix the self-referential, statically initialized fields. */
  592. interp->dtoa = (struct _dtoa_state)_dtoa_state_INIT(interp);
  593. }
  594. interp->f_opcode_trace_set = false;
  595. assert(runtime->xidregistry.mutex != NULL);
  596. interp->xidregistry.mutex = runtime->xidregistry.mutex;
  597. interp->_initialized = 1;
  598. }
  599. PyInterpreterState *
  600. PyInterpreterState_New(void)
  601. {
  602. PyInterpreterState *interp;
  603. _PyRuntimeState *runtime = &_PyRuntime;
  604. PyThreadState *tstate = current_fast_get(runtime);
  605. /* tstate is NULL when Py_InitializeFromConfig() calls
  606. PyInterpreterState_New() to create the main interpreter. */
  607. if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
  608. return NULL;
  609. }
  610. PyThread_type_lock pending_lock = PyThread_allocate_lock();
  611. if (pending_lock == NULL) {
  612. if (tstate != NULL) {
  613. _PyErr_NoMemory(tstate);
  614. }
  615. return NULL;
  616. }
  617. /* Don't get runtime from tstate since tstate can be NULL. */
  618. struct pyinterpreters *interpreters = &runtime->interpreters;
  619. /* We completely serialize creation of multiple interpreters, since
  620. it simplifies things here and blocking concurrent calls isn't a problem.
  621. Regardless, we must fully block subinterpreter creation until
  622. after the main interpreter is created. */
  623. HEAD_LOCK(runtime);
  624. int64_t id = interpreters->next_id;
  625. interpreters->next_id += 1;
  626. // Allocate the interpreter and add it to the runtime state.
  627. PyInterpreterState *old_head = interpreters->head;
  628. if (old_head == NULL) {
  629. // We are creating the main interpreter.
  630. assert(interpreters->main == NULL);
  631. assert(id == 0);
  632. interp = &runtime->_main_interpreter;
  633. assert(interp->id == 0);
  634. assert(interp->next == NULL);
  635. interpreters->main = interp;
  636. }
  637. else {
  638. assert(interpreters->main != NULL);
  639. assert(id != 0);
  640. interp = alloc_interpreter();
  641. if (interp == NULL) {
  642. goto error;
  643. }
  644. // Set to _PyInterpreterState_INIT.
  645. memcpy(interp, &initial._main_interpreter,
  646. sizeof(*interp));
  647. if (id < 0) {
  648. /* overflow or Py_Initialize() not called yet! */
  649. if (tstate != NULL) {
  650. _PyErr_SetString(tstate, PyExc_RuntimeError,
  651. "failed to get an interpreter ID");
  652. }
  653. goto error;
  654. }
  655. }
  656. interpreters->head = interp;
  657. init_interpreter(interp, runtime, id, old_head, pending_lock);
  658. HEAD_UNLOCK(runtime);
  659. return interp;
  660. error:
  661. HEAD_UNLOCK(runtime);
  662. PyThread_free_lock(pending_lock);
  663. if (interp != NULL) {
  664. free_interpreter(interp);
  665. }
  666. return NULL;
  667. }
  668. static void
  669. interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
  670. {
  671. assert(interp != NULL);
  672. assert(tstate != NULL);
  673. _PyRuntimeState *runtime = interp->runtime;
  674. /* XXX Conditions we need to enforce:
  675. * the GIL must be held by the current thread
  676. * tstate must be the "current" thread state (current_fast_get())
  677. * tstate->interp must be interp
  678. * for the main interpreter, tstate must be the main thread
  679. */
  680. // XXX Ideally, we would not rely on any thread state in this function
  681. // (and we would drop the "tstate" argument).
  682. if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
  683. _PyErr_Clear(tstate);
  684. }
  685. // Clear the current/main thread state last.
  686. HEAD_LOCK(runtime);
  687. PyThreadState *p = interp->threads.head;
  688. HEAD_UNLOCK(runtime);
  689. while (p != NULL) {
  690. // See https://github.com/python/cpython/issues/102126
  691. // Must be called without HEAD_LOCK held as it can deadlock
  692. // if any finalizer tries to acquire that lock.
  693. PyThreadState_Clear(p);
  694. HEAD_LOCK(runtime);
  695. p = p->next;
  696. HEAD_UNLOCK(runtime);
  697. }
  698. if (tstate->interp == interp) {
  699. /* We fix tstate->_status below when we for sure aren't using it
  700. (e.g. no longer need the GIL). */
  701. // XXX Eliminate the need to do this.
  702. tstate->_status.cleared = 0;
  703. }
  704. /* It is possible that any of the objects below have a finalizer
  705. that runs Python code or otherwise relies on a thread state
  706. or even the interpreter state. For now we trust that isn't
  707. a problem.
  708. */
  709. // XXX Make sure we properly deal with problematic finalizers.
  710. Py_CLEAR(interp->audit_hooks);
  711. for (int i = 0; i < _PY_MONITORING_UNGROUPED_EVENTS; i++) {
  712. interp->monitors.tools[i] = 0;
  713. }
  714. for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
  715. for (int e = 0; e < _PY_MONITORING_EVENTS; e++) {
  716. Py_CLEAR(interp->monitoring_callables[t][e]);
  717. }
  718. }
  719. interp->sys_profile_initialized = false;
  720. interp->sys_trace_initialized = false;
  721. for (int t = 0; t < PY_MONITORING_TOOL_IDS; t++) {
  722. Py_CLEAR(interp->monitoring_tool_names[t]);
  723. }
  724. PyConfig_Clear(&interp->config);
  725. Py_CLEAR(interp->codec_search_path);
  726. Py_CLEAR(interp->codec_search_cache);
  727. Py_CLEAR(interp->codec_error_registry);
  728. assert(interp->imports.modules == NULL);
  729. assert(interp->imports.modules_by_index == NULL);
  730. assert(interp->imports.importlib == NULL);
  731. assert(interp->imports.import_func == NULL);
  732. Py_CLEAR(interp->sysdict_copy);
  733. Py_CLEAR(interp->builtins_copy);
  734. Py_CLEAR(interp->dict);
  735. #ifdef HAVE_FORK
  736. Py_CLEAR(interp->before_forkers);
  737. Py_CLEAR(interp->after_forkers_parent);
  738. Py_CLEAR(interp->after_forkers_child);
  739. #endif
  740. _PyAST_Fini(interp);
  741. _PyWarnings_Fini(interp);
  742. _PyAtExit_Fini(interp);
  743. // All Python types must be destroyed before the last GC collection. Python
  744. // types create a reference cycle to themselves in their in their
  745. // PyTypeObject.tp_mro member (the tuple contains the type).
  746. /* Last garbage collection on this interpreter */
  747. _PyGC_CollectNoFail(tstate);
  748. _PyGC_Fini(interp);
  749. /* We don't clear sysdict and builtins until the end of this function.
  750. Because clearing other attributes can execute arbitrary Python code
  751. which requires sysdict and builtins. */
  752. PyDict_Clear(interp->sysdict);
  753. PyDict_Clear(interp->builtins);
  754. Py_CLEAR(interp->sysdict);
  755. Py_CLEAR(interp->builtins);
  756. Py_CLEAR(interp->interpreter_trampoline);
  757. _xidregistry_clear(&interp->xidregistry);
  758. /* The lock is owned by the runtime, so we don't free it here. */
  759. interp->xidregistry.mutex = NULL;
  760. if (tstate->interp == interp) {
  761. /* We are now safe to fix tstate->_status.cleared. */
  762. // XXX Do this (much) earlier?
  763. tstate->_status.cleared = 1;
  764. }
  765. for (int i=0; i < DICT_MAX_WATCHERS; i++) {
  766. interp->dict_state.watchers[i] = NULL;
  767. }
  768. for (int i=0; i < TYPE_MAX_WATCHERS; i++) {
  769. interp->type_watchers[i] = NULL;
  770. }
  771. for (int i=0; i < FUNC_MAX_WATCHERS; i++) {
  772. interp->func_watchers[i] = NULL;
  773. }
  774. interp->active_func_watchers = 0;
  775. for (int i=0; i < CODE_MAX_WATCHERS; i++) {
  776. interp->code_watchers[i] = NULL;
  777. }
  778. interp->active_code_watchers = 0;
  779. interp->f_opcode_trace_set = false;
  780. // XXX Once we have one allocator per interpreter (i.e.
  781. // per-interpreter GC) we must ensure that all of the interpreter's
  782. // objects have been cleaned up at the point.
  783. }
  784. void
  785. PyInterpreterState_Clear(PyInterpreterState *interp)
  786. {
  787. // Use the current Python thread state to call audit hooks and to collect
  788. // garbage. It can be different than the current Python thread state
  789. // of 'interp'.
  790. PyThreadState *current_tstate = current_fast_get(interp->runtime);
  791. _PyImport_ClearCore(interp);
  792. interpreter_clear(interp, current_tstate);
  793. }
  794. void
  795. _PyInterpreterState_Clear(PyThreadState *tstate)
  796. {
  797. _PyImport_ClearCore(tstate->interp);
  798. interpreter_clear(tstate->interp, tstate);
  799. }
  800. static inline void tstate_deactivate(PyThreadState *tstate);
  801. static void zapthreads(PyInterpreterState *interp);
  802. void
  803. PyInterpreterState_Delete(PyInterpreterState *interp)
  804. {
  805. _PyRuntimeState *runtime = interp->runtime;
  806. struct pyinterpreters *interpreters = &runtime->interpreters;
  807. // XXX Clearing the "current" thread state should happen before
  808. // we start finalizing the interpreter (or the current thread state).
  809. PyThreadState *tcur = current_fast_get(runtime);
  810. if (tcur != NULL && interp == tcur->interp) {
  811. /* Unset current thread. After this, many C API calls become crashy. */
  812. current_fast_clear(runtime);
  813. tstate_deactivate(tcur);
  814. _PyEval_ReleaseLock(interp, NULL);
  815. }
  816. zapthreads(interp);
  817. _PyEval_FiniState(&interp->ceval);
  818. // XXX These two calls should be done at the end of clear_interpreter(),
  819. // but currently some objects get decref'ed after that.
  820. #ifdef Py_REF_DEBUG
  821. _PyInterpreterState_FinalizeRefTotal(interp);
  822. #endif
  823. _PyInterpreterState_FinalizeAllocatedBlocks(interp);
  824. HEAD_LOCK(runtime);
  825. PyInterpreterState **p;
  826. for (p = &interpreters->head; ; p = &(*p)->next) {
  827. if (*p == NULL) {
  828. Py_FatalError("NULL interpreter");
  829. }
  830. if (*p == interp) {
  831. break;
  832. }
  833. }
  834. if (interp->threads.head != NULL) {
  835. Py_FatalError("remaining threads");
  836. }
  837. *p = interp->next;
  838. if (interpreters->main == interp) {
  839. interpreters->main = NULL;
  840. if (interpreters->head != NULL) {
  841. Py_FatalError("remaining subinterpreters");
  842. }
  843. }
  844. HEAD_UNLOCK(runtime);
  845. if (interp->id_mutex != NULL) {
  846. PyThread_free_lock(interp->id_mutex);
  847. }
  848. free_interpreter(interp);
  849. }
  850. #ifdef HAVE_FORK
  851. /*
  852. * Delete all interpreter states except the main interpreter. If there
  853. * is a current interpreter state, it *must* be the main interpreter.
  854. */
  855. PyStatus
  856. _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
  857. {
  858. struct pyinterpreters *interpreters = &runtime->interpreters;
  859. PyThreadState *tstate = _PyThreadState_Swap(runtime, NULL);
  860. if (tstate != NULL && tstate->interp != interpreters->main) {
  861. return _PyStatus_ERR("not main interpreter");
  862. }
  863. HEAD_LOCK(runtime);
  864. PyInterpreterState *interp = interpreters->head;
  865. interpreters->head = NULL;
  866. while (interp != NULL) {
  867. if (interp == interpreters->main) {
  868. interpreters->main->next = NULL;
  869. interpreters->head = interp;
  870. interp = interp->next;
  871. continue;
  872. }
  873. // XXX Won't this fail since PyInterpreterState_Clear() requires
  874. // the "current" tstate to be set?
  875. PyInterpreterState_Clear(interp); // XXX must activate?
  876. zapthreads(interp);
  877. if (interp->id_mutex != NULL) {
  878. PyThread_free_lock(interp->id_mutex);
  879. }
  880. PyInterpreterState *prev_interp = interp;
  881. interp = interp->next;
  882. free_interpreter(prev_interp);
  883. }
  884. HEAD_UNLOCK(runtime);
  885. if (interpreters->head == NULL) {
  886. return _PyStatus_ERR("missing main interpreter");
  887. }
  888. _PyThreadState_Swap(runtime, tstate);
  889. return _PyStatus_OK();
  890. }
  891. #endif
  892. int
  893. _PyInterpreterState_SetRunningMain(PyInterpreterState *interp)
  894. {
  895. if (interp->threads_main != NULL) {
  896. PyErr_SetString(PyExc_RuntimeError,
  897. "interpreter already running");
  898. return -1;
  899. }
  900. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  901. _Py_EnsureTstateNotNULL(tstate);
  902. if (tstate->interp != interp) {
  903. PyErr_SetString(PyExc_RuntimeError,
  904. "current tstate has wrong interpreter");
  905. return -1;
  906. }
  907. interp->threads_main = tstate;
  908. return 0;
  909. }
  910. void
  911. _PyInterpreterState_SetNotRunningMain(PyInterpreterState *interp)
  912. {
  913. assert(interp->threads_main == current_fast_get(&_PyRuntime));
  914. interp->threads_main = NULL;
  915. }
  916. int
  917. _PyInterpreterState_IsRunningMain(PyInterpreterState *interp)
  918. {
  919. return (interp->threads_main != NULL);
  920. }
  921. //----------
  922. // accessors
  923. //----------
  924. int64_t
  925. PyInterpreterState_GetID(PyInterpreterState *interp)
  926. {
  927. if (interp == NULL) {
  928. PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
  929. return -1;
  930. }
  931. return interp->id;
  932. }
  933. int
  934. _PyInterpreterState_IDInitref(PyInterpreterState *interp)
  935. {
  936. if (interp->id_mutex != NULL) {
  937. return 0;
  938. }
  939. interp->id_mutex = PyThread_allocate_lock();
  940. if (interp->id_mutex == NULL) {
  941. PyErr_SetString(PyExc_RuntimeError,
  942. "failed to create init interpreter ID mutex");
  943. return -1;
  944. }
  945. interp->id_refcount = 0;
  946. return 0;
  947. }
  948. int
  949. _PyInterpreterState_IDIncref(PyInterpreterState *interp)
  950. {
  951. if (_PyInterpreterState_IDInitref(interp) < 0) {
  952. return -1;
  953. }
  954. PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
  955. interp->id_refcount += 1;
  956. PyThread_release_lock(interp->id_mutex);
  957. return 0;
  958. }
  959. void
  960. _PyInterpreterState_IDDecref(PyInterpreterState *interp)
  961. {
  962. assert(interp->id_mutex != NULL);
  963. _PyRuntimeState *runtime = interp->runtime;
  964. PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
  965. assert(interp->id_refcount != 0);
  966. interp->id_refcount -= 1;
  967. int64_t refcount = interp->id_refcount;
  968. PyThread_release_lock(interp->id_mutex);
  969. if (refcount == 0 && interp->requires_idref) {
  970. // XXX Using the "head" thread isn't strictly correct.
  971. PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
  972. // XXX Possible GILState issues?
  973. PyThreadState *save_tstate = _PyThreadState_Swap(runtime, tstate);
  974. Py_EndInterpreter(tstate);
  975. _PyThreadState_Swap(runtime, save_tstate);
  976. }
  977. }
  978. int
  979. _PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
  980. {
  981. return interp->requires_idref;
  982. }
  983. void
  984. _PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
  985. {
  986. interp->requires_idref = required ? 1 : 0;
  987. }
  988. PyObject *
  989. _PyInterpreterState_GetMainModule(PyInterpreterState *interp)
  990. {
  991. PyObject *modules = _PyImport_GetModules(interp);
  992. if (modules == NULL) {
  993. PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
  994. return NULL;
  995. }
  996. return PyMapping_GetItemString(modules, "__main__");
  997. }
  998. PyObject *
  999. PyInterpreterState_GetDict(PyInterpreterState *interp)
  1000. {
  1001. if (interp->dict == NULL) {
  1002. interp->dict = PyDict_New();
  1003. if (interp->dict == NULL) {
  1004. PyErr_Clear();
  1005. }
  1006. }
  1007. /* Returning NULL means no per-interpreter dict is available. */
  1008. return interp->dict;
  1009. }
  1010. //-----------------------------
  1011. // look up an interpreter state
  1012. //-----------------------------
  1013. /* Return the interpreter associated with the current OS thread.
  1014. The GIL must be held.
  1015. */
  1016. PyInterpreterState *
  1017. PyInterpreterState_Get(void)
  1018. {
  1019. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1020. _Py_EnsureTstateNotNULL(tstate);
  1021. PyInterpreterState *interp = tstate->interp;
  1022. if (interp == NULL) {
  1023. Py_FatalError("no current interpreter");
  1024. }
  1025. return interp;
  1026. }
  1027. static PyInterpreterState *
  1028. interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
  1029. {
  1030. PyInterpreterState *interp = runtime->interpreters.head;
  1031. while (interp != NULL) {
  1032. int64_t id = PyInterpreterState_GetID(interp);
  1033. if (id < 0) {
  1034. return NULL;
  1035. }
  1036. if (requested_id == id) {
  1037. return interp;
  1038. }
  1039. interp = PyInterpreterState_Next(interp);
  1040. }
  1041. return NULL;
  1042. }
  1043. /* Return the interpreter state with the given ID.
  1044. Fail with RuntimeError if the interpreter is not found. */
  1045. PyInterpreterState *
  1046. _PyInterpreterState_LookUpID(int64_t requested_id)
  1047. {
  1048. PyInterpreterState *interp = NULL;
  1049. if (requested_id >= 0) {
  1050. _PyRuntimeState *runtime = &_PyRuntime;
  1051. HEAD_LOCK(runtime);
  1052. interp = interp_look_up_id(runtime, requested_id);
  1053. HEAD_UNLOCK(runtime);
  1054. }
  1055. if (interp == NULL && !PyErr_Occurred()) {
  1056. PyErr_Format(PyExc_RuntimeError,
  1057. "unrecognized interpreter ID %lld", requested_id);
  1058. }
  1059. return interp;
  1060. }
  1061. /********************************/
  1062. /* the per-thread runtime state */
  1063. /********************************/
  1064. #ifndef NDEBUG
  1065. static inline int
  1066. tstate_is_alive(PyThreadState *tstate)
  1067. {
  1068. return (tstate->_status.initialized &&
  1069. !tstate->_status.finalized &&
  1070. !tstate->_status.cleared &&
  1071. !tstate->_status.finalizing);
  1072. }
  1073. #endif
  1074. //----------
  1075. // lifecycle
  1076. //----------
  1077. /* Minimum size of data stack chunk */
  1078. #define DATA_STACK_CHUNK_SIZE (16*1024)
  1079. static _PyStackChunk*
  1080. allocate_chunk(int size_in_bytes, _PyStackChunk* previous)
  1081. {
  1082. assert(size_in_bytes % sizeof(PyObject **) == 0);
  1083. _PyStackChunk *res = _PyObject_VirtualAlloc(size_in_bytes);
  1084. if (res == NULL) {
  1085. return NULL;
  1086. }
  1087. res->previous = previous;
  1088. res->size = size_in_bytes;
  1089. res->top = 0;
  1090. return res;
  1091. }
  1092. static PyThreadState *
  1093. alloc_threadstate(void)
  1094. {
  1095. return PyMem_RawCalloc(1, sizeof(PyThreadState));
  1096. }
  1097. static void
  1098. free_threadstate(PyThreadState *tstate)
  1099. {
  1100. // The initial thread state of the interpreter is allocated
  1101. // as part of the interpreter state so should not be freed.
  1102. if (tstate != &tstate->interp->_initial_thread) {
  1103. PyMem_RawFree(tstate);
  1104. }
  1105. }
  1106. /* Get the thread state to a minimal consistent state.
  1107. Further init happens in pylifecycle.c before it can be used.
  1108. All fields not initialized here are expected to be zeroed out,
  1109. e.g. by PyMem_RawCalloc() or memset(), or otherwise pre-initialized.
  1110. The interpreter state is not manipulated. Instead it is assumed that
  1111. the thread is getting added to the interpreter.
  1112. */
  1113. static void
  1114. init_threadstate(PyThreadState *tstate,
  1115. PyInterpreterState *interp, uint64_t id)
  1116. {
  1117. if (tstate->_status.initialized) {
  1118. Py_FatalError("thread state already initialized");
  1119. }
  1120. assert(interp != NULL);
  1121. tstate->interp = interp;
  1122. // next/prev are set in add_threadstate().
  1123. assert(tstate->next == NULL);
  1124. assert(tstate->prev == NULL);
  1125. assert(id > 0);
  1126. tstate->id = id;
  1127. // thread_id and native_thread_id are set in bind_tstate().
  1128. tstate->py_recursion_limit = interp->ceval.recursion_limit,
  1129. tstate->py_recursion_remaining = interp->ceval.recursion_limit,
  1130. tstate->c_recursion_remaining = C_RECURSION_LIMIT;
  1131. tstate->exc_info = &tstate->exc_state;
  1132. // PyGILState_Release must not try to delete this thread state.
  1133. // This is cleared when PyGILState_Ensure() creates the thread state.
  1134. tstate->gilstate_counter = 1;
  1135. tstate->cframe = &tstate->root_cframe;
  1136. tstate->datastack_chunk = NULL;
  1137. tstate->datastack_top = NULL;
  1138. tstate->datastack_limit = NULL;
  1139. tstate->what_event = -1;
  1140. tstate->_status.initialized = 1;
  1141. }
  1142. static void
  1143. add_threadstate(PyInterpreterState *interp, PyThreadState *tstate,
  1144. PyThreadState *next)
  1145. {
  1146. assert(interp->threads.head != tstate);
  1147. assert((next != NULL && tstate->id != 1) ||
  1148. (next == NULL && tstate->id == 1));
  1149. if (next != NULL) {
  1150. assert(next->prev == NULL || next->prev == tstate);
  1151. next->prev = tstate;
  1152. }
  1153. tstate->next = next;
  1154. assert(tstate->prev == NULL);
  1155. interp->threads.head = tstate;
  1156. }
  1157. static PyThreadState *
  1158. new_threadstate(PyInterpreterState *interp)
  1159. {
  1160. PyThreadState *tstate;
  1161. _PyRuntimeState *runtime = interp->runtime;
  1162. // We don't need to allocate a thread state for the main interpreter
  1163. // (the common case), but doing it later for the other case revealed a
  1164. // reentrancy problem (deadlock). So for now we always allocate before
  1165. // taking the interpreters lock. See GH-96071.
  1166. PyThreadState *new_tstate = alloc_threadstate();
  1167. int used_newtstate;
  1168. if (new_tstate == NULL) {
  1169. return NULL;
  1170. }
  1171. /* We serialize concurrent creation to protect global state. */
  1172. HEAD_LOCK(runtime);
  1173. interp->threads.next_unique_id += 1;
  1174. uint64_t id = interp->threads.next_unique_id;
  1175. // Allocate the thread state and add it to the interpreter.
  1176. PyThreadState *old_head = interp->threads.head;
  1177. if (old_head == NULL) {
  1178. // It's the interpreter's initial thread state.
  1179. assert(id == 1);
  1180. used_newtstate = 0;
  1181. tstate = &interp->_initial_thread;
  1182. }
  1183. else {
  1184. // Every valid interpreter must have at least one thread.
  1185. assert(id > 1);
  1186. assert(old_head->prev == NULL);
  1187. used_newtstate = 1;
  1188. tstate = new_tstate;
  1189. // Set to _PyThreadState_INIT.
  1190. memcpy(tstate,
  1191. &initial._main_interpreter._initial_thread,
  1192. sizeof(*tstate));
  1193. }
  1194. init_threadstate(tstate, interp, id);
  1195. add_threadstate(interp, tstate, old_head);
  1196. HEAD_UNLOCK(runtime);
  1197. if (!used_newtstate) {
  1198. // Must be called with lock unlocked to avoid re-entrancy deadlock.
  1199. PyMem_RawFree(new_tstate);
  1200. }
  1201. return tstate;
  1202. }
  1203. PyThreadState *
  1204. PyThreadState_New(PyInterpreterState *interp)
  1205. {
  1206. PyThreadState *tstate = new_threadstate(interp);
  1207. if (tstate) {
  1208. bind_tstate(tstate);
  1209. // This makes sure there's a gilstate tstate bound
  1210. // as soon as possible.
  1211. if (gilstate_tss_get(tstate->interp->runtime) == NULL) {
  1212. bind_gilstate_tstate(tstate);
  1213. }
  1214. }
  1215. return tstate;
  1216. }
  1217. // This must be followed by a call to _PyThreadState_Bind();
  1218. PyThreadState *
  1219. _PyThreadState_New(PyInterpreterState *interp)
  1220. {
  1221. return new_threadstate(interp);
  1222. }
  1223. // We keep this for stable ABI compabibility.
  1224. PyThreadState *
  1225. _PyThreadState_Prealloc(PyInterpreterState *interp)
  1226. {
  1227. return _PyThreadState_New(interp);
  1228. }
  1229. // We keep this around for (accidental) stable ABI compatibility.
  1230. // Realistically, no extensions are using it.
  1231. void
  1232. _PyThreadState_Init(PyThreadState *tstate)
  1233. {
  1234. Py_FatalError("_PyThreadState_Init() is for internal use only");
  1235. }
  1236. static void
  1237. clear_datastack(PyThreadState *tstate)
  1238. {
  1239. _PyStackChunk *chunk = tstate->datastack_chunk;
  1240. tstate->datastack_chunk = NULL;
  1241. while (chunk != NULL) {
  1242. _PyStackChunk *prev = chunk->previous;
  1243. _PyObject_VirtualFree(chunk, chunk->size);
  1244. chunk = prev;
  1245. }
  1246. }
  1247. void
  1248. PyThreadState_Clear(PyThreadState *tstate)
  1249. {
  1250. assert(tstate->_status.initialized && !tstate->_status.cleared);
  1251. // XXX assert(!tstate->_status.bound || tstate->_status.unbound);
  1252. tstate->_status.finalizing = 1; // just in case
  1253. /* XXX Conditions we need to enforce:
  1254. * the GIL must be held by the current thread
  1255. * current_fast_get()->interp must match tstate->interp
  1256. * for the main interpreter, current_fast_get() must be the main thread
  1257. */
  1258. int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
  1259. if (verbose && tstate->cframe->current_frame != NULL) {
  1260. /* bpo-20526: After the main thread calls
  1261. _PyInterpreterState_SetFinalizing() in Py_FinalizeEx()
  1262. (or in Py_EndInterpreter() for subinterpreters),
  1263. threads must exit when trying to take the GIL.
  1264. If a thread exit in the middle of _PyEval_EvalFrameDefault(),
  1265. tstate->frame is not reset to its previous value.
  1266. It is more likely with daemon threads, but it can happen
  1267. with regular threads if threading._shutdown() fails
  1268. (ex: interrupted by CTRL+C). */
  1269. fprintf(stderr,
  1270. "PyThreadState_Clear: warning: thread still has a frame\n");
  1271. }
  1272. /* At this point tstate shouldn't be used any more,
  1273. neither to run Python code nor for other uses.
  1274. This is tricky when current_fast_get() == tstate, in the same way
  1275. as noted in interpreter_clear() above. The below finalizers
  1276. can possibly run Python code or otherwise use the partially
  1277. cleared thread state. For now we trust that isn't a problem
  1278. in practice.
  1279. */
  1280. // XXX Deal with the possibility of problematic finalizers.
  1281. /* Don't clear tstate->pyframe: it is a borrowed reference */
  1282. Py_CLEAR(tstate->dict);
  1283. Py_CLEAR(tstate->async_exc);
  1284. Py_CLEAR(tstate->current_exception);
  1285. Py_CLEAR(tstate->exc_state.exc_value);
  1286. /* The stack of exception states should contain just this thread. */
  1287. if (verbose && tstate->exc_info != &tstate->exc_state) {
  1288. fprintf(stderr,
  1289. "PyThreadState_Clear: warning: thread still has a generator\n");
  1290. }
  1291. if (tstate->c_profilefunc != NULL) {
  1292. tstate->interp->sys_profiling_threads--;
  1293. tstate->c_profilefunc = NULL;
  1294. }
  1295. if (tstate->c_tracefunc != NULL) {
  1296. tstate->interp->sys_tracing_threads--;
  1297. tstate->c_tracefunc = NULL;
  1298. }
  1299. Py_CLEAR(tstate->c_profileobj);
  1300. Py_CLEAR(tstate->c_traceobj);
  1301. Py_CLEAR(tstate->async_gen_firstiter);
  1302. Py_CLEAR(tstate->async_gen_finalizer);
  1303. Py_CLEAR(tstate->context);
  1304. if (tstate->on_delete != NULL) {
  1305. tstate->on_delete(tstate->on_delete_data);
  1306. }
  1307. tstate->_status.cleared = 1;
  1308. // XXX Call _PyThreadStateSwap(runtime, NULL) here if "current".
  1309. // XXX Do it as early in the function as possible.
  1310. }
  1311. /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
  1312. static void
  1313. tstate_delete_common(PyThreadState *tstate)
  1314. {
  1315. assert(tstate->_status.cleared && !tstate->_status.finalized);
  1316. PyInterpreterState *interp = tstate->interp;
  1317. if (interp == NULL) {
  1318. Py_FatalError("NULL interpreter");
  1319. }
  1320. _PyRuntimeState *runtime = interp->runtime;
  1321. HEAD_LOCK(runtime);
  1322. if (tstate->prev) {
  1323. tstate->prev->next = tstate->next;
  1324. }
  1325. else {
  1326. interp->threads.head = tstate->next;
  1327. }
  1328. if (tstate->next) {
  1329. tstate->next->prev = tstate->prev;
  1330. }
  1331. HEAD_UNLOCK(runtime);
  1332. // XXX Unbind in PyThreadState_Clear(), or earlier
  1333. // (and assert not-equal here)?
  1334. if (tstate->_status.bound_gilstate) {
  1335. unbind_gilstate_tstate(tstate);
  1336. }
  1337. if (tstate->_status.bound) {
  1338. unbind_tstate(tstate);
  1339. }
  1340. // XXX Move to PyThreadState_Clear()?
  1341. clear_datastack(tstate);
  1342. tstate->_status.finalized = 1;
  1343. }
  1344. static void
  1345. zapthreads(PyInterpreterState *interp)
  1346. {
  1347. PyThreadState *tstate;
  1348. /* No need to lock the mutex here because this should only happen
  1349. when the threads are all really dead (XXX famous last words). */
  1350. while ((tstate = interp->threads.head) != NULL) {
  1351. tstate_verify_not_active(tstate);
  1352. tstate_delete_common(tstate);
  1353. free_threadstate(tstate);
  1354. }
  1355. }
  1356. void
  1357. PyThreadState_Delete(PyThreadState *tstate)
  1358. {
  1359. _Py_EnsureTstateNotNULL(tstate);
  1360. tstate_verify_not_active(tstate);
  1361. tstate_delete_common(tstate);
  1362. free_threadstate(tstate);
  1363. }
  1364. void
  1365. _PyThreadState_DeleteCurrent(PyThreadState *tstate)
  1366. {
  1367. _Py_EnsureTstateNotNULL(tstate);
  1368. tstate_delete_common(tstate);
  1369. current_fast_clear(tstate->interp->runtime);
  1370. _PyEval_ReleaseLock(tstate->interp, NULL);
  1371. free_threadstate(tstate);
  1372. }
  1373. void
  1374. PyThreadState_DeleteCurrent(void)
  1375. {
  1376. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1377. _PyThreadState_DeleteCurrent(tstate);
  1378. }
  1379. /*
  1380. * Delete all thread states except the one passed as argument.
  1381. * Note that, if there is a current thread state, it *must* be the one
  1382. * passed as argument. Also, this won't touch any other interpreters
  1383. * than the current one, since we don't know which thread state should
  1384. * be kept in those other interpreters.
  1385. */
  1386. void
  1387. _PyThreadState_DeleteExcept(PyThreadState *tstate)
  1388. {
  1389. assert(tstate != NULL);
  1390. PyInterpreterState *interp = tstate->interp;
  1391. _PyRuntimeState *runtime = interp->runtime;
  1392. HEAD_LOCK(runtime);
  1393. /* Remove all thread states, except tstate, from the linked list of
  1394. thread states. This will allow calling PyThreadState_Clear()
  1395. without holding the lock. */
  1396. PyThreadState *list = interp->threads.head;
  1397. if (list == tstate) {
  1398. list = tstate->next;
  1399. }
  1400. if (tstate->prev) {
  1401. tstate->prev->next = tstate->next;
  1402. }
  1403. if (tstate->next) {
  1404. tstate->next->prev = tstate->prev;
  1405. }
  1406. tstate->prev = tstate->next = NULL;
  1407. interp->threads.head = tstate;
  1408. HEAD_UNLOCK(runtime);
  1409. /* Clear and deallocate all stale thread states. Even if this
  1410. executes Python code, we should be safe since it executes
  1411. in the current thread, not one of the stale threads. */
  1412. PyThreadState *p, *next;
  1413. for (p = list; p; p = next) {
  1414. next = p->next;
  1415. PyThreadState_Clear(p);
  1416. free_threadstate(p);
  1417. }
  1418. }
  1419. //----------
  1420. // accessors
  1421. //----------
  1422. /* An extension mechanism to store arbitrary additional per-thread state.
  1423. PyThreadState_GetDict() returns a dictionary that can be used to hold such
  1424. state; the caller should pick a unique key and store its state there. If
  1425. PyThreadState_GetDict() returns NULL, an exception has *not* been raised
  1426. and the caller should assume no per-thread state is available. */
  1427. PyObject *
  1428. _PyThreadState_GetDict(PyThreadState *tstate)
  1429. {
  1430. assert(tstate != NULL);
  1431. if (tstate->dict == NULL) {
  1432. tstate->dict = PyDict_New();
  1433. if (tstate->dict == NULL) {
  1434. _PyErr_Clear(tstate);
  1435. }
  1436. }
  1437. return tstate->dict;
  1438. }
  1439. PyObject *
  1440. PyThreadState_GetDict(void)
  1441. {
  1442. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1443. if (tstate == NULL) {
  1444. return NULL;
  1445. }
  1446. return _PyThreadState_GetDict(tstate);
  1447. }
  1448. PyInterpreterState *
  1449. PyThreadState_GetInterpreter(PyThreadState *tstate)
  1450. {
  1451. assert(tstate != NULL);
  1452. return tstate->interp;
  1453. }
  1454. PyFrameObject*
  1455. PyThreadState_GetFrame(PyThreadState *tstate)
  1456. {
  1457. assert(tstate != NULL);
  1458. _PyInterpreterFrame *f = _PyThreadState_GetFrame(tstate);
  1459. if (f == NULL) {
  1460. return NULL;
  1461. }
  1462. PyFrameObject *frame = _PyFrame_GetFrameObject(f);
  1463. if (frame == NULL) {
  1464. PyErr_Clear();
  1465. }
  1466. return (PyFrameObject*)Py_XNewRef(frame);
  1467. }
  1468. uint64_t
  1469. PyThreadState_GetID(PyThreadState *tstate)
  1470. {
  1471. assert(tstate != NULL);
  1472. return tstate->id;
  1473. }
  1474. static inline void
  1475. tstate_activate(PyThreadState *tstate)
  1476. {
  1477. assert(tstate != NULL);
  1478. // XXX assert(tstate_is_alive(tstate));
  1479. assert(tstate_is_bound(tstate));
  1480. assert(!tstate->_status.active);
  1481. assert(!tstate->_status.bound_gilstate ||
  1482. tstate == gilstate_tss_get((tstate->interp->runtime)));
  1483. if (!tstate->_status.bound_gilstate) {
  1484. bind_gilstate_tstate(tstate);
  1485. }
  1486. tstate->_status.active = 1;
  1487. }
  1488. static inline void
  1489. tstate_deactivate(PyThreadState *tstate)
  1490. {
  1491. assert(tstate != NULL);
  1492. // XXX assert(tstate_is_alive(tstate));
  1493. assert(tstate_is_bound(tstate));
  1494. assert(tstate->_status.active);
  1495. tstate->_status.active = 0;
  1496. // We do not unbind the gilstate tstate here.
  1497. // It will still be used in PyGILState_Ensure().
  1498. }
  1499. //----------
  1500. // other API
  1501. //----------
  1502. /* Asynchronously raise an exception in a thread.
  1503. Requested by Just van Rossum and Alex Martelli.
  1504. To prevent naive misuse, you must write your own extension
  1505. to call this, or use ctypes. Must be called with the GIL held.
  1506. Returns the number of tstates modified (normally 1, but 0 if `id` didn't
  1507. match any known thread id). Can be called with exc=NULL to clear an
  1508. existing async exception. This raises no exceptions. */
  1509. // XXX Move this to Python/ceval_gil.c?
  1510. // XXX Deprecate this.
  1511. int
  1512. PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
  1513. {
  1514. _PyRuntimeState *runtime = &_PyRuntime;
  1515. PyInterpreterState *interp = _PyInterpreterState_GET();
  1516. /* Although the GIL is held, a few C API functions can be called
  1517. * without the GIL held, and in particular some that create and
  1518. * destroy thread and interpreter states. Those can mutate the
  1519. * list of thread states we're traversing, so to prevent that we lock
  1520. * head_mutex for the duration.
  1521. */
  1522. HEAD_LOCK(runtime);
  1523. for (PyThreadState *tstate = interp->threads.head; tstate != NULL; tstate = tstate->next) {
  1524. if (tstate->thread_id != id) {
  1525. continue;
  1526. }
  1527. /* Tricky: we need to decref the current value
  1528. * (if any) in tstate->async_exc, but that can in turn
  1529. * allow arbitrary Python code to run, including
  1530. * perhaps calls to this function. To prevent
  1531. * deadlock, we need to release head_mutex before
  1532. * the decref.
  1533. */
  1534. PyObject *old_exc = tstate->async_exc;
  1535. tstate->async_exc = Py_XNewRef(exc);
  1536. HEAD_UNLOCK(runtime);
  1537. Py_XDECREF(old_exc);
  1538. _PyEval_SignalAsyncExc(tstate->interp);
  1539. return 1;
  1540. }
  1541. HEAD_UNLOCK(runtime);
  1542. return 0;
  1543. }
  1544. //---------------------------------
  1545. // API for the current thread state
  1546. //---------------------------------
  1547. PyThreadState *
  1548. _PyThreadState_UncheckedGet(void)
  1549. {
  1550. return current_fast_get(&_PyRuntime);
  1551. }
  1552. PyThreadState *
  1553. PyThreadState_Get(void)
  1554. {
  1555. PyThreadState *tstate = current_fast_get(&_PyRuntime);
  1556. _Py_EnsureTstateNotNULL(tstate);
  1557. return tstate;
  1558. }
  1559. static void
  1560. _swap_thread_states(_PyRuntimeState *runtime,
  1561. PyThreadState *oldts, PyThreadState *newts)
  1562. {
  1563. // XXX Do this only if oldts != NULL?
  1564. current_fast_clear(runtime);
  1565. if (oldts != NULL) {
  1566. // XXX assert(tstate_is_alive(oldts) && tstate_is_bound(oldts));
  1567. tstate_deactivate(oldts);
  1568. }
  1569. if (newts != NULL) {
  1570. // XXX assert(tstate_is_alive(newts));
  1571. assert(tstate_is_bound(newts));
  1572. current_fast_set(runtime, newts);
  1573. tstate_activate(newts);
  1574. }
  1575. }
  1576. PyThreadState *
  1577. _PyThreadState_SwapNoGIL(PyThreadState *newts)
  1578. {
  1579. #if defined(Py_DEBUG)
  1580. /* This can be called from PyEval_RestoreThread(). Similar
  1581. to it, we need to ensure errno doesn't change.
  1582. */
  1583. int err = errno;
  1584. #endif
  1585. PyThreadState *oldts = current_fast_get(&_PyRuntime);
  1586. _swap_thread_states(&_PyRuntime, oldts, newts);
  1587. #if defined(Py_DEBUG)
  1588. errno = err;
  1589. #endif
  1590. return oldts;
  1591. }
  1592. PyThreadState *
  1593. _PyThreadState_Swap(_PyRuntimeState *runtime, PyThreadState *newts)
  1594. {
  1595. PyThreadState *oldts = current_fast_get(runtime);
  1596. if (oldts != NULL) {
  1597. _PyEval_ReleaseLock(oldts->interp, oldts);
  1598. }
  1599. _swap_thread_states(runtime, oldts, newts);
  1600. if (newts != NULL) {
  1601. _PyEval_AcquireLock(newts);
  1602. }
  1603. return oldts;
  1604. }
  1605. PyThreadState *
  1606. PyThreadState_Swap(PyThreadState *newts)
  1607. {
  1608. return _PyThreadState_Swap(&_PyRuntime, newts);
  1609. }
  1610. void
  1611. _PyThreadState_Bind(PyThreadState *tstate)
  1612. {
  1613. // gh-104690: If Python is being finalized and PyInterpreterState_Delete()
  1614. // was called, tstate becomes a dangling pointer.
  1615. assert(_PyThreadState_CheckConsistency(tstate));
  1616. bind_tstate(tstate);
  1617. // This makes sure there's a gilstate tstate bound
  1618. // as soon as possible.
  1619. if (gilstate_tss_get(tstate->interp->runtime) == NULL) {
  1620. bind_gilstate_tstate(tstate);
  1621. }
  1622. }
  1623. /***********************************/
  1624. /* routines for advanced debuggers */
  1625. /***********************************/
  1626. // (requested by David Beazley)
  1627. // Don't use unless you know what you are doing!
  1628. PyInterpreterState *
  1629. PyInterpreterState_Head(void)
  1630. {
  1631. return _PyRuntime.interpreters.head;
  1632. }
  1633. PyInterpreterState *
  1634. PyInterpreterState_Main(void)
  1635. {
  1636. return _PyInterpreterState_Main();
  1637. }
  1638. PyInterpreterState *
  1639. PyInterpreterState_Next(PyInterpreterState *interp) {
  1640. return interp->next;
  1641. }
  1642. PyThreadState *
  1643. PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
  1644. return interp->threads.head;
  1645. }
  1646. PyThreadState *
  1647. PyThreadState_Next(PyThreadState *tstate) {
  1648. return tstate->next;
  1649. }
  1650. /********************************************/
  1651. /* reporting execution state of all threads */
  1652. /********************************************/
  1653. /* The implementation of sys._current_frames(). This is intended to be
  1654. called with the GIL held, as it will be when called via
  1655. sys._current_frames(). It's possible it would work fine even without
  1656. the GIL held, but haven't thought enough about that.
  1657. */
  1658. PyObject *
  1659. _PyThread_CurrentFrames(void)
  1660. {
  1661. _PyRuntimeState *runtime = &_PyRuntime;
  1662. PyThreadState *tstate = current_fast_get(runtime);
  1663. if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
  1664. return NULL;
  1665. }
  1666. PyObject *result = PyDict_New();
  1667. if (result == NULL) {
  1668. return NULL;
  1669. }
  1670. /* for i in all interpreters:
  1671. * for t in all of i's thread states:
  1672. * if t's frame isn't NULL, map t's id to its frame
  1673. * Because these lists can mutate even when the GIL is held, we
  1674. * need to grab head_mutex for the duration.
  1675. */
  1676. HEAD_LOCK(runtime);
  1677. PyInterpreterState *i;
  1678. for (i = runtime->interpreters.head; i != NULL; i = i->next) {
  1679. PyThreadState *t;
  1680. for (t = i->threads.head; t != NULL; t = t->next) {
  1681. _PyInterpreterFrame *frame = t->cframe->current_frame;
  1682. frame = _PyFrame_GetFirstComplete(frame);
  1683. if (frame == NULL) {
  1684. continue;
  1685. }
  1686. PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
  1687. if (id == NULL) {
  1688. goto fail;
  1689. }
  1690. PyObject *frameobj = (PyObject *)_PyFrame_GetFrameObject(frame);
  1691. if (frameobj == NULL) {
  1692. Py_DECREF(id);
  1693. goto fail;
  1694. }
  1695. int stat = PyDict_SetItem(result, id, frameobj);
  1696. Py_DECREF(id);
  1697. if (stat < 0) {
  1698. goto fail;
  1699. }
  1700. }
  1701. }
  1702. goto done;
  1703. fail:
  1704. Py_CLEAR(result);
  1705. done:
  1706. HEAD_UNLOCK(runtime);
  1707. return result;
  1708. }
  1709. /* The implementation of sys._current_exceptions(). This is intended to be
  1710. called with the GIL held, as it will be when called via
  1711. sys._current_exceptions(). It's possible it would work fine even without
  1712. the GIL held, but haven't thought enough about that.
  1713. */
  1714. PyObject *
  1715. _PyThread_CurrentExceptions(void)
  1716. {
  1717. _PyRuntimeState *runtime = &_PyRuntime;
  1718. PyThreadState *tstate = current_fast_get(runtime);
  1719. _Py_EnsureTstateNotNULL(tstate);
  1720. if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
  1721. return NULL;
  1722. }
  1723. PyObject *result = PyDict_New();
  1724. if (result == NULL) {
  1725. return NULL;
  1726. }
  1727. /* for i in all interpreters:
  1728. * for t in all of i's thread states:
  1729. * if t's frame isn't NULL, map t's id to its frame
  1730. * Because these lists can mutate even when the GIL is held, we
  1731. * need to grab head_mutex for the duration.
  1732. */
  1733. HEAD_LOCK(runtime);
  1734. PyInterpreterState *i;
  1735. for (i = runtime->interpreters.head; i != NULL; i = i->next) {
  1736. PyThreadState *t;
  1737. for (t = i->threads.head; t != NULL; t = t->next) {
  1738. _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
  1739. if (err_info == NULL) {
  1740. continue;
  1741. }
  1742. PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
  1743. if (id == NULL) {
  1744. goto fail;
  1745. }
  1746. PyObject *exc = err_info->exc_value;
  1747. assert(exc == NULL ||
  1748. exc == Py_None ||
  1749. PyExceptionInstance_Check(exc));
  1750. int stat = PyDict_SetItem(result, id, exc == NULL ? Py_None : exc);
  1751. Py_DECREF(id);
  1752. if (stat < 0) {
  1753. goto fail;
  1754. }
  1755. }
  1756. }
  1757. goto done;
  1758. fail:
  1759. Py_CLEAR(result);
  1760. done:
  1761. HEAD_UNLOCK(runtime);
  1762. return result;
  1763. }
  1764. /***********************************/
  1765. /* Python "auto thread state" API. */
  1766. /***********************************/
  1767. /* Internal initialization/finalization functions called by
  1768. Py_Initialize/Py_FinalizeEx
  1769. */
  1770. PyStatus
  1771. _PyGILState_Init(PyInterpreterState *interp)
  1772. {
  1773. if (!_Py_IsMainInterpreter(interp)) {
  1774. /* Currently, PyGILState is shared by all interpreters. The main
  1775. * interpreter is responsible to initialize it. */
  1776. return _PyStatus_OK();
  1777. }
  1778. _PyRuntimeState *runtime = interp->runtime;
  1779. assert(gilstate_tss_get(runtime) == NULL);
  1780. assert(runtime->gilstate.autoInterpreterState == NULL);
  1781. runtime->gilstate.autoInterpreterState = interp;
  1782. return _PyStatus_OK();
  1783. }
  1784. void
  1785. _PyGILState_Fini(PyInterpreterState *interp)
  1786. {
  1787. if (!_Py_IsMainInterpreter(interp)) {
  1788. /* Currently, PyGILState is shared by all interpreters. The main
  1789. * interpreter is responsible to initialize it. */
  1790. return;
  1791. }
  1792. interp->runtime->gilstate.autoInterpreterState = NULL;
  1793. }
  1794. // XXX Drop this.
  1795. PyStatus
  1796. _PyGILState_SetTstate(PyThreadState *tstate)
  1797. {
  1798. /* must init with valid states */
  1799. assert(tstate != NULL);
  1800. assert(tstate->interp != NULL);
  1801. if (!_Py_IsMainInterpreter(tstate->interp)) {
  1802. /* Currently, PyGILState is shared by all interpreters. The main
  1803. * interpreter is responsible to initialize it. */
  1804. return _PyStatus_OK();
  1805. }
  1806. #ifndef NDEBUG
  1807. _PyRuntimeState *runtime = tstate->interp->runtime;
  1808. assert(runtime->gilstate.autoInterpreterState == tstate->interp);
  1809. assert(gilstate_tss_get(runtime) == tstate);
  1810. assert(tstate->gilstate_counter == 1);
  1811. #endif
  1812. return _PyStatus_OK();
  1813. }
  1814. PyInterpreterState *
  1815. _PyGILState_GetInterpreterStateUnsafe(void)
  1816. {
  1817. return _PyRuntime.gilstate.autoInterpreterState;
  1818. }
  1819. /* The public functions */
  1820. PyThreadState *
  1821. PyGILState_GetThisThreadState(void)
  1822. {
  1823. _PyRuntimeState *runtime = &_PyRuntime;
  1824. if (!gilstate_tss_initialized(runtime)) {
  1825. return NULL;
  1826. }
  1827. return gilstate_tss_get(runtime);
  1828. }
  1829. int
  1830. PyGILState_Check(void)
  1831. {
  1832. _PyRuntimeState *runtime = &_PyRuntime;
  1833. if (!runtime->gilstate.check_enabled) {
  1834. return 1;
  1835. }
  1836. if (!gilstate_tss_initialized(runtime)) {
  1837. return 1;
  1838. }
  1839. PyThreadState *tstate = current_fast_get(runtime);
  1840. if (tstate == NULL) {
  1841. return 0;
  1842. }
  1843. return (tstate == gilstate_tss_get(runtime));
  1844. }
  1845. PyGILState_STATE
  1846. PyGILState_Ensure(void)
  1847. {
  1848. _PyRuntimeState *runtime = &_PyRuntime;
  1849. /* Note that we do not auto-init Python here - apart from
  1850. potential races with 2 threads auto-initializing, pep-311
  1851. spells out other issues. Embedders are expected to have
  1852. called Py_Initialize(). */
  1853. /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
  1854. called by Py_Initialize() */
  1855. assert(_PyEval_ThreadsInitialized());
  1856. assert(gilstate_tss_initialized(runtime));
  1857. assert(runtime->gilstate.autoInterpreterState != NULL);
  1858. PyThreadState *tcur = gilstate_tss_get(runtime);
  1859. int has_gil;
  1860. if (tcur == NULL) {
  1861. /* Create a new Python thread state for this thread */
  1862. tcur = new_threadstate(runtime->gilstate.autoInterpreterState);
  1863. if (tcur == NULL) {
  1864. Py_FatalError("Couldn't create thread-state for new thread");
  1865. }
  1866. bind_tstate(tcur);
  1867. bind_gilstate_tstate(tcur);
  1868. /* This is our thread state! We'll need to delete it in the
  1869. matching call to PyGILState_Release(). */
  1870. assert(tcur->gilstate_counter == 1);
  1871. tcur->gilstate_counter = 0;
  1872. has_gil = 0; /* new thread state is never current */
  1873. }
  1874. else {
  1875. has_gil = holds_gil(tcur);
  1876. }
  1877. if (!has_gil) {
  1878. PyEval_RestoreThread(tcur);
  1879. }
  1880. /* Update our counter in the thread-state - no need for locks:
  1881. - tcur will remain valid as we hold the GIL.
  1882. - the counter is safe as we are the only thread "allowed"
  1883. to modify this value
  1884. */
  1885. ++tcur->gilstate_counter;
  1886. return has_gil ? PyGILState_LOCKED : PyGILState_UNLOCKED;
  1887. }
  1888. void
  1889. PyGILState_Release(PyGILState_STATE oldstate)
  1890. {
  1891. _PyRuntimeState *runtime = &_PyRuntime;
  1892. PyThreadState *tstate = gilstate_tss_get(runtime);
  1893. if (tstate == NULL) {
  1894. Py_FatalError("auto-releasing thread-state, "
  1895. "but no thread-state for this thread");
  1896. }
  1897. /* We must hold the GIL and have our thread state current */
  1898. /* XXX - remove the check - the assert should be fine,
  1899. but while this is very new (April 2003), the extra check
  1900. by release-only users can't hurt.
  1901. */
  1902. if (!holds_gil(tstate)) {
  1903. _Py_FatalErrorFormat(__func__,
  1904. "thread state %p must be current when releasing",
  1905. tstate);
  1906. }
  1907. assert(holds_gil(tstate));
  1908. --tstate->gilstate_counter;
  1909. assert(tstate->gilstate_counter >= 0); /* illegal counter value */
  1910. /* If we're going to destroy this thread-state, we must
  1911. * clear it while the GIL is held, as destructors may run.
  1912. */
  1913. if (tstate->gilstate_counter == 0) {
  1914. /* can't have been locked when we created it */
  1915. assert(oldstate == PyGILState_UNLOCKED);
  1916. // XXX Unbind tstate here.
  1917. // gh-119585: `PyThreadState_Clear()` may call destructors that
  1918. // themselves use PyGILState_Ensure and PyGILState_Release, so make
  1919. // sure that gilstate_counter is not zero when calling it.
  1920. ++tstate->gilstate_counter;
  1921. PyThreadState_Clear(tstate);
  1922. --tstate->gilstate_counter;
  1923. /* Delete the thread-state. Note this releases the GIL too!
  1924. * It's vital that the GIL be held here, to avoid shutdown
  1925. * races; see bugs 225673 and 1061968 (that nasty bug has a
  1926. * habit of coming back).
  1927. */
  1928. assert(tstate->gilstate_counter == 0);
  1929. assert(current_fast_get(runtime) == tstate);
  1930. _PyThreadState_DeleteCurrent(tstate);
  1931. }
  1932. /* Release the lock if necessary */
  1933. else if (oldstate == PyGILState_UNLOCKED) {
  1934. PyEval_SaveThread();
  1935. }
  1936. }
  1937. /**************************/
  1938. /* cross-interpreter data */
  1939. /**************************/
  1940. /* cross-interpreter data */
  1941. static inline void
  1942. _xidata_init(_PyCrossInterpreterData *data)
  1943. {
  1944. // If the value is being reused
  1945. // then _xidata_clear() should have been called already.
  1946. assert(data->data == NULL);
  1947. assert(data->obj == NULL);
  1948. *data = (_PyCrossInterpreterData){0};
  1949. data->interp = -1;
  1950. }
  1951. static inline void
  1952. _xidata_clear(_PyCrossInterpreterData *data)
  1953. {
  1954. // _PyCrossInterpreterData only has two members that need to be
  1955. // cleaned up, if set: "data" must be freed and "obj" must be decref'ed.
  1956. // In both cases the original (owning) interpreter must be used,
  1957. // which is the caller's responsibility to ensure.
  1958. if (data->data != NULL) {
  1959. if (data->free != NULL) {
  1960. data->free(data->data);
  1961. }
  1962. data->data = NULL;
  1963. }
  1964. Py_CLEAR(data->obj);
  1965. }
  1966. void
  1967. _PyCrossInterpreterData_Init(_PyCrossInterpreterData *data,
  1968. PyInterpreterState *interp,
  1969. void *shared, PyObject *obj,
  1970. xid_newobjectfunc new_object)
  1971. {
  1972. assert(data != NULL);
  1973. assert(new_object != NULL);
  1974. _xidata_init(data);
  1975. data->data = shared;
  1976. if (obj != NULL) {
  1977. assert(interp != NULL);
  1978. // released in _PyCrossInterpreterData_Clear()
  1979. data->obj = Py_NewRef(obj);
  1980. }
  1981. // Ideally every object would know its owning interpreter.
  1982. // Until then, we have to rely on the caller to identify it
  1983. // (but we don't need it in all cases).
  1984. data->interp = (interp != NULL) ? interp->id : -1;
  1985. data->new_object = new_object;
  1986. }
  1987. int
  1988. _PyCrossInterpreterData_InitWithSize(_PyCrossInterpreterData *data,
  1989. PyInterpreterState *interp,
  1990. const size_t size, PyObject *obj,
  1991. xid_newobjectfunc new_object)
  1992. {
  1993. assert(size > 0);
  1994. // For now we always free the shared data in the same interpreter
  1995. // where it was allocated, so the interpreter is required.
  1996. assert(interp != NULL);
  1997. _PyCrossInterpreterData_Init(data, interp, NULL, obj, new_object);
  1998. data->data = PyMem_RawMalloc(size);
  1999. if (data->data == NULL) {
  2000. return -1;
  2001. }
  2002. data->free = PyMem_RawFree;
  2003. return 0;
  2004. }
  2005. void
  2006. _PyCrossInterpreterData_Clear(PyInterpreterState *interp,
  2007. _PyCrossInterpreterData *data)
  2008. {
  2009. assert(data != NULL);
  2010. // This must be called in the owning interpreter.
  2011. assert(interp == NULL || data->interp == interp->id);
  2012. _xidata_clear(data);
  2013. }
  2014. static int
  2015. _check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
  2016. {
  2017. // data->data can be anything, including NULL, so we don't check it.
  2018. // data->obj may be NULL, so we don't check it.
  2019. if (data->interp < 0) {
  2020. _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
  2021. return -1;
  2022. }
  2023. if (data->new_object == NULL) {
  2024. _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
  2025. return -1;
  2026. }
  2027. // data->free may be NULL, so we don't check it.
  2028. return 0;
  2029. }
  2030. crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
  2031. /* This is a separate func from _PyCrossInterpreterData_Lookup in order
  2032. to keep the registry code separate. */
  2033. static crossinterpdatafunc
  2034. _lookup_getdata(PyObject *obj)
  2035. {
  2036. crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
  2037. if (getdata == NULL && PyErr_Occurred() == 0)
  2038. PyErr_Format(PyExc_ValueError,
  2039. "%S does not support cross-interpreter data", obj);
  2040. return getdata;
  2041. }
  2042. int
  2043. _PyObject_CheckCrossInterpreterData(PyObject *obj)
  2044. {
  2045. crossinterpdatafunc getdata = _lookup_getdata(obj);
  2046. if (getdata == NULL) {
  2047. return -1;
  2048. }
  2049. return 0;
  2050. }
  2051. int
  2052. _PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
  2053. {
  2054. _PyRuntimeState *runtime = &_PyRuntime;
  2055. PyThreadState *tstate = current_fast_get(runtime);
  2056. #ifdef Py_DEBUG
  2057. // The caller must hold the GIL
  2058. _Py_EnsureTstateNotNULL(tstate);
  2059. #endif
  2060. PyInterpreterState *interp = tstate->interp;
  2061. // Reset data before re-populating.
  2062. *data = (_PyCrossInterpreterData){0};
  2063. data->interp = -1;
  2064. // Call the "getdata" func for the object.
  2065. Py_INCREF(obj);
  2066. crossinterpdatafunc getdata = _lookup_getdata(obj);
  2067. if (getdata == NULL) {
  2068. Py_DECREF(obj);
  2069. return -1;
  2070. }
  2071. int res = getdata(tstate, obj, data);
  2072. Py_DECREF(obj);
  2073. if (res != 0) {
  2074. return -1;
  2075. }
  2076. // Fill in the blanks and validate the result.
  2077. data->interp = interp->id;
  2078. if (_check_xidata(tstate, data) != 0) {
  2079. (void)_PyCrossInterpreterData_Release(data);
  2080. return -1;
  2081. }
  2082. return 0;
  2083. }
  2084. PyObject *
  2085. _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
  2086. {
  2087. return data->new_object(data);
  2088. }
  2089. static int
  2090. _release_xidata_pending(void *data)
  2091. {
  2092. _xidata_clear((_PyCrossInterpreterData *)data);
  2093. return 0;
  2094. }
  2095. static int
  2096. _xidata_release_and_rawfree_pending(void *data)
  2097. {
  2098. _xidata_clear((_PyCrossInterpreterData *)data);
  2099. PyMem_RawFree(data);
  2100. return 0;
  2101. }
  2102. static int
  2103. _xidata_release(_PyCrossInterpreterData *data, int rawfree)
  2104. {
  2105. if ((data->data == NULL || data->free == NULL) && data->obj == NULL) {
  2106. // Nothing to release!
  2107. if (rawfree) {
  2108. PyMem_RawFree(data);
  2109. }
  2110. else {
  2111. data->data = NULL;
  2112. }
  2113. return 0;
  2114. }
  2115. // Switch to the original interpreter.
  2116. PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
  2117. if (interp == NULL) {
  2118. // The interpreter was already destroyed.
  2119. // This function shouldn't have been called.
  2120. // XXX Someone leaked some memory...
  2121. assert(PyErr_Occurred());
  2122. if (rawfree) {
  2123. PyMem_RawFree(data);
  2124. }
  2125. return -1;
  2126. }
  2127. // "Release" the data and/or the object.
  2128. if (interp == current_fast_get(interp->runtime)->interp) {
  2129. _xidata_clear(data);
  2130. if (rawfree) {
  2131. PyMem_RawFree(data);
  2132. }
  2133. }
  2134. else {
  2135. int (*func)(void *) = _release_xidata_pending;
  2136. if (rawfree) {
  2137. func = _xidata_release_and_rawfree_pending;
  2138. }
  2139. // XXX Emit a warning if this fails?
  2140. _PyEval_AddPendingCall(interp, func, data, 0);
  2141. }
  2142. return 0;
  2143. }
  2144. int
  2145. _PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
  2146. {
  2147. return _xidata_release(data, 0);
  2148. }
  2149. int
  2150. _PyCrossInterpreterData_ReleaseAndRawFree(_PyCrossInterpreterData *data)
  2151. {
  2152. return _xidata_release(data, 1);
  2153. }
  2154. /* registry of {type -> crossinterpdatafunc} */
  2155. /* For now we use a global registry of shareable classes. An
  2156. alternative would be to add a tp_* slot for a class's
  2157. crossinterpdatafunc. It would be simpler and more efficient. */
  2158. static int
  2159. _xidregistry_add_type(struct _xidregistry *xidregistry,
  2160. PyTypeObject *cls, crossinterpdatafunc getdata)
  2161. {
  2162. struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
  2163. if (newhead == NULL) {
  2164. return -1;
  2165. }
  2166. *newhead = (struct _xidregitem){
  2167. // We do not keep a reference, to avoid keeping the class alive.
  2168. .cls = cls,
  2169. .refcount = 1,
  2170. .getdata = getdata,
  2171. };
  2172. if (cls->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  2173. // XXX Assign a callback to clear the entry from the registry?
  2174. newhead->weakref = PyWeakref_NewRef((PyObject *)cls, NULL);
  2175. if (newhead->weakref == NULL) {
  2176. PyMem_RawFree(newhead);
  2177. return -1;
  2178. }
  2179. }
  2180. newhead->next = xidregistry->head;
  2181. if (newhead->next != NULL) {
  2182. newhead->next->prev = newhead;
  2183. }
  2184. xidregistry->head = newhead;
  2185. return 0;
  2186. }
  2187. static struct _xidregitem *
  2188. _xidregistry_remove_entry(struct _xidregistry *xidregistry,
  2189. struct _xidregitem *entry)
  2190. {
  2191. struct _xidregitem *next = entry->next;
  2192. if (entry->prev != NULL) {
  2193. assert(entry->prev->next == entry);
  2194. entry->prev->next = next;
  2195. }
  2196. else {
  2197. assert(xidregistry->head == entry);
  2198. xidregistry->head = next;
  2199. }
  2200. if (next != NULL) {
  2201. next->prev = entry->prev;
  2202. }
  2203. Py_XDECREF(entry->weakref);
  2204. PyMem_RawFree(entry);
  2205. return next;
  2206. }
  2207. static void
  2208. _xidregistry_clear(struct _xidregistry *xidregistry)
  2209. {
  2210. struct _xidregitem *cur = xidregistry->head;
  2211. xidregistry->head = NULL;
  2212. while (cur != NULL) {
  2213. struct _xidregitem *next = cur->next;
  2214. Py_XDECREF(cur->weakref);
  2215. PyMem_RawFree(cur);
  2216. cur = next;
  2217. }
  2218. }
  2219. static struct _xidregitem *
  2220. _xidregistry_find_type(struct _xidregistry *xidregistry, PyTypeObject *cls)
  2221. {
  2222. struct _xidregitem *cur = xidregistry->head;
  2223. while (cur != NULL) {
  2224. if (cur->weakref != NULL) {
  2225. // cur is/was a heap type.
  2226. PyObject *registered = PyWeakref_GetObject(cur->weakref);
  2227. assert(registered != NULL);
  2228. if (registered == Py_None) {
  2229. // The weakly ref'ed object was freed.
  2230. cur = _xidregistry_remove_entry(xidregistry, cur);
  2231. continue;
  2232. }
  2233. assert(PyType_Check(registered));
  2234. assert(cur->cls == (PyTypeObject *)registered);
  2235. assert(cur->cls->tp_flags & Py_TPFLAGS_HEAPTYPE);
  2236. //Py_DECREF(registered);
  2237. }
  2238. if (cur->cls == cls) {
  2239. return cur;
  2240. }
  2241. cur = cur->next;
  2242. }
  2243. return NULL;
  2244. }
  2245. static inline struct _xidregistry *
  2246. _get_xidregistry(PyInterpreterState *interp, PyTypeObject *cls)
  2247. {
  2248. struct _xidregistry *xidregistry = &interp->runtime->xidregistry;
  2249. if (cls->tp_flags & Py_TPFLAGS_HEAPTYPE) {
  2250. assert(interp->xidregistry.mutex == xidregistry->mutex);
  2251. xidregistry = &interp->xidregistry;
  2252. }
  2253. return xidregistry;
  2254. }
  2255. static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
  2256. static inline void
  2257. _ensure_builtins_xid(PyInterpreterState *interp, struct _xidregistry *xidregistry)
  2258. {
  2259. if (xidregistry != &interp->xidregistry) {
  2260. assert(xidregistry == &interp->runtime->xidregistry);
  2261. if (xidregistry->head == NULL) {
  2262. _register_builtins_for_crossinterpreter_data(xidregistry);
  2263. }
  2264. }
  2265. }
  2266. int
  2267. _PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
  2268. crossinterpdatafunc getdata)
  2269. {
  2270. if (!PyType_Check(cls)) {
  2271. PyErr_Format(PyExc_ValueError, "only classes may be registered");
  2272. return -1;
  2273. }
  2274. if (getdata == NULL) {
  2275. PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
  2276. return -1;
  2277. }
  2278. int res = 0;
  2279. PyInterpreterState *interp = _PyInterpreterState_GET();
  2280. struct _xidregistry *xidregistry = _get_xidregistry(interp, cls);
  2281. PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
  2282. _ensure_builtins_xid(interp, xidregistry);
  2283. struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
  2284. if (matched != NULL) {
  2285. assert(matched->getdata == getdata);
  2286. matched->refcount += 1;
  2287. goto finally;
  2288. }
  2289. res = _xidregistry_add_type(xidregistry, cls, getdata);
  2290. finally:
  2291. PyThread_release_lock(xidregistry->mutex);
  2292. return res;
  2293. }
  2294. int
  2295. _PyCrossInterpreterData_UnregisterClass(PyTypeObject *cls)
  2296. {
  2297. int res = 0;
  2298. PyInterpreterState *interp = _PyInterpreterState_GET();
  2299. struct _xidregistry *xidregistry = _get_xidregistry(interp, cls);
  2300. PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
  2301. struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
  2302. if (matched != NULL) {
  2303. assert(matched->refcount > 0);
  2304. matched->refcount -= 1;
  2305. if (matched->refcount == 0) {
  2306. (void)_xidregistry_remove_entry(xidregistry, matched);
  2307. }
  2308. res = 1;
  2309. }
  2310. PyThread_release_lock(xidregistry->mutex);
  2311. return res;
  2312. }
  2313. /* Cross-interpreter objects are looked up by exact match on the class.
  2314. We can reassess this policy when we move from a global registry to a
  2315. tp_* slot. */
  2316. crossinterpdatafunc
  2317. _PyCrossInterpreterData_Lookup(PyObject *obj)
  2318. {
  2319. PyTypeObject *cls = Py_TYPE(obj);
  2320. PyInterpreterState *interp = _PyInterpreterState_GET();
  2321. struct _xidregistry *xidregistry = _get_xidregistry(interp, cls);
  2322. PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
  2323. _ensure_builtins_xid(interp, xidregistry);
  2324. struct _xidregitem *matched = _xidregistry_find_type(xidregistry, cls);
  2325. crossinterpdatafunc func = matched != NULL ? matched->getdata : NULL;
  2326. PyThread_release_lock(xidregistry->mutex);
  2327. return func;
  2328. }
  2329. /* cross-interpreter data for builtin types */
  2330. struct _shared_bytes_data {
  2331. char *bytes;
  2332. Py_ssize_t len;
  2333. };
  2334. static PyObject *
  2335. _new_bytes_object(_PyCrossInterpreterData *data)
  2336. {
  2337. struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
  2338. return PyBytes_FromStringAndSize(shared->bytes, shared->len);
  2339. }
  2340. static int
  2341. _bytes_shared(PyThreadState *tstate, PyObject *obj,
  2342. _PyCrossInterpreterData *data)
  2343. {
  2344. if (_PyCrossInterpreterData_InitWithSize(
  2345. data, tstate->interp, sizeof(struct _shared_bytes_data), obj,
  2346. _new_bytes_object
  2347. ) < 0)
  2348. {
  2349. return -1;
  2350. }
  2351. struct _shared_bytes_data *shared = (struct _shared_bytes_data *)data->data;
  2352. if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
  2353. _PyCrossInterpreterData_Clear(tstate->interp, data);
  2354. return -1;
  2355. }
  2356. return 0;
  2357. }
  2358. struct _shared_str_data {
  2359. int kind;
  2360. const void *buffer;
  2361. Py_ssize_t len;
  2362. };
  2363. static PyObject *
  2364. _new_str_object(_PyCrossInterpreterData *data)
  2365. {
  2366. struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
  2367. return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
  2368. }
  2369. static int
  2370. _str_shared(PyThreadState *tstate, PyObject *obj,
  2371. _PyCrossInterpreterData *data)
  2372. {
  2373. if (_PyCrossInterpreterData_InitWithSize(
  2374. data, tstate->interp, sizeof(struct _shared_str_data), obj,
  2375. _new_str_object
  2376. ) < 0)
  2377. {
  2378. return -1;
  2379. }
  2380. struct _shared_str_data *shared = (struct _shared_str_data *)data->data;
  2381. shared->kind = PyUnicode_KIND(obj);
  2382. shared->buffer = PyUnicode_DATA(obj);
  2383. shared->len = PyUnicode_GET_LENGTH(obj);
  2384. return 0;
  2385. }
  2386. static PyObject *
  2387. _new_long_object(_PyCrossInterpreterData *data)
  2388. {
  2389. return PyLong_FromSsize_t((Py_ssize_t)(data->data));
  2390. }
  2391. static int
  2392. _long_shared(PyThreadState *tstate, PyObject *obj,
  2393. _PyCrossInterpreterData *data)
  2394. {
  2395. /* Note that this means the size of shareable ints is bounded by
  2396. * sys.maxsize. Hence on 32-bit architectures that is half the
  2397. * size of maximum shareable ints on 64-bit.
  2398. */
  2399. Py_ssize_t value = PyLong_AsSsize_t(obj);
  2400. if (value == -1 && PyErr_Occurred()) {
  2401. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  2402. PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
  2403. }
  2404. return -1;
  2405. }
  2406. _PyCrossInterpreterData_Init(data, tstate->interp, (void *)value, NULL,
  2407. _new_long_object);
  2408. // data->obj and data->free remain NULL
  2409. return 0;
  2410. }
  2411. static PyObject *
  2412. _new_none_object(_PyCrossInterpreterData *data)
  2413. {
  2414. // XXX Singleton refcounts are problematic across interpreters...
  2415. return Py_NewRef(Py_None);
  2416. }
  2417. static int
  2418. _none_shared(PyThreadState *tstate, PyObject *obj,
  2419. _PyCrossInterpreterData *data)
  2420. {
  2421. _PyCrossInterpreterData_Init(data, tstate->interp, NULL, NULL,
  2422. _new_none_object);
  2423. // data->data, data->obj and data->free remain NULL
  2424. return 0;
  2425. }
  2426. static void
  2427. _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
  2428. {
  2429. // None
  2430. if (_xidregistry_add_type(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
  2431. Py_FatalError("could not register None for cross-interpreter sharing");
  2432. }
  2433. // int
  2434. if (_xidregistry_add_type(xidregistry, &PyLong_Type, _long_shared) != 0) {
  2435. Py_FatalError("could not register int for cross-interpreter sharing");
  2436. }
  2437. // bytes
  2438. if (_xidregistry_add_type(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
  2439. Py_FatalError("could not register bytes for cross-interpreter sharing");
  2440. }
  2441. // str
  2442. if (_xidregistry_add_type(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
  2443. Py_FatalError("could not register str for cross-interpreter sharing");
  2444. }
  2445. }
  2446. /*************/
  2447. /* Other API */
  2448. /*************/
  2449. _PyFrameEvalFunction
  2450. _PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
  2451. {
  2452. if (interp->eval_frame == NULL) {
  2453. return _PyEval_EvalFrameDefault;
  2454. }
  2455. return interp->eval_frame;
  2456. }
  2457. void
  2458. _PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
  2459. _PyFrameEvalFunction eval_frame)
  2460. {
  2461. if (eval_frame == _PyEval_EvalFrameDefault) {
  2462. interp->eval_frame = NULL;
  2463. }
  2464. else {
  2465. interp->eval_frame = eval_frame;
  2466. }
  2467. }
  2468. const PyConfig*
  2469. _PyInterpreterState_GetConfig(PyInterpreterState *interp)
  2470. {
  2471. return &interp->config;
  2472. }
  2473. int
  2474. _PyInterpreterState_GetConfigCopy(PyConfig *config)
  2475. {
  2476. PyInterpreterState *interp = PyInterpreterState_Get();
  2477. PyStatus status = _PyConfig_Copy(config, &interp->config);
  2478. if (PyStatus_Exception(status)) {
  2479. _PyErr_SetFromPyStatus(status);
  2480. return -1;
  2481. }
  2482. return 0;
  2483. }
  2484. const PyConfig*
  2485. _Py_GetConfig(void)
  2486. {
  2487. _PyRuntimeState *runtime = &_PyRuntime;
  2488. assert(PyGILState_Check());
  2489. PyThreadState *tstate = current_fast_get(runtime);
  2490. _Py_EnsureTstateNotNULL(tstate);
  2491. return _PyInterpreterState_GetConfig(tstate->interp);
  2492. }
  2493. int
  2494. _PyInterpreterState_HasFeature(PyInterpreterState *interp, unsigned long feature)
  2495. {
  2496. return ((interp->feature_flags & feature) != 0);
  2497. }
  2498. #define MINIMUM_OVERHEAD 1000
  2499. static PyObject **
  2500. push_chunk(PyThreadState *tstate, int size)
  2501. {
  2502. int allocate_size = DATA_STACK_CHUNK_SIZE;
  2503. while (allocate_size < (int)sizeof(PyObject*)*(size + MINIMUM_OVERHEAD)) {
  2504. allocate_size *= 2;
  2505. }
  2506. _PyStackChunk *new = allocate_chunk(allocate_size, tstate->datastack_chunk);
  2507. if (new == NULL) {
  2508. return NULL;
  2509. }
  2510. if (tstate->datastack_chunk) {
  2511. tstate->datastack_chunk->top = tstate->datastack_top -
  2512. &tstate->datastack_chunk->data[0];
  2513. }
  2514. tstate->datastack_chunk = new;
  2515. tstate->datastack_limit = (PyObject **)(((char *)new) + allocate_size);
  2516. // When new is the "root" chunk (i.e. new->previous == NULL), we can keep
  2517. // _PyThreadState_PopFrame from freeing it later by "skipping" over the
  2518. // first element:
  2519. PyObject **res = &new->data[new->previous == NULL];
  2520. tstate->datastack_top = res + size;
  2521. return res;
  2522. }
  2523. _PyInterpreterFrame *
  2524. _PyThreadState_PushFrame(PyThreadState *tstate, size_t size)
  2525. {
  2526. assert(size < INT_MAX/sizeof(PyObject *));
  2527. if (_PyThreadState_HasStackSpace(tstate, (int)size)) {
  2528. _PyInterpreterFrame *res = (_PyInterpreterFrame *)tstate->datastack_top;
  2529. tstate->datastack_top += size;
  2530. return res;
  2531. }
  2532. return (_PyInterpreterFrame *)push_chunk(tstate, (int)size);
  2533. }
  2534. void
  2535. _PyThreadState_PopFrame(PyThreadState *tstate, _PyInterpreterFrame * frame)
  2536. {
  2537. assert(tstate->datastack_chunk);
  2538. PyObject **base = (PyObject **)frame;
  2539. if (base == &tstate->datastack_chunk->data[0]) {
  2540. _PyStackChunk *chunk = tstate->datastack_chunk;
  2541. _PyStackChunk *previous = chunk->previous;
  2542. // push_chunk ensures that the root chunk is never popped:
  2543. assert(previous);
  2544. tstate->datastack_top = &previous->data[previous->top];
  2545. tstate->datastack_chunk = previous;
  2546. _PyObject_VirtualFree(chunk, chunk->size);
  2547. tstate->datastack_limit = (PyObject **)(((char *)previous) + previous->size);
  2548. }
  2549. else {
  2550. assert(tstate->datastack_top);
  2551. assert(tstate->datastack_top >= base);
  2552. tstate->datastack_top = base;
  2553. }
  2554. }
  2555. #ifndef NDEBUG
  2556. // Check that a Python thread state valid. In practice, this function is used
  2557. // on a Python debug build to check if 'tstate' is a dangling pointer, if the
  2558. // PyThreadState memory has been freed.
  2559. //
  2560. // Usage:
  2561. //
  2562. // assert(_PyThreadState_CheckConsistency(tstate));
  2563. int
  2564. _PyThreadState_CheckConsistency(PyThreadState *tstate)
  2565. {
  2566. assert(!_PyMem_IsPtrFreed(tstate));
  2567. assert(!_PyMem_IsPtrFreed(tstate->interp));
  2568. return 1;
  2569. }
  2570. #endif
  2571. // Check if a Python thread must exit immediately, rather than taking the GIL
  2572. // if Py_Finalize() has been called.
  2573. //
  2574. // When this function is called by a daemon thread after Py_Finalize() has been
  2575. // called, the GIL does no longer exist.
  2576. //
  2577. // tstate can be a dangling pointer (point to freed memory): only tstate value
  2578. // is used, the pointer is not deferenced.
  2579. //
  2580. // tstate must be non-NULL.
  2581. int
  2582. _PyThreadState_MustExit(PyThreadState *tstate)
  2583. {
  2584. /* bpo-39877: Access _PyRuntime directly rather than using
  2585. tstate->interp->runtime to support calls from Python daemon threads.
  2586. After Py_Finalize() has been called, tstate can be a dangling pointer:
  2587. point to PyThreadState freed memory. */
  2588. unsigned long finalizing_id = _PyRuntimeState_GetFinalizingID(&_PyRuntime);
  2589. PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(&_PyRuntime);
  2590. if (finalizing == NULL) {
  2591. // XXX This isn't completely safe from daemon thraeds,
  2592. // since tstate might be a dangling pointer.
  2593. finalizing = _PyInterpreterState_GetFinalizing(tstate->interp);
  2594. finalizing_id = _PyInterpreterState_GetFinalizingID(tstate->interp);
  2595. }
  2596. // XXX else check &_PyRuntime._main_interpreter._initial_thread
  2597. if (finalizing == NULL) {
  2598. return 0;
  2599. }
  2600. else if (finalizing == tstate) {
  2601. return 0;
  2602. }
  2603. else if (finalizing_id == PyThread_get_thread_ident()) {
  2604. /* gh-109793: we must have switched interpreters. */
  2605. return 0;
  2606. }
  2607. return 1;
  2608. }
  2609. #ifdef __cplusplus
  2610. }
  2611. #endif