blob: b1be682f7adc522caba04b5cc971de22608b9efb [file] [log] [blame]
Antoine Pitrou8e605772011-04-25 21:21:07 +02001#include <Python.h>
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01002#include "pythread.h"
Eric Snowe3774162017-05-22 19:46:40 -07003#include <inttypes.h>
Antoine Pitrou8e605772011-04-25 21:21:07 +02004#include <stdio.h>
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07005#include <wchar.h>
Antoine Pitrou8e605772011-04-25 21:21:07 +02006
Nick Coghlan7d270ee2013-10-17 22:35:35 +10007/*********************************************************
8 * Embedded interpreter tests that need a custom exe
9 *
10 * Executed via 'EmbeddingTests' in Lib/test/test_capi.py
11 *********************************************************/
12
13static void _testembed_Py_Initialize(void)
14{
15 /* HACK: the "./" at front avoids a search along the PATH in
16 Modules/getpath.c */
17 Py_SetProgramName(L"./_testembed");
18 Py_Initialize();
19}
20
21
22/*****************************************************
Martin Panter8f265652016-04-19 04:03:41 +000023 * Test repeated initialisation and subinterpreters
Nick Coghlan7d270ee2013-10-17 22:35:35 +100024 *****************************************************/
25
26static void print_subinterp(void)
Antoine Pitrou8e605772011-04-25 21:21:07 +020027{
Eric Snowe3774162017-05-22 19:46:40 -070028 /* Output information about the interpreter in the format
29 expected in Lib/test/test_capi.py (test_subinterps). */
Antoine Pitrou8e605772011-04-25 21:21:07 +020030 PyThreadState *ts = PyThreadState_Get();
Eric Snowe3774162017-05-22 19:46:40 -070031 PyInterpreterState *interp = ts->interp;
32 int64_t id = PyInterpreterState_GetID(interp);
Eric Snowd1c3c132017-05-24 17:19:47 -070033 printf("interp %" PRId64 " <0x%" PRIXPTR ">, thread state <0x%" PRIXPTR ">: ",
Eric Snowe3774162017-05-22 19:46:40 -070034 id, (uintptr_t)interp, (uintptr_t)ts);
Antoine Pitrou8e605772011-04-25 21:21:07 +020035 fflush(stdout);
36 PyRun_SimpleString(
37 "import sys;"
38 "print('id(modules) =', id(sys.modules));"
39 "sys.stdout.flush()"
40 );
41}
42
Steve Dowerea74f0c2017-01-01 20:25:03 -080043static int test_repeated_init_and_subinterpreters(void)
Antoine Pitrou8e605772011-04-25 21:21:07 +020044{
45 PyThreadState *mainstate, *substate;
46 PyGILState_STATE gilstate;
47 int i, j;
48
Ned Deily939231b2016-08-16 00:17:42 -040049 for (i=0; i<15; i++) {
Antoine Pitrou8e605772011-04-25 21:21:07 +020050 printf("--- Pass %d ---\n", i);
Nick Coghlan7d270ee2013-10-17 22:35:35 +100051 _testembed_Py_Initialize();
Antoine Pitrou8e605772011-04-25 21:21:07 +020052 mainstate = PyThreadState_Get();
53
54 PyEval_InitThreads();
55 PyEval_ReleaseThread(mainstate);
56
57 gilstate = PyGILState_Ensure();
58 print_subinterp();
59 PyThreadState_Swap(NULL);
60
61 for (j=0; j<3; j++) {
62 substate = Py_NewInterpreter();
63 print_subinterp();
64 Py_EndInterpreter(substate);
65 }
66
67 PyThreadState_Swap(mainstate);
68 print_subinterp();
69 PyGILState_Release(gilstate);
Antoine Pitrou8e605772011-04-25 21:21:07 +020070
71 PyEval_RestoreThread(mainstate);
72 Py_Finalize();
73 }
Steve Dowerea74f0c2017-01-01 20:25:03 -080074 return 0;
Nick Coghlan7d270ee2013-10-17 22:35:35 +100075}
76
77/*****************************************************
78 * Test forcing a particular IO encoding
79 *****************************************************/
80
81static void check_stdio_details(const char *encoding, const char * errors)
82{
83 /* Output info for the test case to check */
84 if (encoding) {
85 printf("Expected encoding: %s\n", encoding);
86 } else {
87 printf("Expected encoding: default\n");
88 }
89 if (errors) {
90 printf("Expected errors: %s\n", errors);
91 } else {
92 printf("Expected errors: default\n");
93 }
94 fflush(stdout);
95 /* Force the given IO encoding */
96 Py_SetStandardStreamEncoding(encoding, errors);
97 _testembed_Py_Initialize();
98 PyRun_SimpleString(
99 "import sys;"
100 "print('stdin: {0.encoding}:{0.errors}'.format(sys.stdin));"
101 "print('stdout: {0.encoding}:{0.errors}'.format(sys.stdout));"
102 "print('stderr: {0.encoding}:{0.errors}'.format(sys.stderr));"
103 "sys.stdout.flush()"
104 );
105 Py_Finalize();
106}
107
Steve Dowerea74f0c2017-01-01 20:25:03 -0800108static int test_forced_io_encoding(void)
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000109{
110 /* Check various combinations */
111 printf("--- Use defaults ---\n");
112 check_stdio_details(NULL, NULL);
113 printf("--- Set errors only ---\n");
Victor Stinnerb2bef622014-03-18 02:38:12 +0100114 check_stdio_details(NULL, "ignore");
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000115 printf("--- Set encoding only ---\n");
116 check_stdio_details("latin-1", NULL);
117 printf("--- Set encoding and errors ---\n");
Victor Stinnerb2bef622014-03-18 02:38:12 +0100118 check_stdio_details("latin-1", "replace");
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000119
120 /* Check calling after initialization fails */
121 Py_Initialize();
122
123 if (Py_SetStandardStreamEncoding(NULL, NULL) == 0) {
124 printf("Unexpected success calling Py_SetStandardStreamEncoding");
125 }
126 Py_Finalize();
Steve Dowerea74f0c2017-01-01 20:25:03 -0800127 return 0;
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000128}
129
Victor Stinner9e87e772017-11-24 12:09:24 +0100130/*********************************************************
131 * Test parts of the C-API that work before initialization
132 *********************************************************/
133
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700134/* The pre-initialization tests tend to break by segfaulting, so explicitly
135 * flushed progress messages make the broken API easier to find when they fail.
136 */
137#define _Py_EMBED_PREINIT_CHECK(msg) \
138 do {printf(msg); fflush(stdout);} while (0);
139
Victor Stinner9e87e772017-11-24 12:09:24 +0100140static int test_pre_initialization_api(void)
141{
Nick Coghlan42746092017-11-26 14:19:13 +1000142 /* Leading "./" ensures getpath.c can still find the standard library */
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700143 _Py_EMBED_PREINIT_CHECK("Checking Py_DecodeLocale\n");
Nick Coghlan42746092017-11-26 14:19:13 +1000144 wchar_t *program = Py_DecodeLocale("./spam", NULL);
Victor Stinner9e87e772017-11-24 12:09:24 +0100145 if (program == NULL) {
146 fprintf(stderr, "Fatal error: cannot decode program name\n");
147 return 1;
148 }
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700149 _Py_EMBED_PREINIT_CHECK("Checking Py_SetProgramName\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100150 Py_SetProgramName(program);
151
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700152 _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100153 Py_Initialize();
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700154 _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
155 PyRun_SimpleString("import sys; "
156 "print('sys.executable:', sys.executable)");
157 _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100158 Py_Finalize();
159
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700160 _Py_EMBED_PREINIT_CHECK("Freeing memory allocated by Py_DecodeLocale\n");
Victor Stinner9e87e772017-11-24 12:09:24 +0100161 PyMem_RawFree(program);
162 return 0;
163}
164
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700165
166/* bpo-33042: Ensure embedding apps can predefine sys module options */
167static int test_pre_initialization_sys_options(void)
168{
Miss Islington (bot)29617172018-03-29 23:24:03 -0700169 /* We allocate a couple of the options dynamically, and then delete
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700170 * them before calling Py_Initialize. This ensures the interpreter isn't
171 * relying on the caller to keep the passed in strings alive.
172 */
Miss Islington (bot)29617172018-03-29 23:24:03 -0700173 const wchar_t *static_warnoption = L"once";
174 const wchar_t *static_xoption = L"also_not_an_option=2";
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700175 size_t warnoption_len = wcslen(static_warnoption);
176 size_t xoption_len = wcslen(static_xoption);
Miss Islington (bot)29617172018-03-29 23:24:03 -0700177 wchar_t *dynamic_once_warnoption = \
178 (wchar_t *) calloc(warnoption_len+1, sizeof(wchar_t));
179 wchar_t *dynamic_xoption = \
180 (wchar_t *) calloc(xoption_len+1, sizeof(wchar_t));
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700181 wcsncpy(dynamic_once_warnoption, static_warnoption, warnoption_len+1);
182 wcsncpy(dynamic_xoption, static_xoption, xoption_len+1);
183
184 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption\n");
185 PySys_AddWarnOption(L"default");
186 _Py_EMBED_PREINIT_CHECK("Checking PySys_ResetWarnOptions\n");
187 PySys_ResetWarnOptions();
188 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption linked list\n");
189 PySys_AddWarnOption(dynamic_once_warnoption);
190 PySys_AddWarnOption(L"module");
191 PySys_AddWarnOption(L"default");
192 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddXOption\n");
193 PySys_AddXOption(L"not_an_option=1");
194 PySys_AddXOption(dynamic_xoption);
195
196 /* Delete the dynamic options early */
197 free(dynamic_once_warnoption);
198 dynamic_once_warnoption = NULL;
199 free(dynamic_xoption);
200 dynamic_xoption = NULL;
201
202 _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
203 _testembed_Py_Initialize();
204 _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
205 PyRun_SimpleString("import sys; "
206 "print('sys.warnoptions:', sys.warnoptions); "
207 "print('sys._xoptions:', sys._xoptions); "
208 "warnings = sys.modules['warnings']; "
209 "latest_filters = [f[0] for f in warnings.filters[:3]]; "
210 "print('warnings.filters[:3]:', latest_filters)");
211 _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
212 Py_Finalize();
213
214 return 0;
215}
216
217
218/* bpo-20891: Avoid race condition when initialising the GIL */
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100219static void bpo20891_thread(void *lockp)
220{
221 PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
222
223 PyGILState_STATE state = PyGILState_Ensure();
224 if (!PyGILState_Check()) {
225 fprintf(stderr, "PyGILState_Check failed!");
226 abort();
227 }
228
229 PyGILState_Release(state);
230
231 PyThread_release_lock(lock);
232
233 PyThread_exit_thread();
234}
235
236static int test_bpo20891(void)
237{
238 /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
239 calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
240 call PyEval_InitThreads() for us in this case. */
241 PyThread_type_lock lock = PyThread_allocate_lock();
242 if (!lock) {
243 fprintf(stderr, "PyThread_allocate_lock failed!");
244 return 1;
245 }
246
247 _testembed_Py_Initialize();
248
249 unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
250 if (thrd == PYTHREAD_INVALID_THREAD_ID) {
251 fprintf(stderr, "PyThread_start_new_thread failed!");
252 return 1;
253 }
254 PyThread_acquire_lock(lock, WAIT_LOCK);
255
256 Py_BEGIN_ALLOW_THREADS
257 /* wait until the thread exit */
258 PyThread_acquire_lock(lock, WAIT_LOCK);
259 Py_END_ALLOW_THREADS
260
261 PyThread_free_lock(lock);
262
263 return 0;
264}
265
Miss Islington (bot)3747dd12018-06-22 10:33:48 -0700266static int test_initialize_twice(void)
267{
268 _testembed_Py_Initialize();
269
270 /* bpo-33932: Calling Py_Initialize() twice should do nothing
271 * (and not crash!). */
272 Py_Initialize();
273
274 Py_Finalize();
275
276 return 0;
277}
278
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700279static int test_initialize_pymain(void)
280{
281 wchar_t *argv[] = {L"PYTHON", L"-c",
282 L"import sys; print(f'Py_Main() after Py_Initialize: sys.argv={sys.argv}')",
283 L"arg2"};
284 _testembed_Py_Initialize();
285
286 /* bpo-34008: Calling Py_Main() after Py_Initialize() must not crash */
287 Py_Main(Py_ARRAY_LENGTH(argv), argv);
288
289 Py_Finalize();
290
291 return 0;
292}
293
Victor Stinner9e87e772017-11-24 12:09:24 +0100294
Steve Dowerea74f0c2017-01-01 20:25:03 -0800295/* *********************************************************
296 * List of test cases and the function that implements it.
Serhiy Storchaka13ad3b72017-09-14 09:38:36 +0300297 *
Steve Dowerea74f0c2017-01-01 20:25:03 -0800298 * Names are compared case-sensitively with the first
299 * argument. If no match is found, or no first argument was
300 * provided, the names of all test cases are printed and
301 * the exit code will be -1.
302 *
303 * The int returned from test functions is used as the exit
304 * code, and test_capi treats all non-zero exit codes as a
Serhiy Storchaka13ad3b72017-09-14 09:38:36 +0300305 * failed test.
Steve Dowerea74f0c2017-01-01 20:25:03 -0800306 *********************************************************/
307struct TestCase
308{
309 const char *name;
310 int (*func)(void);
311};
312
313static struct TestCase TestCases[] = {
314 { "forced_io_encoding", test_forced_io_encoding },
315 { "repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters },
Victor Stinner9e87e772017-11-24 12:09:24 +0100316 { "pre_initialization_api", test_pre_initialization_api },
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700317 { "pre_initialization_sys_options", test_pre_initialization_sys_options },
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100318 { "bpo20891", test_bpo20891 },
Miss Islington (bot)3747dd12018-06-22 10:33:48 -0700319 { "initialize_twice", test_initialize_twice },
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700320 { "initialize_pymain", test_initialize_pymain },
Steve Dowerea74f0c2017-01-01 20:25:03 -0800321 { NULL, NULL }
322};
323
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000324int main(int argc, char *argv[])
325{
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000326 if (argc > 1) {
Steve Dowerea74f0c2017-01-01 20:25:03 -0800327 for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
328 if (strcmp(argv[1], tc->name) == 0)
329 return (*tc->func)();
330 }
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000331 }
Steve Dowerea74f0c2017-01-01 20:25:03 -0800332
333 /* No match found, or no test name provided, so display usage */
334 printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700335 "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
Steve Dowerea74f0c2017-01-01 20:25:03 -0800336 "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
337 for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
338 printf(" %s\n", tc->name);
339 }
340
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700341 /* Non-zero exit code will cause test_embed.py tests to fail.
Steve Dowerea74f0c2017-01-01 20:25:03 -0800342 This is intentional. */
343 return -1;
Antoine Pitrou8e605772011-04-25 21:21:07 +0200344}