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

344 lines
11 KiB

  1. #include <Python.h>
  2. #include "pythread.h"
  3. #include <inttypes.h>
  4. #include <stdio.h>
  5. #include <wchar.h>
  6. /*********************************************************
  7. * Embedded interpreter tests that need a custom exe
  8. *
  9. * Executed via 'EmbeddingTests' in Lib/test/test_capi.py
  10. *********************************************************/
  11. static void _testembed_Py_Initialize(void)
  12. {
  13. /* HACK: the "./" at front avoids a search along the PATH in
  14. Modules/getpath.c */
  15. Py_SetProgramName(L"./_testembed");
  16. Py_Initialize();
  17. }
  18. /*****************************************************
  19. * Test repeated initialisation and subinterpreters
  20. *****************************************************/
  21. static void print_subinterp(void)
  22. {
  23. /* Output information about the interpreter in the format
  24. expected in Lib/test/test_capi.py (test_subinterps). */
  25. PyThreadState *ts = PyThreadState_Get();
  26. PyInterpreterState *interp = ts->interp;
  27. int64_t id = PyInterpreterState_GetID(interp);
  28. printf("interp %" PRId64 " <0x%" PRIXPTR ">, thread state <0x%" PRIXPTR ">: ",
  29. id, (uintptr_t)interp, (uintptr_t)ts);
  30. fflush(stdout);
  31. PyRun_SimpleString(
  32. "import sys;"
  33. "print('id(modules) =', id(sys.modules));"
  34. "sys.stdout.flush()"
  35. );
  36. }
  37. static int test_repeated_init_and_subinterpreters(void)
  38. {
  39. PyThreadState *mainstate, *substate;
  40. PyGILState_STATE gilstate;
  41. int i, j;
  42. for (i=0; i<15; i++) {
  43. printf("--- Pass %d ---\n", i);
  44. _testembed_Py_Initialize();
  45. mainstate = PyThreadState_Get();
  46. PyEval_InitThreads();
  47. PyEval_ReleaseThread(mainstate);
  48. gilstate = PyGILState_Ensure();
  49. print_subinterp();
  50. PyThreadState_Swap(NULL);
  51. for (j=0; j<3; j++) {
  52. substate = Py_NewInterpreter();
  53. print_subinterp();
  54. Py_EndInterpreter(substate);
  55. }
  56. PyThreadState_Swap(mainstate);
  57. print_subinterp();
  58. PyGILState_Release(gilstate);
  59. PyEval_RestoreThread(mainstate);
  60. Py_Finalize();
  61. }
  62. return 0;
  63. }
  64. /*****************************************************
  65. * Test forcing a particular IO encoding
  66. *****************************************************/
  67. static void check_stdio_details(const char *encoding, const char * errors)
  68. {
  69. /* Output info for the test case to check */
  70. if (encoding) {
  71. printf("Expected encoding: %s\n", encoding);
  72. } else {
  73. printf("Expected encoding: default\n");
  74. }
  75. if (errors) {
  76. printf("Expected errors: %s\n", errors);
  77. } else {
  78. printf("Expected errors: default\n");
  79. }
  80. fflush(stdout);
  81. /* Force the given IO encoding */
  82. Py_SetStandardStreamEncoding(encoding, errors);
  83. _testembed_Py_Initialize();
  84. PyRun_SimpleString(
  85. "import sys;"
  86. "print('stdin: {0.encoding}:{0.errors}'.format(sys.stdin));"
  87. "print('stdout: {0.encoding}:{0.errors}'.format(sys.stdout));"
  88. "print('stderr: {0.encoding}:{0.errors}'.format(sys.stderr));"
  89. "sys.stdout.flush()"
  90. );
  91. Py_Finalize();
  92. }
  93. static int test_forced_io_encoding(void)
  94. {
  95. /* Check various combinations */
  96. printf("--- Use defaults ---\n");
  97. check_stdio_details(NULL, NULL);
  98. printf("--- Set errors only ---\n");
  99. check_stdio_details(NULL, "ignore");
  100. printf("--- Set encoding only ---\n");
  101. check_stdio_details("latin-1", NULL);
  102. printf("--- Set encoding and errors ---\n");
  103. check_stdio_details("latin-1", "replace");
  104. /* Check calling after initialization fails */
  105. Py_Initialize();
  106. if (Py_SetStandardStreamEncoding(NULL, NULL) == 0) {
  107. printf("Unexpected success calling Py_SetStandardStreamEncoding");
  108. }
  109. Py_Finalize();
  110. return 0;
  111. }
  112. /*********************************************************
  113. * Test parts of the C-API that work before initialization
  114. *********************************************************/
  115. /* The pre-initialization tests tend to break by segfaulting, so explicitly
  116. * flushed progress messages make the broken API easier to find when they fail.
  117. */
  118. #define _Py_EMBED_PREINIT_CHECK(msg) \
  119. do {printf(msg); fflush(stdout);} while (0);
  120. static int test_pre_initialization_api(void)
  121. {
  122. /* Leading "./" ensures getpath.c can still find the standard library */
  123. _Py_EMBED_PREINIT_CHECK("Checking Py_DecodeLocale\n");
  124. wchar_t *program = Py_DecodeLocale("./spam", NULL);
  125. if (program == NULL) {
  126. fprintf(stderr, "Fatal error: cannot decode program name\n");
  127. return 1;
  128. }
  129. _Py_EMBED_PREINIT_CHECK("Checking Py_SetProgramName\n");
  130. Py_SetProgramName(program);
  131. _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
  132. Py_Initialize();
  133. _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
  134. PyRun_SimpleString("import sys; "
  135. "print('sys.executable:', sys.executable)");
  136. _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
  137. Py_Finalize();
  138. _Py_EMBED_PREINIT_CHECK("Freeing memory allocated by Py_DecodeLocale\n");
  139. PyMem_RawFree(program);
  140. return 0;
  141. }
  142. /* bpo-33042: Ensure embedding apps can predefine sys module options */
  143. static int test_pre_initialization_sys_options(void)
  144. {
  145. /* We allocate a couple of the options dynamically, and then delete
  146. * them before calling Py_Initialize. This ensures the interpreter isn't
  147. * relying on the caller to keep the passed in strings alive.
  148. */
  149. const wchar_t *static_warnoption = L"once";
  150. const wchar_t *static_xoption = L"also_not_an_option=2";
  151. size_t warnoption_len = wcslen(static_warnoption);
  152. size_t xoption_len = wcslen(static_xoption);
  153. wchar_t *dynamic_once_warnoption = \
  154. (wchar_t *) calloc(warnoption_len+1, sizeof(wchar_t));
  155. wchar_t *dynamic_xoption = \
  156. (wchar_t *) calloc(xoption_len+1, sizeof(wchar_t));
  157. wcsncpy(dynamic_once_warnoption, static_warnoption, warnoption_len+1);
  158. wcsncpy(dynamic_xoption, static_xoption, xoption_len+1);
  159. _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption\n");
  160. PySys_AddWarnOption(L"default");
  161. _Py_EMBED_PREINIT_CHECK("Checking PySys_ResetWarnOptions\n");
  162. PySys_ResetWarnOptions();
  163. _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption linked list\n");
  164. PySys_AddWarnOption(dynamic_once_warnoption);
  165. PySys_AddWarnOption(L"module");
  166. PySys_AddWarnOption(L"default");
  167. _Py_EMBED_PREINIT_CHECK("Checking PySys_AddXOption\n");
  168. PySys_AddXOption(L"not_an_option=1");
  169. PySys_AddXOption(dynamic_xoption);
  170. /* Delete the dynamic options early */
  171. free(dynamic_once_warnoption);
  172. dynamic_once_warnoption = NULL;
  173. free(dynamic_xoption);
  174. dynamic_xoption = NULL;
  175. _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
  176. _testembed_Py_Initialize();
  177. _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
  178. PyRun_SimpleString("import sys; "
  179. "print('sys.warnoptions:', sys.warnoptions); "
  180. "print('sys._xoptions:', sys._xoptions); "
  181. "warnings = sys.modules['warnings']; "
  182. "latest_filters = [f[0] for f in warnings.filters[:3]]; "
  183. "print('warnings.filters[:3]:', latest_filters)");
  184. _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
  185. Py_Finalize();
  186. return 0;
  187. }
  188. /* bpo-20891: Avoid race condition when initialising the GIL */
  189. static void bpo20891_thread(void *lockp)
  190. {
  191. PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
  192. PyGILState_STATE state = PyGILState_Ensure();
  193. if (!PyGILState_Check()) {
  194. fprintf(stderr, "PyGILState_Check failed!");
  195. abort();
  196. }
  197. PyGILState_Release(state);
  198. PyThread_release_lock(lock);
  199. PyThread_exit_thread();
  200. }
  201. static int test_bpo20891(void)
  202. {
  203. /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
  204. calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
  205. call PyEval_InitThreads() for us in this case. */
  206. PyThread_type_lock lock = PyThread_allocate_lock();
  207. if (!lock) {
  208. fprintf(stderr, "PyThread_allocate_lock failed!");
  209. return 1;
  210. }
  211. _testembed_Py_Initialize();
  212. unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
  213. if (thrd == PYTHREAD_INVALID_THREAD_ID) {
  214. fprintf(stderr, "PyThread_start_new_thread failed!");
  215. return 1;
  216. }
  217. PyThread_acquire_lock(lock, WAIT_LOCK);
  218. Py_BEGIN_ALLOW_THREADS
  219. /* wait until the thread exit */
  220. PyThread_acquire_lock(lock, WAIT_LOCK);
  221. Py_END_ALLOW_THREADS
  222. PyThread_free_lock(lock);
  223. return 0;
  224. }
  225. static int test_initialize_twice(void)
  226. {
  227. _testembed_Py_Initialize();
  228. /* bpo-33932: Calling Py_Initialize() twice should do nothing
  229. * (and not crash!). */
  230. Py_Initialize();
  231. Py_Finalize();
  232. return 0;
  233. }
  234. static int test_initialize_pymain(void)
  235. {
  236. wchar_t *argv[] = {L"PYTHON", L"-c",
  237. L"import sys; print(f'Py_Main() after Py_Initialize: sys.argv={sys.argv}')",
  238. L"arg2"};
  239. _testembed_Py_Initialize();
  240. /* bpo-34008: Calling Py_Main() after Py_Initialize() must not crash */
  241. Py_Main(Py_ARRAY_LENGTH(argv), argv);
  242. Py_Finalize();
  243. return 0;
  244. }
  245. /* *********************************************************
  246. * List of test cases and the function that implements it.
  247. *
  248. * Names are compared case-sensitively with the first
  249. * argument. If no match is found, or no first argument was
  250. * provided, the names of all test cases are printed and
  251. * the exit code will be -1.
  252. *
  253. * The int returned from test functions is used as the exit
  254. * code, and test_capi treats all non-zero exit codes as a
  255. * failed test.
  256. *********************************************************/
  257. struct TestCase
  258. {
  259. const char *name;
  260. int (*func)(void);
  261. };
  262. static struct TestCase TestCases[] = {
  263. { "forced_io_encoding", test_forced_io_encoding },
  264. { "repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters },
  265. { "pre_initialization_api", test_pre_initialization_api },
  266. { "pre_initialization_sys_options", test_pre_initialization_sys_options },
  267. { "bpo20891", test_bpo20891 },
  268. { "initialize_twice", test_initialize_twice },
  269. { "initialize_pymain", test_initialize_pymain },
  270. { NULL, NULL }
  271. };
  272. int main(int argc, char *argv[])
  273. {
  274. if (argc > 1) {
  275. for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
  276. if (strcmp(argv[1], tc->name) == 0)
  277. return (*tc->func)();
  278. }
  279. }
  280. /* No match found, or no test name provided, so display usage */
  281. printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
  282. "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
  283. "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
  284. for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
  285. printf(" %s\n", tc->name);
  286. }
  287. /* Non-zero exit code will cause test_embed.py tests to fail.
  288. This is intentional. */
  289. return -1;
  290. }