blob: 09b7bf6d94fc8ae35e5eef0ed3c869fff454ddb2 [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{
169 /* We allocate a couple of the option dynamically, and then delete
170 * them before calling Py_Initialize. This ensures the interpreter isn't
171 * relying on the caller to keep the passed in strings alive.
172 */
173 wchar_t *static_warnoption = L"once";
174 wchar_t *static_xoption = L"also_not_an_option=2";
175 size_t warnoption_len = wcslen(static_warnoption);
176 size_t xoption_len = wcslen(static_xoption);
177 wchar_t *dynamic_once_warnoption = calloc(warnoption_len+1, sizeof(wchar_t));
178 wchar_t *dynamic_xoption = calloc(xoption_len+1, sizeof(wchar_t));
179 wcsncpy(dynamic_once_warnoption, static_warnoption, warnoption_len+1);
180 wcsncpy(dynamic_xoption, static_xoption, xoption_len+1);
181
182 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption\n");
183 PySys_AddWarnOption(L"default");
184 _Py_EMBED_PREINIT_CHECK("Checking PySys_ResetWarnOptions\n");
185 PySys_ResetWarnOptions();
186 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption linked list\n");
187 PySys_AddWarnOption(dynamic_once_warnoption);
188 PySys_AddWarnOption(L"module");
189 PySys_AddWarnOption(L"default");
190 _Py_EMBED_PREINIT_CHECK("Checking PySys_AddXOption\n");
191 PySys_AddXOption(L"not_an_option=1");
192 PySys_AddXOption(dynamic_xoption);
193
194 /* Delete the dynamic options early */
195 free(dynamic_once_warnoption);
196 dynamic_once_warnoption = NULL;
197 free(dynamic_xoption);
198 dynamic_xoption = NULL;
199
200 _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
201 _testembed_Py_Initialize();
202 _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
203 PyRun_SimpleString("import sys; "
204 "print('sys.warnoptions:', sys.warnoptions); "
205 "print('sys._xoptions:', sys._xoptions); "
206 "warnings = sys.modules['warnings']; "
207 "latest_filters = [f[0] for f in warnings.filters[:3]]; "
208 "print('warnings.filters[:3]:', latest_filters)");
209 _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
210 Py_Finalize();
211
212 return 0;
213}
214
215
216/* bpo-20891: Avoid race condition when initialising the GIL */
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100217static void bpo20891_thread(void *lockp)
218{
219 PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
220
221 PyGILState_STATE state = PyGILState_Ensure();
222 if (!PyGILState_Check()) {
223 fprintf(stderr, "PyGILState_Check failed!");
224 abort();
225 }
226
227 PyGILState_Release(state);
228
229 PyThread_release_lock(lock);
230
231 PyThread_exit_thread();
232}
233
234static int test_bpo20891(void)
235{
236 /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
237 calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
238 call PyEval_InitThreads() for us in this case. */
239 PyThread_type_lock lock = PyThread_allocate_lock();
240 if (!lock) {
241 fprintf(stderr, "PyThread_allocate_lock failed!");
242 return 1;
243 }
244
245 _testembed_Py_Initialize();
246
247 unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
248 if (thrd == PYTHREAD_INVALID_THREAD_ID) {
249 fprintf(stderr, "PyThread_start_new_thread failed!");
250 return 1;
251 }
252 PyThread_acquire_lock(lock, WAIT_LOCK);
253
254 Py_BEGIN_ALLOW_THREADS
255 /* wait until the thread exit */
256 PyThread_acquire_lock(lock, WAIT_LOCK);
257 Py_END_ALLOW_THREADS
258
259 PyThread_free_lock(lock);
260
261 return 0;
262}
263
Victor Stinner9e87e772017-11-24 12:09:24 +0100264
Steve Dowerea74f0c2017-01-01 20:25:03 -0800265/* *********************************************************
266 * List of test cases and the function that implements it.
Serhiy Storchaka13ad3b72017-09-14 09:38:36 +0300267 *
Steve Dowerea74f0c2017-01-01 20:25:03 -0800268 * Names are compared case-sensitively with the first
269 * argument. If no match is found, or no first argument was
270 * provided, the names of all test cases are printed and
271 * the exit code will be -1.
272 *
273 * The int returned from test functions is used as the exit
274 * code, and test_capi treats all non-zero exit codes as a
Serhiy Storchaka13ad3b72017-09-14 09:38:36 +0300275 * failed test.
Steve Dowerea74f0c2017-01-01 20:25:03 -0800276 *********************************************************/
277struct TestCase
278{
279 const char *name;
280 int (*func)(void);
281};
282
283static struct TestCase TestCases[] = {
284 { "forced_io_encoding", test_forced_io_encoding },
285 { "repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters },
Victor Stinner9e87e772017-11-24 12:09:24 +0100286 { "pre_initialization_api", test_pre_initialization_api },
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700287 { "pre_initialization_sys_options", test_pre_initialization_sys_options },
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100288 { "bpo20891", test_bpo20891 },
Steve Dowerea74f0c2017-01-01 20:25:03 -0800289 { NULL, NULL }
290};
291
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000292int main(int argc, char *argv[])
293{
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000294 if (argc > 1) {
Steve Dowerea74f0c2017-01-01 20:25:03 -0800295 for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
296 if (strcmp(argv[1], tc->name) == 0)
297 return (*tc->func)();
298 }
Nick Coghlan7d270ee2013-10-17 22:35:35 +1000299 }
Steve Dowerea74f0c2017-01-01 20:25:03 -0800300
301 /* No match found, or no test name provided, so display usage */
302 printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700303 "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
Steve Dowerea74f0c2017-01-01 20:25:03 -0800304 "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
305 for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
306 printf(" %s\n", tc->name);
307 }
308
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -0700309 /* Non-zero exit code will cause test_embed.py tests to fail.
Steve Dowerea74f0c2017-01-01 20:25:03 -0800310 This is intentional. */
311 return -1;
Antoine Pitrou8e605772011-04-25 21:21:07 +0200312}