_xxsubinterpretersmodule.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  1. /* interpreters module */
  2. /* low-level access to interpreter primitives */
  3. #ifndef Py_BUILD_CORE_BUILTIN
  4. # define Py_BUILD_CORE_MODULE 1
  5. #endif
  6. #include "Python.h"
  7. #include "pycore_initconfig.h" // _PyErr_SetFromPyStatus()
  8. #include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
  9. #include "pycore_pystate.h" // _PyInterpreterState_SetRunningMain()
  10. #include "interpreteridobject.h"
  11. #define MODULE_NAME "_xxsubinterpreters"
  12. static const char *
  13. _copy_raw_string(PyObject *strobj)
  14. {
  15. const char *str = PyUnicode_AsUTF8(strobj);
  16. if (str == NULL) {
  17. return NULL;
  18. }
  19. char *copied = PyMem_RawMalloc(strlen(str)+1);
  20. if (copied == NULL) {
  21. PyErr_NoMemory();
  22. return NULL;
  23. }
  24. strcpy(copied, str);
  25. return copied;
  26. }
  27. static PyInterpreterState *
  28. _get_current_interp(void)
  29. {
  30. // PyInterpreterState_Get() aborts if lookup fails, so don't need
  31. // to check the result for NULL.
  32. return PyInterpreterState_Get();
  33. }
  34. static PyObject *
  35. add_new_exception(PyObject *mod, const char *name, PyObject *base)
  36. {
  37. assert(!PyObject_HasAttrString(mod, name));
  38. PyObject *exctype = PyErr_NewException(name, base, NULL);
  39. if (exctype == NULL) {
  40. return NULL;
  41. }
  42. int res = PyModule_AddType(mod, (PyTypeObject *)exctype);
  43. if (res < 0) {
  44. Py_DECREF(exctype);
  45. return NULL;
  46. }
  47. return exctype;
  48. }
  49. #define ADD_NEW_EXCEPTION(MOD, NAME, BASE) \
  50. add_new_exception(MOD, MODULE_NAME "." Py_STRINGIFY(NAME), BASE)
  51. static int
  52. _release_xid_data(_PyCrossInterpreterData *data)
  53. {
  54. PyObject *exc = PyErr_GetRaisedException();
  55. int res = _PyCrossInterpreterData_Release(data);
  56. if (res < 0) {
  57. /* The owning interpreter is already destroyed. */
  58. _PyCrossInterpreterData_Clear(NULL, data);
  59. // XXX Emit a warning?
  60. PyErr_Clear();
  61. }
  62. PyErr_SetRaisedException(exc);
  63. return res;
  64. }
  65. /* module state *************************************************************/
  66. typedef struct {
  67. /* exceptions */
  68. PyObject *RunFailedError;
  69. } module_state;
  70. static inline module_state *
  71. get_module_state(PyObject *mod)
  72. {
  73. assert(mod != NULL);
  74. module_state *state = PyModule_GetState(mod);
  75. assert(state != NULL);
  76. return state;
  77. }
  78. static int
  79. traverse_module_state(module_state *state, visitproc visit, void *arg)
  80. {
  81. /* exceptions */
  82. Py_VISIT(state->RunFailedError);
  83. return 0;
  84. }
  85. static int
  86. clear_module_state(module_state *state)
  87. {
  88. /* exceptions */
  89. Py_CLEAR(state->RunFailedError);
  90. return 0;
  91. }
  92. /* data-sharing-specific code ***********************************************/
  93. struct _sharednsitem {
  94. const char *name;
  95. _PyCrossInterpreterData data;
  96. };
  97. static void _sharednsitem_clear(struct _sharednsitem *); // forward
  98. static int
  99. _sharednsitem_init(struct _sharednsitem *item, PyObject *key, PyObject *value)
  100. {
  101. item->name = _copy_raw_string(key);
  102. if (item->name == NULL) {
  103. return -1;
  104. }
  105. if (_PyObject_GetCrossInterpreterData(value, &item->data) != 0) {
  106. _sharednsitem_clear(item);
  107. return -1;
  108. }
  109. return 0;
  110. }
  111. static void
  112. _sharednsitem_clear(struct _sharednsitem *item)
  113. {
  114. if (item->name != NULL) {
  115. PyMem_RawFree((void *)item->name);
  116. item->name = NULL;
  117. }
  118. (void)_release_xid_data(&item->data);
  119. }
  120. static int
  121. _sharednsitem_apply(struct _sharednsitem *item, PyObject *ns)
  122. {
  123. PyObject *name = PyUnicode_FromString(item->name);
  124. if (name == NULL) {
  125. return -1;
  126. }
  127. PyObject *value = _PyCrossInterpreterData_NewObject(&item->data);
  128. if (value == NULL) {
  129. Py_DECREF(name);
  130. return -1;
  131. }
  132. int res = PyDict_SetItem(ns, name, value);
  133. Py_DECREF(name);
  134. Py_DECREF(value);
  135. return res;
  136. }
  137. typedef struct _sharedns {
  138. Py_ssize_t len;
  139. struct _sharednsitem* items;
  140. } _sharedns;
  141. static _sharedns *
  142. _sharedns_new(Py_ssize_t len)
  143. {
  144. _sharedns *shared = PyMem_RawCalloc(sizeof(_sharedns), 1);
  145. if (shared == NULL) {
  146. PyErr_NoMemory();
  147. return NULL;
  148. }
  149. shared->len = len;
  150. shared->items = PyMem_RawCalloc(sizeof(struct _sharednsitem), len);
  151. if (shared->items == NULL) {
  152. PyErr_NoMemory();
  153. PyMem_RawFree(shared);
  154. return NULL;
  155. }
  156. return shared;
  157. }
  158. static void
  159. _sharedns_free(_sharedns *shared)
  160. {
  161. for (Py_ssize_t i=0; i < shared->len; i++) {
  162. _sharednsitem_clear(&shared->items[i]);
  163. }
  164. PyMem_RawFree(shared->items);
  165. PyMem_RawFree(shared);
  166. }
  167. static _sharedns *
  168. _get_shared_ns(PyObject *shareable)
  169. {
  170. if (shareable == NULL || shareable == Py_None) {
  171. return NULL;
  172. }
  173. Py_ssize_t len = PyDict_Size(shareable);
  174. if (len == 0) {
  175. return NULL;
  176. }
  177. _sharedns *shared = _sharedns_new(len);
  178. if (shared == NULL) {
  179. return NULL;
  180. }
  181. Py_ssize_t pos = 0;
  182. for (Py_ssize_t i=0; i < len; i++) {
  183. PyObject *key, *value;
  184. if (PyDict_Next(shareable, &pos, &key, &value) == 0) {
  185. break;
  186. }
  187. if (_sharednsitem_init(&shared->items[i], key, value) != 0) {
  188. break;
  189. }
  190. }
  191. if (PyErr_Occurred()) {
  192. _sharedns_free(shared);
  193. return NULL;
  194. }
  195. return shared;
  196. }
  197. static int
  198. _sharedns_apply(_sharedns *shared, PyObject *ns)
  199. {
  200. for (Py_ssize_t i=0; i < shared->len; i++) {
  201. if (_sharednsitem_apply(&shared->items[i], ns) != 0) {
  202. return -1;
  203. }
  204. }
  205. return 0;
  206. }
  207. // Ultimately we'd like to preserve enough information about the
  208. // exception and traceback that we could re-constitute (or at least
  209. // simulate, a la traceback.TracebackException), and even chain, a copy
  210. // of the exception in the calling interpreter.
  211. typedef struct _sharedexception {
  212. const char *name;
  213. const char *msg;
  214. } _sharedexception;
  215. static const struct _sharedexception no_exception = {
  216. .name = NULL,
  217. .msg = NULL,
  218. };
  219. static void
  220. _sharedexception_clear(_sharedexception *exc)
  221. {
  222. if (exc->name != NULL) {
  223. PyMem_RawFree((void *)exc->name);
  224. }
  225. if (exc->msg != NULL) {
  226. PyMem_RawFree((void *)exc->msg);
  227. }
  228. }
  229. static const char *
  230. _sharedexception_bind(PyObject *exc, _sharedexception *sharedexc)
  231. {
  232. assert(exc != NULL);
  233. const char *failure = NULL;
  234. PyObject *nameobj = PyUnicode_FromFormat("%S", Py_TYPE(exc));
  235. if (nameobj == NULL) {
  236. failure = "unable to format exception type name";
  237. goto error;
  238. }
  239. sharedexc->name = _copy_raw_string(nameobj);
  240. Py_DECREF(nameobj);
  241. if (sharedexc->name == NULL) {
  242. if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
  243. failure = "out of memory copying exception type name";
  244. } else {
  245. failure = "unable to encode and copy exception type name";
  246. }
  247. goto error;
  248. }
  249. if (exc != NULL) {
  250. PyObject *msgobj = PyUnicode_FromFormat("%S", exc);
  251. if (msgobj == NULL) {
  252. failure = "unable to format exception message";
  253. goto error;
  254. }
  255. sharedexc->msg = _copy_raw_string(msgobj);
  256. Py_DECREF(msgobj);
  257. if (sharedexc->msg == NULL) {
  258. if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
  259. failure = "out of memory copying exception message";
  260. } else {
  261. failure = "unable to encode and copy exception message";
  262. }
  263. goto error;
  264. }
  265. }
  266. return NULL;
  267. error:
  268. assert(failure != NULL);
  269. PyErr_Clear();
  270. _sharedexception_clear(sharedexc);
  271. *sharedexc = no_exception;
  272. return failure;
  273. }
  274. static void
  275. _sharedexception_apply(_sharedexception *exc, PyObject *wrapperclass)
  276. {
  277. if (exc->name != NULL) {
  278. if (exc->msg != NULL) {
  279. PyErr_Format(wrapperclass, "%s: %s", exc->name, exc->msg);
  280. }
  281. else {
  282. PyErr_SetString(wrapperclass, exc->name);
  283. }
  284. }
  285. else if (exc->msg != NULL) {
  286. PyErr_SetString(wrapperclass, exc->msg);
  287. }
  288. else {
  289. PyErr_SetNone(wrapperclass);
  290. }
  291. }
  292. /* interpreter-specific code ************************************************/
  293. static int
  294. exceptions_init(PyObject *mod)
  295. {
  296. module_state *state = get_module_state(mod);
  297. if (state == NULL) {
  298. return -1;
  299. }
  300. #define ADD(NAME, BASE) \
  301. do { \
  302. assert(state->NAME == NULL); \
  303. state->NAME = ADD_NEW_EXCEPTION(mod, NAME, BASE); \
  304. if (state->NAME == NULL) { \
  305. return -1; \
  306. } \
  307. } while (0)
  308. // An uncaught exception came out of interp_run_string().
  309. ADD(RunFailedError, PyExc_RuntimeError);
  310. #undef ADD
  311. return 0;
  312. }
  313. static int
  314. _run_script(PyInterpreterState *interp, const char *codestr,
  315. _sharedns *shared, _sharedexception *sharedexc)
  316. {
  317. if (_PyInterpreterState_SetRunningMain(interp) < 0) {
  318. // We skip going through the shared exception.
  319. return -1;
  320. }
  321. PyObject *excval = NULL;
  322. PyObject *main_mod = _PyInterpreterState_GetMainModule(interp);
  323. if (main_mod == NULL) {
  324. goto error;
  325. }
  326. PyObject *ns = PyModule_GetDict(main_mod); // borrowed
  327. Py_DECREF(main_mod);
  328. if (ns == NULL) {
  329. goto error;
  330. }
  331. Py_INCREF(ns);
  332. // Apply the cross-interpreter data.
  333. if (shared != NULL) {
  334. if (_sharedns_apply(shared, ns) != 0) {
  335. Py_DECREF(ns);
  336. goto error;
  337. }
  338. }
  339. // Run the string (see PyRun_SimpleStringFlags).
  340. PyObject *result = PyRun_StringFlags(codestr, Py_file_input, ns, ns, NULL);
  341. Py_DECREF(ns);
  342. if (result == NULL) {
  343. goto error;
  344. }
  345. else {
  346. Py_DECREF(result); // We throw away the result.
  347. }
  348. _PyInterpreterState_SetNotRunningMain(interp);
  349. *sharedexc = no_exception;
  350. return 0;
  351. error:
  352. excval = PyErr_GetRaisedException();
  353. const char *failure = _sharedexception_bind(excval, sharedexc);
  354. if (failure != NULL) {
  355. fprintf(stderr,
  356. "RunFailedError: script raised an uncaught exception (%s)",
  357. failure);
  358. PyErr_Clear();
  359. }
  360. Py_XDECREF(excval);
  361. assert(!PyErr_Occurred());
  362. _PyInterpreterState_SetNotRunningMain(interp);
  363. return -1;
  364. }
  365. static int
  366. _run_script_in_interpreter(PyObject *mod, PyInterpreterState *interp,
  367. const char *codestr, PyObject *shareables)
  368. {
  369. module_state *state = get_module_state(mod);
  370. _sharedns *shared = _get_shared_ns(shareables);
  371. if (shared == NULL && PyErr_Occurred()) {
  372. return -1;
  373. }
  374. // Switch to interpreter.
  375. PyThreadState *save_tstate = NULL;
  376. if (interp != PyInterpreterState_Get()) {
  377. // XXX gh-109860: Using the "head" thread isn't strictly correct.
  378. PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
  379. assert(tstate != NULL);
  380. // Hack (until gh-109860): The interpreter's initial thread state
  381. // is least likely to break.
  382. while(tstate->next != NULL) {
  383. tstate = tstate->next;
  384. }
  385. // We must do this check before switching interpreters, so any
  386. // exception gets raised in the right one.
  387. // XXX gh-109860: Drop this redundant check once we stop
  388. // re-using tstates that might already be in use.
  389. if (_PyInterpreterState_IsRunningMain(interp)) {
  390. PyErr_SetString(PyExc_RuntimeError,
  391. "interpreter already running");
  392. if (shared != NULL) {
  393. _sharedns_free(shared);
  394. }
  395. return -1;
  396. }
  397. // XXX Possible GILState issues?
  398. save_tstate = PyThreadState_Swap(tstate);
  399. }
  400. // Run the script.
  401. _sharedexception exc = {NULL, NULL};
  402. int result = _run_script(interp, codestr, shared, &exc);
  403. // Switch back.
  404. if (save_tstate != NULL) {
  405. PyThreadState_Swap(save_tstate);
  406. }
  407. // Propagate any exception out to the caller.
  408. if (exc.name != NULL) {
  409. assert(state != NULL);
  410. _sharedexception_apply(&exc, state->RunFailedError);
  411. }
  412. else if (result != 0) {
  413. if (!PyErr_Occurred()) {
  414. // We were unable to allocate a shared exception.
  415. PyErr_NoMemory();
  416. }
  417. }
  418. if (shared != NULL) {
  419. _sharedns_free(shared);
  420. }
  421. return result;
  422. }
  423. /* module level code ********************************************************/
  424. static PyObject *
  425. interp_create(PyObject *self, PyObject *args, PyObject *kwds)
  426. {
  427. static char *kwlist[] = {"isolated", NULL};
  428. int isolated = 1;
  429. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|$i:create", kwlist,
  430. &isolated)) {
  431. return NULL;
  432. }
  433. // Create and initialize the new interpreter.
  434. PyThreadState *save_tstate = PyThreadState_Get();
  435. assert(save_tstate != NULL);
  436. const PyInterpreterConfig config = isolated
  437. ? (PyInterpreterConfig)_PyInterpreterConfig_INIT
  438. : (PyInterpreterConfig)_PyInterpreterConfig_LEGACY_INIT;
  439. // XXX Possible GILState issues?
  440. PyThreadState *tstate = NULL;
  441. PyStatus status = Py_NewInterpreterFromConfig(&tstate, &config);
  442. PyThreadState_Swap(save_tstate);
  443. if (PyStatus_Exception(status)) {
  444. /* Since no new thread state was created, there is no exception to
  445. propagate; raise a fresh one after swapping in the old thread
  446. state. */
  447. _PyErr_SetFromPyStatus(status);
  448. PyObject *exc = PyErr_GetRaisedException();
  449. PyErr_SetString(PyExc_RuntimeError, "interpreter creation failed");
  450. _PyErr_ChainExceptions1(exc);
  451. return NULL;
  452. }
  453. assert(tstate != NULL);
  454. PyInterpreterState *interp = PyThreadState_GetInterpreter(tstate);
  455. PyObject *idobj = _PyInterpreterState_GetIDObject(interp);
  456. if (idobj == NULL) {
  457. // XXX Possible GILState issues?
  458. save_tstate = PyThreadState_Swap(tstate);
  459. Py_EndInterpreter(tstate);
  460. PyThreadState_Swap(save_tstate);
  461. return NULL;
  462. }
  463. _PyInterpreterState_RequireIDRef(interp, 1);
  464. return idobj;
  465. }
  466. PyDoc_STRVAR(create_doc,
  467. "create() -> ID\n\
  468. \n\
  469. Create a new interpreter and return a unique generated ID.");
  470. static PyObject *
  471. interp_destroy(PyObject *self, PyObject *args, PyObject *kwds)
  472. {
  473. static char *kwlist[] = {"id", NULL};
  474. PyObject *id;
  475. // XXX Use "L" for id?
  476. if (!PyArg_ParseTupleAndKeywords(args, kwds,
  477. "O:destroy", kwlist, &id)) {
  478. return NULL;
  479. }
  480. // Look up the interpreter.
  481. PyInterpreterState *interp = _PyInterpreterID_LookUp(id);
  482. if (interp == NULL) {
  483. return NULL;
  484. }
  485. // Ensure we don't try to destroy the current interpreter.
  486. PyInterpreterState *current = _get_current_interp();
  487. if (current == NULL) {
  488. return NULL;
  489. }
  490. if (interp == current) {
  491. PyErr_SetString(PyExc_RuntimeError,
  492. "cannot destroy the current interpreter");
  493. return NULL;
  494. }
  495. // Ensure the interpreter isn't running.
  496. /* XXX We *could* support destroying a running interpreter but
  497. aren't going to worry about it for now. */
  498. if (_PyInterpreterState_IsRunningMain(interp)) {
  499. PyErr_Format(PyExc_RuntimeError, "interpreter running");
  500. return NULL;
  501. }
  502. // Destroy the interpreter.
  503. // XXX gh-109860: Using the "head" thread isn't strictly correct.
  504. PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
  505. assert(tstate != NULL);
  506. // Hack (until gh-109860): The interpreter's initial thread state
  507. // is least likely to break.
  508. while(tstate->next != NULL) {
  509. tstate = tstate->next;
  510. }
  511. // XXX Possible GILState issues?
  512. PyThreadState *save_tstate = PyThreadState_Swap(tstate);
  513. Py_EndInterpreter(tstate);
  514. PyThreadState_Swap(save_tstate);
  515. Py_RETURN_NONE;
  516. }
  517. PyDoc_STRVAR(destroy_doc,
  518. "destroy(id)\n\
  519. \n\
  520. Destroy the identified interpreter.\n\
  521. \n\
  522. Attempting to destroy the current interpreter results in a RuntimeError.\n\
  523. So does an unrecognized ID.");
  524. static PyObject *
  525. interp_list_all(PyObject *self, PyObject *Py_UNUSED(ignored))
  526. {
  527. PyObject *ids, *id;
  528. PyInterpreterState *interp;
  529. ids = PyList_New(0);
  530. if (ids == NULL) {
  531. return NULL;
  532. }
  533. interp = PyInterpreterState_Head();
  534. while (interp != NULL) {
  535. id = _PyInterpreterState_GetIDObject(interp);
  536. if (id == NULL) {
  537. Py_DECREF(ids);
  538. return NULL;
  539. }
  540. // insert at front of list
  541. int res = PyList_Insert(ids, 0, id);
  542. Py_DECREF(id);
  543. if (res < 0) {
  544. Py_DECREF(ids);
  545. return NULL;
  546. }
  547. interp = PyInterpreterState_Next(interp);
  548. }
  549. return ids;
  550. }
  551. PyDoc_STRVAR(list_all_doc,
  552. "list_all() -> [ID]\n\
  553. \n\
  554. Return a list containing the ID of every existing interpreter.");
  555. static PyObject *
  556. interp_get_current(PyObject *self, PyObject *Py_UNUSED(ignored))
  557. {
  558. PyInterpreterState *interp =_get_current_interp();
  559. if (interp == NULL) {
  560. return NULL;
  561. }
  562. return _PyInterpreterState_GetIDObject(interp);
  563. }
  564. PyDoc_STRVAR(get_current_doc,
  565. "get_current() -> ID\n\
  566. \n\
  567. Return the ID of current interpreter.");
  568. static PyObject *
  569. interp_get_main(PyObject *self, PyObject *Py_UNUSED(ignored))
  570. {
  571. // Currently, 0 is always the main interpreter.
  572. int64_t id = 0;
  573. return _PyInterpreterID_New(id);
  574. }
  575. PyDoc_STRVAR(get_main_doc,
  576. "get_main() -> ID\n\
  577. \n\
  578. Return the ID of main interpreter.");
  579. static PyObject *
  580. interp_run_string(PyObject *self, PyObject *args, PyObject *kwds)
  581. {
  582. static char *kwlist[] = {"id", "script", "shared", NULL};
  583. PyObject *id, *code;
  584. PyObject *shared = NULL;
  585. if (!PyArg_ParseTupleAndKeywords(args, kwds,
  586. "OU|O:run_string", kwlist,
  587. &id, &code, &shared)) {
  588. return NULL;
  589. }
  590. // Look up the interpreter.
  591. PyInterpreterState *interp = _PyInterpreterID_LookUp(id);
  592. if (interp == NULL) {
  593. return NULL;
  594. }
  595. // Extract code.
  596. Py_ssize_t size;
  597. const char *codestr = PyUnicode_AsUTF8AndSize(code, &size);
  598. if (codestr == NULL) {
  599. return NULL;
  600. }
  601. if (strlen(codestr) != (size_t)size) {
  602. PyErr_SetString(PyExc_ValueError,
  603. "source code string cannot contain null bytes");
  604. return NULL;
  605. }
  606. // Run the code in the interpreter.
  607. if (_run_script_in_interpreter(self, interp, codestr, shared) != 0) {
  608. return NULL;
  609. }
  610. Py_RETURN_NONE;
  611. }
  612. PyDoc_STRVAR(run_string_doc,
  613. "run_string(id, script, shared)\n\
  614. \n\
  615. Execute the provided string in the identified interpreter.\n\
  616. \n\
  617. See PyRun_SimpleStrings.");
  618. static PyObject *
  619. object_is_shareable(PyObject *self, PyObject *args, PyObject *kwds)
  620. {
  621. static char *kwlist[] = {"obj", NULL};
  622. PyObject *obj;
  623. if (!PyArg_ParseTupleAndKeywords(args, kwds,
  624. "O:is_shareable", kwlist, &obj)) {
  625. return NULL;
  626. }
  627. if (_PyObject_CheckCrossInterpreterData(obj) == 0) {
  628. Py_RETURN_TRUE;
  629. }
  630. PyErr_Clear();
  631. Py_RETURN_FALSE;
  632. }
  633. PyDoc_STRVAR(is_shareable_doc,
  634. "is_shareable(obj) -> bool\n\
  635. \n\
  636. Return True if the object's data may be shared between interpreters and\n\
  637. False otherwise.");
  638. static PyObject *
  639. interp_is_running(PyObject *self, PyObject *args, PyObject *kwds)
  640. {
  641. static char *kwlist[] = {"id", NULL};
  642. PyObject *id;
  643. if (!PyArg_ParseTupleAndKeywords(args, kwds,
  644. "O:is_running", kwlist, &id)) {
  645. return NULL;
  646. }
  647. PyInterpreterState *interp = _PyInterpreterID_LookUp(id);
  648. if (interp == NULL) {
  649. return NULL;
  650. }
  651. if (_PyInterpreterState_IsRunningMain(interp)) {
  652. Py_RETURN_TRUE;
  653. }
  654. Py_RETURN_FALSE;
  655. }
  656. PyDoc_STRVAR(is_running_doc,
  657. "is_running(id) -> bool\n\
  658. \n\
  659. Return whether or not the identified interpreter is running.");
  660. static PyMethodDef module_functions[] = {
  661. {"create", _PyCFunction_CAST(interp_create),
  662. METH_VARARGS | METH_KEYWORDS, create_doc},
  663. {"destroy", _PyCFunction_CAST(interp_destroy),
  664. METH_VARARGS | METH_KEYWORDS, destroy_doc},
  665. {"list_all", interp_list_all,
  666. METH_NOARGS, list_all_doc},
  667. {"get_current", interp_get_current,
  668. METH_NOARGS, get_current_doc},
  669. {"get_main", interp_get_main,
  670. METH_NOARGS, get_main_doc},
  671. {"is_running", _PyCFunction_CAST(interp_is_running),
  672. METH_VARARGS | METH_KEYWORDS, is_running_doc},
  673. {"run_string", _PyCFunction_CAST(interp_run_string),
  674. METH_VARARGS | METH_KEYWORDS, run_string_doc},
  675. {"is_shareable", _PyCFunction_CAST(object_is_shareable),
  676. METH_VARARGS | METH_KEYWORDS, is_shareable_doc},
  677. {NULL, NULL} /* sentinel */
  678. };
  679. /* initialization function */
  680. PyDoc_STRVAR(module_doc,
  681. "This module provides primitive operations to manage Python interpreters.\n\
  682. The 'interpreters' module provides a more convenient interface.");
  683. static int
  684. module_exec(PyObject *mod)
  685. {
  686. /* Add exception types */
  687. if (exceptions_init(mod) != 0) {
  688. goto error;
  689. }
  690. // PyInterpreterID
  691. if (PyModule_AddType(mod, &_PyInterpreterID_Type) < 0) {
  692. goto error;
  693. }
  694. return 0;
  695. error:
  696. return -1;
  697. }
  698. static struct PyModuleDef_Slot module_slots[] = {
  699. {Py_mod_exec, module_exec},
  700. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  701. {0, NULL},
  702. };
  703. static int
  704. module_traverse(PyObject *mod, visitproc visit, void *arg)
  705. {
  706. module_state *state = get_module_state(mod);
  707. assert(state != NULL);
  708. traverse_module_state(state, visit, arg);
  709. return 0;
  710. }
  711. static int
  712. module_clear(PyObject *mod)
  713. {
  714. module_state *state = get_module_state(mod);
  715. assert(state != NULL);
  716. clear_module_state(state);
  717. return 0;
  718. }
  719. static void
  720. module_free(void *mod)
  721. {
  722. module_state *state = get_module_state(mod);
  723. assert(state != NULL);
  724. clear_module_state(state);
  725. }
  726. static struct PyModuleDef moduledef = {
  727. .m_base = PyModuleDef_HEAD_INIT,
  728. .m_name = MODULE_NAME,
  729. .m_doc = module_doc,
  730. .m_size = sizeof(module_state),
  731. .m_methods = module_functions,
  732. .m_slots = module_slots,
  733. .m_traverse = module_traverse,
  734. .m_clear = module_clear,
  735. .m_free = (freefunc)module_free,
  736. };
  737. PyMODINIT_FUNC
  738. PyInit__xxsubinterpreters(void)
  739. {
  740. return PyModuleDef_Init(&moduledef);
  741. }