• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #ifndef Py_BUILD_CORE_MODULE
2 #  define Py_BUILD_CORE_MODULE
3 #endif
4 
5 /* Always enable assertion (even in release mode) */
6 #undef NDEBUG
7 
8 #include <Python.h>
9 #include "pycore_initconfig.h"   /* _PyConfig_InitCompatConfig() */
10 #include "pycore_pystate.h"      /* _PyRuntime */
11 #include <Python.h>
12 #include "pythread.h"
13 #include <inttypes.h>
14 #include <stdio.h>
15 #include <wchar.h>
16 
17 /*********************************************************
18  * Embedded interpreter tests that need a custom exe
19  *
20  * Executed via 'EmbeddingTests' in Lib/test/test_capi.py
21  *********************************************************/
22 
23 /* Use path starting with "./" avoids a search along the PATH */
24 #define PROGRAM_NAME L"./_testembed"
25 
_testembed_Py_Initialize(void)26 static void _testembed_Py_Initialize(void)
27 {
28     Py_SetProgramName(PROGRAM_NAME);
29     Py_Initialize();
30 }
31 
32 
33 /*****************************************************
34  * Test repeated initialisation and subinterpreters
35  *****************************************************/
36 
print_subinterp(void)37 static void print_subinterp(void)
38 {
39     /* Output information about the interpreter in the format
40        expected in Lib/test/test_capi.py (test_subinterps). */
41     PyThreadState *ts = PyThreadState_Get();
42     PyInterpreterState *interp = ts->interp;
43     int64_t id = PyInterpreterState_GetID(interp);
44     printf("interp %" PRId64 " <0x%" PRIXPTR ">, thread state <0x%" PRIXPTR ">: ",
45             id, (uintptr_t)interp, (uintptr_t)ts);
46     fflush(stdout);
47     PyRun_SimpleString(
48         "import sys;"
49         "print('id(modules) =', id(sys.modules));"
50         "sys.stdout.flush()"
51     );
52 }
53 
test_repeated_init_and_subinterpreters(void)54 static int test_repeated_init_and_subinterpreters(void)
55 {
56     PyThreadState *mainstate, *substate;
57     PyGILState_STATE gilstate;
58     int i, j;
59 
60     for (i=0; i<15; i++) {
61         printf("--- Pass %d ---\n", i);
62         _testembed_Py_Initialize();
63         mainstate = PyThreadState_Get();
64 
65         PyEval_InitThreads();
66         PyEval_ReleaseThread(mainstate);
67 
68         gilstate = PyGILState_Ensure();
69         print_subinterp();
70         PyThreadState_Swap(NULL);
71 
72         for (j=0; j<3; j++) {
73             substate = Py_NewInterpreter();
74             print_subinterp();
75             Py_EndInterpreter(substate);
76         }
77 
78         PyThreadState_Swap(mainstate);
79         print_subinterp();
80         PyGILState_Release(gilstate);
81 
82         PyEval_RestoreThread(mainstate);
83         Py_Finalize();
84     }
85     return 0;
86 }
87 
88 /*****************************************************
89  * Test forcing a particular IO encoding
90  *****************************************************/
91 
check_stdio_details(const char * encoding,const char * errors)92 static void check_stdio_details(const char *encoding, const char * errors)
93 {
94     /* Output info for the test case to check */
95     if (encoding) {
96         printf("Expected encoding: %s\n", encoding);
97     } else {
98         printf("Expected encoding: default\n");
99     }
100     if (errors) {
101         printf("Expected errors: %s\n", errors);
102     } else {
103         printf("Expected errors: default\n");
104     }
105     fflush(stdout);
106     /* Force the given IO encoding */
107     Py_SetStandardStreamEncoding(encoding, errors);
108     _testembed_Py_Initialize();
109     PyRun_SimpleString(
110         "import sys;"
111         "print('stdin: {0.encoding}:{0.errors}'.format(sys.stdin));"
112         "print('stdout: {0.encoding}:{0.errors}'.format(sys.stdout));"
113         "print('stderr: {0.encoding}:{0.errors}'.format(sys.stderr));"
114         "sys.stdout.flush()"
115     );
116     Py_Finalize();
117 }
118 
test_forced_io_encoding(void)119 static int test_forced_io_encoding(void)
120 {
121     /* Check various combinations */
122     printf("--- Use defaults ---\n");
123     check_stdio_details(NULL, NULL);
124     printf("--- Set errors only ---\n");
125     check_stdio_details(NULL, "ignore");
126     printf("--- Set encoding only ---\n");
127     check_stdio_details("iso8859-1", NULL);
128     printf("--- Set encoding and errors ---\n");
129     check_stdio_details("iso8859-1", "replace");
130 
131     /* Check calling after initialization fails */
132     Py_Initialize();
133 
134     if (Py_SetStandardStreamEncoding(NULL, NULL) == 0) {
135         printf("Unexpected success calling Py_SetStandardStreamEncoding");
136     }
137     Py_Finalize();
138     return 0;
139 }
140 
141 /*********************************************************
142  * Test parts of the C-API that work before initialization
143  *********************************************************/
144 
145 /* The pre-initialization tests tend to break by segfaulting, so explicitly
146  * flushed progress messages make the broken API easier to find when they fail.
147  */
148 #define _Py_EMBED_PREINIT_CHECK(msg) \
149     do {printf(msg); fflush(stdout);} while (0);
150 
test_pre_initialization_api(void)151 static int test_pre_initialization_api(void)
152 {
153     /* the test doesn't support custom memory allocators */
154     putenv("PYTHONMALLOC=");
155 
156     /* Leading "./" ensures getpath.c can still find the standard library */
157     _Py_EMBED_PREINIT_CHECK("Checking Py_DecodeLocale\n");
158     wchar_t *program = Py_DecodeLocale("./spam", NULL);
159     if (program == NULL) {
160         fprintf(stderr, "Fatal error: cannot decode program name\n");
161         return 1;
162     }
163     _Py_EMBED_PREINIT_CHECK("Checking Py_SetProgramName\n");
164     Py_SetProgramName(program);
165 
166     _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
167     Py_Initialize();
168     _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
169     PyRun_SimpleString("import sys; "
170                        "print('sys.executable:', sys.executable)");
171     _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
172     Py_Finalize();
173 
174     _Py_EMBED_PREINIT_CHECK("Freeing memory allocated by Py_DecodeLocale\n");
175     PyMem_RawFree(program);
176     return 0;
177 }
178 
179 
180 /* bpo-33042: Ensure embedding apps can predefine sys module options */
test_pre_initialization_sys_options(void)181 static int test_pre_initialization_sys_options(void)
182 {
183     /* We allocate a couple of the options dynamically, and then delete
184      * them before calling Py_Initialize. This ensures the interpreter isn't
185      * relying on the caller to keep the passed in strings alive.
186      */
187     const wchar_t *static_warnoption = L"once";
188     const wchar_t *static_xoption = L"also_not_an_option=2";
189     size_t warnoption_len = wcslen(static_warnoption);
190     size_t xoption_len = wcslen(static_xoption);
191     wchar_t *dynamic_once_warnoption = \
192              (wchar_t *) calloc(warnoption_len+1, sizeof(wchar_t));
193     wchar_t *dynamic_xoption = \
194              (wchar_t *) calloc(xoption_len+1, sizeof(wchar_t));
195     wcsncpy(dynamic_once_warnoption, static_warnoption, warnoption_len+1);
196     wcsncpy(dynamic_xoption, static_xoption, xoption_len+1);
197 
198     _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption\n");
199     PySys_AddWarnOption(L"default");
200     _Py_EMBED_PREINIT_CHECK("Checking PySys_ResetWarnOptions\n");
201     PySys_ResetWarnOptions();
202     _Py_EMBED_PREINIT_CHECK("Checking PySys_AddWarnOption linked list\n");
203     PySys_AddWarnOption(dynamic_once_warnoption);
204     PySys_AddWarnOption(L"module");
205     PySys_AddWarnOption(L"default");
206     _Py_EMBED_PREINIT_CHECK("Checking PySys_AddXOption\n");
207     PySys_AddXOption(L"not_an_option=1");
208     PySys_AddXOption(dynamic_xoption);
209 
210     /* Delete the dynamic options early */
211     free(dynamic_once_warnoption);
212     dynamic_once_warnoption = NULL;
213     free(dynamic_xoption);
214     dynamic_xoption = NULL;
215 
216     _Py_EMBED_PREINIT_CHECK("Initializing interpreter\n");
217     _testembed_Py_Initialize();
218     _Py_EMBED_PREINIT_CHECK("Check sys module contents\n");
219     PyRun_SimpleString("import sys; "
220                        "print('sys.warnoptions:', sys.warnoptions); "
221                        "print('sys._xoptions:', sys._xoptions); "
222                        "warnings = sys.modules['warnings']; "
223                        "latest_filters = [f[0] for f in warnings.filters[:3]]; "
224                        "print('warnings.filters[:3]:', latest_filters)");
225     _Py_EMBED_PREINIT_CHECK("Finalizing interpreter\n");
226     Py_Finalize();
227 
228     return 0;
229 }
230 
231 
232 /* bpo-20891: Avoid race condition when initialising the GIL */
bpo20891_thread(void * lockp)233 static void bpo20891_thread(void *lockp)
234 {
235     PyThread_type_lock lock = *((PyThread_type_lock*)lockp);
236 
237     PyGILState_STATE state = PyGILState_Ensure();
238     if (!PyGILState_Check()) {
239         fprintf(stderr, "PyGILState_Check failed!");
240         abort();
241     }
242 
243     PyGILState_Release(state);
244 
245     PyThread_release_lock(lock);
246 
247     PyThread_exit_thread();
248 }
249 
test_bpo20891(void)250 static int test_bpo20891(void)
251 {
252     /* the test doesn't support custom memory allocators */
253     putenv("PYTHONMALLOC=");
254 
255     /* bpo-20891: Calling PyGILState_Ensure in a non-Python thread before
256        calling PyEval_InitThreads() must not crash. PyGILState_Ensure() must
257        call PyEval_InitThreads() for us in this case. */
258     PyThread_type_lock lock = PyThread_allocate_lock();
259     if (!lock) {
260         fprintf(stderr, "PyThread_allocate_lock failed!");
261         return 1;
262     }
263 
264     _testembed_Py_Initialize();
265 
266     unsigned long thrd = PyThread_start_new_thread(bpo20891_thread, &lock);
267     if (thrd == PYTHREAD_INVALID_THREAD_ID) {
268         fprintf(stderr, "PyThread_start_new_thread failed!");
269         return 1;
270     }
271     PyThread_acquire_lock(lock, WAIT_LOCK);
272 
273     Py_BEGIN_ALLOW_THREADS
274     /* wait until the thread exit */
275     PyThread_acquire_lock(lock, WAIT_LOCK);
276     Py_END_ALLOW_THREADS
277 
278     PyThread_free_lock(lock);
279 
280     return 0;
281 }
282 
test_initialize_twice(void)283 static int test_initialize_twice(void)
284 {
285     _testembed_Py_Initialize();
286 
287     /* bpo-33932: Calling Py_Initialize() twice should do nothing
288      * (and not crash!). */
289     Py_Initialize();
290 
291     Py_Finalize();
292 
293     return 0;
294 }
295 
test_initialize_pymain(void)296 static int test_initialize_pymain(void)
297 {
298     wchar_t *argv[] = {L"PYTHON", L"-c",
299                        (L"import sys; "
300                         L"print(f'Py_Main() after Py_Initialize: "
301                         L"sys.argv={sys.argv}')"),
302                        L"arg2"};
303     _testembed_Py_Initialize();
304 
305     /* bpo-34008: Calling Py_Main() after Py_Initialize() must not crash */
306     Py_Main(Py_ARRAY_LENGTH(argv), argv);
307 
308     Py_Finalize();
309 
310     return 0;
311 }
312 
313 
314 static void
dump_config(void)315 dump_config(void)
316 {
317     (void) PyRun_SimpleStringFlags(
318         "import _testinternalcapi, json; "
319         "print(json.dumps(_testinternalcapi.get_configs()))",
320         0);
321 }
322 
323 
test_init_initialize_config(void)324 static int test_init_initialize_config(void)
325 {
326     _testembed_Py_Initialize();
327     dump_config();
328     Py_Finalize();
329     return 0;
330 }
331 
332 
config_set_string(PyConfig * config,wchar_t ** config_str,const wchar_t * str)333 static void config_set_string(PyConfig *config, wchar_t **config_str, const wchar_t *str)
334 {
335     PyStatus status = PyConfig_SetString(config, config_str, str);
336     if (PyStatus_Exception(status)) {
337         PyConfig_Clear(config);
338         Py_ExitStatusException(status);
339     }
340 }
341 
342 
config_set_argv(PyConfig * config,Py_ssize_t argc,wchar_t * const * argv)343 static void config_set_argv(PyConfig *config, Py_ssize_t argc, wchar_t * const *argv)
344 {
345     PyStatus status = PyConfig_SetArgv(config, argc, argv);
346     if (PyStatus_Exception(status)) {
347         PyConfig_Clear(config);
348         Py_ExitStatusException(status);
349     }
350 }
351 
352 
353 static void
config_set_wide_string_list(PyConfig * config,PyWideStringList * list,Py_ssize_t length,wchar_t ** items)354 config_set_wide_string_list(PyConfig *config, PyWideStringList *list,
355                             Py_ssize_t length, wchar_t **items)
356 {
357     PyStatus status = PyConfig_SetWideStringList(config, list, length, items);
358     if (PyStatus_Exception(status)) {
359         PyConfig_Clear(config);
360         Py_ExitStatusException(status);
361     }
362 }
363 
364 
config_set_program_name(PyConfig * config)365 static void config_set_program_name(PyConfig *config)
366 {
367     const wchar_t *program_name = PROGRAM_NAME;
368     config_set_string(config, &config->program_name, program_name);
369 }
370 
371 
init_from_config_clear(PyConfig * config)372 static void init_from_config_clear(PyConfig *config)
373 {
374     PyStatus status = Py_InitializeFromConfig(config);
375     PyConfig_Clear(config);
376     if (PyStatus_Exception(status)) {
377         Py_ExitStatusException(status);
378     }
379 }
380 
381 
check_init_compat_config(int preinit)382 static int check_init_compat_config(int preinit)
383 {
384     PyStatus status;
385 
386     if (preinit) {
387         PyPreConfig preconfig;
388         _PyPreConfig_InitCompatConfig(&preconfig);
389 
390         status = Py_PreInitialize(&preconfig);
391         if (PyStatus_Exception(status)) {
392             Py_ExitStatusException(status);
393         }
394     }
395 
396     PyConfig config;
397     _PyConfig_InitCompatConfig(&config);
398 
399     config_set_program_name(&config);
400     init_from_config_clear(&config);
401 
402     dump_config();
403     Py_Finalize();
404     return 0;
405 }
406 
407 
test_preinit_compat_config(void)408 static int test_preinit_compat_config(void)
409 {
410     return check_init_compat_config(1);
411 }
412 
413 
test_init_compat_config(void)414 static int test_init_compat_config(void)
415 {
416     return check_init_compat_config(0);
417 }
418 
419 
test_init_global_config(void)420 static int test_init_global_config(void)
421 {
422     /* FIXME: test Py_IgnoreEnvironmentFlag */
423 
424     putenv("PYTHONUTF8=0");
425     Py_UTF8Mode = 1;
426 
427     /* Test initialization from global configuration variables (Py_xxx) */
428     Py_SetProgramName(L"./globalvar");
429 
430     /* Py_IsolatedFlag is not tested */
431     Py_NoSiteFlag = 1;
432     Py_BytesWarningFlag = 1;
433 
434     putenv("PYTHONINSPECT=");
435     Py_InspectFlag = 1;
436 
437     putenv("PYTHONOPTIMIZE=0");
438     Py_InteractiveFlag = 1;
439 
440     putenv("PYTHONDEBUG=0");
441     Py_OptimizeFlag = 2;
442 
443     /* Py_DebugFlag is not tested */
444 
445     putenv("PYTHONDONTWRITEBYTECODE=");
446     Py_DontWriteBytecodeFlag = 1;
447 
448     putenv("PYTHONVERBOSE=0");
449     Py_VerboseFlag = 1;
450 
451     Py_QuietFlag = 1;
452     Py_NoUserSiteDirectory = 1;
453 
454     putenv("PYTHONUNBUFFERED=");
455     Py_UnbufferedStdioFlag = 1;
456 
457     Py_FrozenFlag = 1;
458 
459     /* FIXME: test Py_LegacyWindowsFSEncodingFlag */
460     /* FIXME: test Py_LegacyWindowsStdioFlag */
461 
462     Py_Initialize();
463     dump_config();
464     Py_Finalize();
465     return 0;
466 }
467 
468 
test_init_from_config(void)469 static int test_init_from_config(void)
470 {
471     PyPreConfig preconfig;
472     _PyPreConfig_InitCompatConfig(&preconfig);
473 
474     putenv("PYTHONMALLOC=malloc_debug");
475     preconfig.allocator = PYMEM_ALLOCATOR_MALLOC;
476 
477     putenv("PYTHONUTF8=0");
478     Py_UTF8Mode = 0;
479     preconfig.utf8_mode = 1;
480 
481     PyStatus status = Py_PreInitialize(&preconfig);
482     if (PyStatus_Exception(status)) {
483         Py_ExitStatusException(status);
484     }
485 
486     PyConfig config;
487     _PyConfig_InitCompatConfig(&config);
488 
489     config.install_signal_handlers = 0;
490 
491     /* FIXME: test use_environment */
492 
493     putenv("PYTHONHASHSEED=42");
494     config.use_hash_seed = 1;
495     config.hash_seed = 123;
496 
497     /* dev_mode=1 is tested in test_init_dev_mode() */
498 
499     putenv("PYTHONFAULTHANDLER=");
500     config.faulthandler = 1;
501 
502     putenv("PYTHONTRACEMALLOC=0");
503     config.tracemalloc = 2;
504 
505     putenv("PYTHONPROFILEIMPORTTIME=0");
506     config.import_time = 1;
507 
508     config.show_ref_count = 1;
509     config.show_alloc_count = 1;
510     /* FIXME: test dump_refs: bpo-34223 */
511 
512     putenv("PYTHONMALLOCSTATS=0");
513     config.malloc_stats = 1;
514 
515     putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
516     config_set_string(&config, &config.pycache_prefix, L"conf_pycache_prefix");
517 
518     Py_SetProgramName(L"./globalvar");
519     config_set_string(&config, &config.program_name, L"./conf_program_name");
520 
521     wchar_t* argv[] = {
522         L"python3",
523         L"-W",
524         L"cmdline_warnoption",
525         L"-X",
526         L"cmdline_xoption",
527         L"-c",
528         L"pass",
529         L"arg2",
530     };
531     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
532     config.parse_argv = 1;
533 
534     wchar_t* xoptions[3] = {
535         L"config_xoption1=3",
536         L"config_xoption2=",
537         L"config_xoption3",
538     };
539     config_set_wide_string_list(&config, &config.xoptions,
540                                 Py_ARRAY_LENGTH(xoptions), xoptions);
541 
542     wchar_t* warnoptions[1] = {
543         L"config_warnoption",
544     };
545     config_set_wide_string_list(&config, &config.warnoptions,
546                                 Py_ARRAY_LENGTH(warnoptions), warnoptions);
547 
548     /* FIXME: test pythonpath_env */
549     /* FIXME: test home */
550     /* FIXME: test path config: module_search_path .. dll_path */
551 
552     putenv("PYTHONVERBOSE=0");
553     Py_VerboseFlag = 0;
554     config.verbose = 1;
555 
556     Py_NoSiteFlag = 0;
557     config.site_import = 0;
558 
559     Py_BytesWarningFlag = 0;
560     config.bytes_warning = 1;
561 
562     putenv("PYTHONINSPECT=");
563     Py_InspectFlag = 0;
564     config.inspect = 1;
565 
566     Py_InteractiveFlag = 0;
567     config.interactive = 1;
568 
569     putenv("PYTHONOPTIMIZE=0");
570     Py_OptimizeFlag = 1;
571     config.optimization_level = 2;
572 
573     /* FIXME: test parser_debug */
574 
575     putenv("PYTHONDONTWRITEBYTECODE=");
576     Py_DontWriteBytecodeFlag = 0;
577     config.write_bytecode = 0;
578 
579     Py_QuietFlag = 0;
580     config.quiet = 1;
581 
582     config.configure_c_stdio = 1;
583 
584     putenv("PYTHONUNBUFFERED=");
585     Py_UnbufferedStdioFlag = 0;
586     config.buffered_stdio = 0;
587 
588     putenv("PYTHONIOENCODING=cp424");
589     Py_SetStandardStreamEncoding("ascii", "ignore");
590 #ifdef MS_WINDOWS
591     /* Py_SetStandardStreamEncoding() sets Py_LegacyWindowsStdioFlag to 1.
592        Force it to 0 through the config. */
593     config.legacy_windows_stdio = 0;
594 #endif
595     config_set_string(&config, &config.stdio_encoding, L"iso8859-1");
596     config_set_string(&config, &config.stdio_errors, L"replace");
597 
598     putenv("PYTHONNOUSERSITE=");
599     Py_NoUserSiteDirectory = 0;
600     config.user_site_directory = 0;
601 
602     config_set_string(&config, &config.check_hash_pycs_mode, L"always");
603 
604     Py_FrozenFlag = 0;
605     config.pathconfig_warnings = 0;
606 
607     init_from_config_clear(&config);
608 
609     dump_config();
610     Py_Finalize();
611     return 0;
612 }
613 
614 
check_init_parse_argv(int parse_argv)615 static int check_init_parse_argv(int parse_argv)
616 {
617     PyConfig config;
618     PyConfig_InitPythonConfig(&config);
619 
620     config.parse_argv = parse_argv;
621 
622     wchar_t* argv[] = {
623         L"./argv0",
624         L"-E",
625         L"-c",
626         L"pass",
627         L"arg1",
628         L"-v",
629         L"arg3",
630     };
631     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
632     init_from_config_clear(&config);
633 
634     dump_config();
635     Py_Finalize();
636     return 0;
637 }
638 
639 
test_init_parse_argv(void)640 static int test_init_parse_argv(void)
641 {
642     return check_init_parse_argv(1);
643 }
644 
645 
test_init_dont_parse_argv(void)646 static int test_init_dont_parse_argv(void)
647 {
648     return check_init_parse_argv(0);
649 }
650 
651 
set_most_env_vars(void)652 static void set_most_env_vars(void)
653 {
654     putenv("PYTHONHASHSEED=42");
655     putenv("PYTHONMALLOC=malloc");
656     putenv("PYTHONTRACEMALLOC=2");
657     putenv("PYTHONPROFILEIMPORTTIME=1");
658     putenv("PYTHONMALLOCSTATS=1");
659     putenv("PYTHONUTF8=1");
660     putenv("PYTHONVERBOSE=1");
661     putenv("PYTHONINSPECT=1");
662     putenv("PYTHONOPTIMIZE=2");
663     putenv("PYTHONDONTWRITEBYTECODE=1");
664     putenv("PYTHONUNBUFFERED=1");
665     putenv("PYTHONPYCACHEPREFIX=env_pycache_prefix");
666     putenv("PYTHONNOUSERSITE=1");
667     putenv("PYTHONFAULTHANDLER=1");
668     putenv("PYTHONIOENCODING=iso8859-1:replace");
669 }
670 
671 
set_all_env_vars(void)672 static void set_all_env_vars(void)
673 {
674     set_most_env_vars();
675 
676     putenv("PYTHONWARNINGS=EnvVar");
677     putenv("PYTHONPATH=/my/path");
678 }
679 
680 
test_init_compat_env(void)681 static int test_init_compat_env(void)
682 {
683     /* Test initialization from environment variables */
684     Py_IgnoreEnvironmentFlag = 0;
685     set_all_env_vars();
686     _testembed_Py_Initialize();
687     dump_config();
688     Py_Finalize();
689     return 0;
690 }
691 
692 
test_init_python_env(void)693 static int test_init_python_env(void)
694 {
695     set_all_env_vars();
696 
697     PyConfig config;
698     PyConfig_InitPythonConfig(&config);
699 
700     config_set_program_name(&config);
701     init_from_config_clear(&config);
702 
703     dump_config();
704     Py_Finalize();
705     return 0;
706 }
707 
708 
set_all_env_vars_dev_mode(void)709 static void set_all_env_vars_dev_mode(void)
710 {
711     putenv("PYTHONMALLOC=");
712     putenv("PYTHONFAULTHANDLER=");
713     putenv("PYTHONDEVMODE=1");
714 }
715 
716 
test_init_env_dev_mode(void)717 static int test_init_env_dev_mode(void)
718 {
719     /* Test initialization from environment variables */
720     Py_IgnoreEnvironmentFlag = 0;
721     set_all_env_vars_dev_mode();
722     _testembed_Py_Initialize();
723     dump_config();
724     Py_Finalize();
725     return 0;
726 }
727 
728 
test_init_env_dev_mode_alloc(void)729 static int test_init_env_dev_mode_alloc(void)
730 {
731     /* Test initialization from environment variables */
732     Py_IgnoreEnvironmentFlag = 0;
733     set_all_env_vars_dev_mode();
734     putenv("PYTHONMALLOC=malloc");
735     _testembed_Py_Initialize();
736     dump_config();
737     Py_Finalize();
738     return 0;
739 }
740 
741 
test_init_isolated_flag(void)742 static int test_init_isolated_flag(void)
743 {
744     /* Test PyConfig.isolated=1 */
745     PyConfig config;
746     PyConfig_InitPythonConfig(&config);
747 
748     Py_IsolatedFlag = 0;
749     config.isolated = 1;
750 
751     config_set_program_name(&config);
752     set_all_env_vars();
753     init_from_config_clear(&config);
754 
755     dump_config();
756     Py_Finalize();
757     return 0;
758 }
759 
760 
761 /* PyPreConfig.isolated=1, PyConfig.isolated=0 */
test_preinit_isolated1(void)762 static int test_preinit_isolated1(void)
763 {
764     PyPreConfig preconfig;
765     _PyPreConfig_InitCompatConfig(&preconfig);
766 
767     preconfig.isolated = 1;
768 
769     PyStatus status = Py_PreInitialize(&preconfig);
770     if (PyStatus_Exception(status)) {
771         Py_ExitStatusException(status);
772     }
773 
774     PyConfig config;
775     _PyConfig_InitCompatConfig(&config);
776 
777     config_set_program_name(&config);
778     set_all_env_vars();
779     init_from_config_clear(&config);
780 
781     dump_config();
782     Py_Finalize();
783     return 0;
784 }
785 
786 
787 /* PyPreConfig.isolated=0, PyConfig.isolated=1 */
test_preinit_isolated2(void)788 static int test_preinit_isolated2(void)
789 {
790     PyPreConfig preconfig;
791     _PyPreConfig_InitCompatConfig(&preconfig);
792 
793     preconfig.isolated = 0;
794 
795     PyStatus status = Py_PreInitialize(&preconfig);
796     if (PyStatus_Exception(status)) {
797         Py_ExitStatusException(status);
798     }
799 
800     /* Test PyConfig.isolated=1 */
801     PyConfig config;
802     _PyConfig_InitCompatConfig(&config);
803 
804     Py_IsolatedFlag = 0;
805     config.isolated = 1;
806 
807     config_set_program_name(&config);
808     set_all_env_vars();
809     init_from_config_clear(&config);
810 
811     dump_config();
812     Py_Finalize();
813     return 0;
814 }
815 
816 
test_preinit_dont_parse_argv(void)817 static int test_preinit_dont_parse_argv(void)
818 {
819     PyPreConfig preconfig;
820     PyPreConfig_InitIsolatedConfig(&preconfig);
821 
822     preconfig.isolated = 0;
823 
824     /* -X dev must be ignored by isolated preconfiguration */
825     wchar_t *argv[] = {L"python3",
826                        L"-E",
827                        L"-I",
828                        L"-X", L"dev",
829                        L"-X", L"utf8",
830                        L"script.py"};
831     PyStatus status = Py_PreInitializeFromArgs(&preconfig,
832                                                Py_ARRAY_LENGTH(argv), argv);
833     if (PyStatus_Exception(status)) {
834         Py_ExitStatusException(status);
835     }
836 
837     PyConfig config;
838     PyConfig_InitIsolatedConfig(&config);
839 
840     config.isolated = 0;
841 
842     /* Pre-initialize implicitly using argv: make sure that -X dev
843        is used to configure the allocation in preinitialization */
844     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
845     config_set_program_name(&config);
846     init_from_config_clear(&config);
847 
848     dump_config();
849     Py_Finalize();
850     return 0;
851 }
852 
853 
test_preinit_parse_argv(void)854 static int test_preinit_parse_argv(void)
855 {
856     PyConfig config;
857     PyConfig_InitPythonConfig(&config);
858 
859     /* Pre-initialize implicitly using argv: make sure that -X dev
860        is used to configure the allocation in preinitialization */
861     wchar_t *argv[] = {L"python3", L"-X", L"dev", L"script.py"};
862     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
863     config_set_program_name(&config);
864     init_from_config_clear(&config);
865 
866     dump_config();
867     Py_Finalize();
868     return 0;
869 }
870 
871 
872 
873 
set_all_global_config_variables(void)874 static void set_all_global_config_variables(void)
875 {
876     Py_IsolatedFlag = 0;
877     Py_IgnoreEnvironmentFlag = 0;
878     Py_BytesWarningFlag = 2;
879     Py_InspectFlag = 1;
880     Py_InteractiveFlag = 1;
881     Py_OptimizeFlag = 1;
882     Py_DebugFlag = 1;
883     Py_VerboseFlag = 1;
884     Py_QuietFlag = 1;
885     Py_FrozenFlag = 0;
886     Py_UnbufferedStdioFlag = 1;
887     Py_NoSiteFlag = 1;
888     Py_DontWriteBytecodeFlag = 1;
889     Py_NoUserSiteDirectory = 1;
890 #ifdef MS_WINDOWS
891     Py_LegacyWindowsStdioFlag = 1;
892 #endif
893 }
894 
895 
check_preinit_isolated_config(int preinit)896 static int check_preinit_isolated_config(int preinit)
897 {
898     PyStatus status;
899     PyPreConfig *rt_preconfig;
900 
901     /* environment variables must be ignored */
902     set_all_env_vars();
903 
904     /* global configuration variables must be ignored */
905     set_all_global_config_variables();
906 
907     if (preinit) {
908         PyPreConfig preconfig;
909         PyPreConfig_InitIsolatedConfig(&preconfig);
910 
911         status = Py_PreInitialize(&preconfig);
912         if (PyStatus_Exception(status)) {
913             Py_ExitStatusException(status);
914         }
915 
916         rt_preconfig = &_PyRuntime.preconfig;
917         assert(rt_preconfig->isolated == 1);
918         assert(rt_preconfig->use_environment == 0);
919     }
920 
921     PyConfig config;
922     PyConfig_InitIsolatedConfig(&config);
923 
924     config_set_program_name(&config);
925     init_from_config_clear(&config);
926 
927     rt_preconfig = &_PyRuntime.preconfig;
928     assert(rt_preconfig->isolated == 1);
929     assert(rt_preconfig->use_environment == 0);
930 
931     dump_config();
932     Py_Finalize();
933     return 0;
934 }
935 
936 
test_preinit_isolated_config(void)937 static int test_preinit_isolated_config(void)
938 {
939     return check_preinit_isolated_config(1);
940 }
941 
942 
test_init_isolated_config(void)943 static int test_init_isolated_config(void)
944 {
945     return check_preinit_isolated_config(0);
946 }
947 
948 
check_init_python_config(int preinit)949 static int check_init_python_config(int preinit)
950 {
951     /* global configuration variables must be ignored */
952     set_all_global_config_variables();
953     Py_IsolatedFlag = 1;
954     Py_IgnoreEnvironmentFlag = 1;
955     Py_FrozenFlag = 1;
956     Py_UnbufferedStdioFlag = 1;
957     Py_NoSiteFlag = 1;
958     Py_DontWriteBytecodeFlag = 1;
959     Py_NoUserSiteDirectory = 1;
960 #ifdef MS_WINDOWS
961     Py_LegacyWindowsStdioFlag = 1;
962 #endif
963 
964     if (preinit) {
965         PyPreConfig preconfig;
966         PyPreConfig_InitPythonConfig(&preconfig);
967 
968         PyStatus status = Py_PreInitialize(&preconfig);
969         if (PyStatus_Exception(status)) {
970             Py_ExitStatusException(status);
971         }
972     }
973 
974     PyConfig config;
975     PyConfig_InitPythonConfig(&config);
976 
977     config_set_program_name(&config);
978     init_from_config_clear(&config);
979 
980     dump_config();
981     Py_Finalize();
982     return 0;
983 }
984 
985 
test_preinit_python_config(void)986 static int test_preinit_python_config(void)
987 {
988     return check_init_python_config(1);
989 }
990 
991 
test_init_python_config(void)992 static int test_init_python_config(void)
993 {
994     return check_init_python_config(0);
995 }
996 
997 
test_init_dont_configure_locale(void)998 static int test_init_dont_configure_locale(void)
999 {
1000     PyPreConfig preconfig;
1001     PyPreConfig_InitPythonConfig(&preconfig);
1002 
1003     preconfig.configure_locale = 0;
1004     preconfig.coerce_c_locale = 1;
1005     preconfig.coerce_c_locale_warn = 1;
1006 
1007     PyStatus status = Py_PreInitialize(&preconfig);
1008     if (PyStatus_Exception(status)) {
1009         Py_ExitStatusException(status);
1010     }
1011 
1012     PyConfig config;
1013     PyConfig_InitPythonConfig(&config);
1014 
1015     config_set_program_name(&config);
1016     init_from_config_clear(&config);
1017 
1018     dump_config();
1019     Py_Finalize();
1020     return 0;
1021 }
1022 
1023 
test_init_dev_mode(void)1024 static int test_init_dev_mode(void)
1025 {
1026     PyConfig config;
1027     PyConfig_InitPythonConfig(&config);
1028 
1029     putenv("PYTHONFAULTHANDLER=");
1030     putenv("PYTHONMALLOC=");
1031     config.dev_mode = 1;
1032     config_set_program_name(&config);
1033     init_from_config_clear(&config);
1034 
1035     dump_config();
1036     Py_Finalize();
1037     return 0;
1038 }
1039 
_open_code_hook(PyObject * path,void * data)1040 static PyObject *_open_code_hook(PyObject *path, void *data)
1041 {
1042     if (PyUnicode_CompareWithASCIIString(path, "$$test-filename") == 0) {
1043         return PyLong_FromVoidPtr(data);
1044     }
1045     PyObject *io = PyImport_ImportModule("_io");
1046     if (!io) {
1047         return NULL;
1048     }
1049     return PyObject_CallMethod(io, "open", "Os", path, "rb");
1050 }
1051 
test_open_code_hook(void)1052 static int test_open_code_hook(void)
1053 {
1054     int result = 0;
1055 
1056     /* Provide a hook */
1057     result = PyFile_SetOpenCodeHook(_open_code_hook, &result);
1058     if (result) {
1059         printf("Failed to set hook\n");
1060         return 1;
1061     }
1062     /* A second hook should fail */
1063     result = PyFile_SetOpenCodeHook(_open_code_hook, &result);
1064     if (!result) {
1065         printf("Should have failed to set second hook\n");
1066         return 2;
1067     }
1068 
1069     Py_IgnoreEnvironmentFlag = 0;
1070     _testembed_Py_Initialize();
1071     result = 0;
1072 
1073     PyObject *r = PyFile_OpenCode("$$test-filename");
1074     if (!r) {
1075         PyErr_Print();
1076         result = 3;
1077     } else {
1078         void *cmp = PyLong_AsVoidPtr(r);
1079         Py_DECREF(r);
1080         if (cmp != &result) {
1081             printf("Did not get expected result from hook\n");
1082             result = 4;
1083         }
1084     }
1085 
1086     if (!result) {
1087         PyObject *io = PyImport_ImportModule("_io");
1088         PyObject *r = io
1089             ? PyObject_CallMethod(io, "open_code", "s", "$$test-filename")
1090             : NULL;
1091         if (!r) {
1092             PyErr_Print();
1093             result = 5;
1094         } else {
1095             void *cmp = PyLong_AsVoidPtr(r);
1096             Py_DECREF(r);
1097             if (cmp != &result) {
1098                 printf("Did not get expected result from hook\n");
1099                 result = 6;
1100             }
1101         }
1102         Py_XDECREF(io);
1103     }
1104 
1105     Py_Finalize();
1106     return result;
1107 }
1108 
_audit_hook(const char * event,PyObject * args,void * userdata)1109 static int _audit_hook(const char *event, PyObject *args, void *userdata)
1110 {
1111     if (strcmp(event, "_testembed.raise") == 0) {
1112         PyErr_SetString(PyExc_RuntimeError, "Intentional error");
1113         return -1;
1114     } else if (strcmp(event, "_testembed.set") == 0) {
1115         if (!PyArg_ParseTuple(args, "n", userdata)) {
1116             return -1;
1117         }
1118         return 0;
1119     }
1120     return 0;
1121 }
1122 
_test_audit(Py_ssize_t setValue)1123 static int _test_audit(Py_ssize_t setValue)
1124 {
1125     Py_ssize_t sawSet = 0;
1126 
1127     Py_IgnoreEnvironmentFlag = 0;
1128     PySys_AddAuditHook(_audit_hook, &sawSet);
1129     _testembed_Py_Initialize();
1130 
1131     if (PySys_Audit("_testembed.raise", NULL) == 0) {
1132         printf("No error raised");
1133         return 1;
1134     }
1135     if (PySys_Audit("_testembed.nop", NULL) != 0) {
1136         printf("Nop event failed");
1137         /* Exception from above may still remain */
1138         PyErr_Clear();
1139         return 2;
1140     }
1141     if (!PyErr_Occurred()) {
1142         printf("Exception not preserved");
1143         return 3;
1144     }
1145     PyErr_Clear();
1146 
1147     if (PySys_Audit("_testembed.set", "n", setValue) != 0) {
1148         PyErr_Print();
1149         printf("Set event failed");
1150         return 4;
1151     }
1152 
1153     if (sawSet != 42) {
1154         printf("Failed to see *userData change\n");
1155         return 5;
1156     }
1157     return 0;
1158 }
1159 
test_audit(void)1160 static int test_audit(void)
1161 {
1162     int result = _test_audit(42);
1163     Py_Finalize();
1164     return result;
1165 }
1166 
1167 static volatile int _audit_subinterpreter_interpreter_count = 0;
1168 
_audit_subinterpreter_hook(const char * event,PyObject * args,void * userdata)1169 static int _audit_subinterpreter_hook(const char *event, PyObject *args, void *userdata)
1170 {
1171     printf("%s\n", event);
1172     if (strcmp(event, "cpython.PyInterpreterState_New") == 0) {
1173         _audit_subinterpreter_interpreter_count += 1;
1174     }
1175     return 0;
1176 }
1177 
test_audit_subinterpreter(void)1178 static int test_audit_subinterpreter(void)
1179 {
1180     Py_IgnoreEnvironmentFlag = 0;
1181     PySys_AddAuditHook(_audit_subinterpreter_hook, NULL);
1182     _testembed_Py_Initialize();
1183 
1184     Py_NewInterpreter();
1185     Py_NewInterpreter();
1186     Py_NewInterpreter();
1187 
1188     Py_Finalize();
1189 
1190     switch (_audit_subinterpreter_interpreter_count) {
1191         case 3: return 0;
1192         case 0: return -1;
1193         default: return _audit_subinterpreter_interpreter_count;
1194     }
1195 }
1196 
1197 typedef struct {
1198     const char* expected;
1199     int exit;
1200 } AuditRunCommandTest;
1201 
_audit_hook_run(const char * eventName,PyObject * args,void * userData)1202 static int _audit_hook_run(const char *eventName, PyObject *args, void *userData)
1203 {
1204     AuditRunCommandTest *test = (AuditRunCommandTest*)userData;
1205     if (strcmp(eventName, test->expected)) {
1206         return 0;
1207     }
1208 
1209     if (test->exit) {
1210         PyObject *msg = PyUnicode_FromFormat("detected %s(%R)", eventName, args);
1211         if (msg) {
1212             printf("%s\n", PyUnicode_AsUTF8(msg));
1213             Py_DECREF(msg);
1214         }
1215         exit(test->exit);
1216     }
1217 
1218     PyErr_Format(PyExc_RuntimeError, "detected %s(%R)", eventName, args);
1219     return -1;
1220 }
1221 
test_audit_run_command(void)1222 static int test_audit_run_command(void)
1223 {
1224     AuditRunCommandTest test = {"cpython.run_command"};
1225     wchar_t *argv[] = {PROGRAM_NAME, L"-c", L"pass"};
1226 
1227     Py_IgnoreEnvironmentFlag = 0;
1228     PySys_AddAuditHook(_audit_hook_run, (void*)&test);
1229 
1230     return Py_Main(Py_ARRAY_LENGTH(argv), argv);
1231 }
1232 
test_audit_run_file(void)1233 static int test_audit_run_file(void)
1234 {
1235     AuditRunCommandTest test = {"cpython.run_file"};
1236     wchar_t *argv[] = {PROGRAM_NAME, L"filename.py"};
1237 
1238     Py_IgnoreEnvironmentFlag = 0;
1239     PySys_AddAuditHook(_audit_hook_run, (void*)&test);
1240 
1241     return Py_Main(Py_ARRAY_LENGTH(argv), argv);
1242 }
1243 
run_audit_run_test(int argc,wchar_t ** argv,void * test)1244 static int run_audit_run_test(int argc, wchar_t **argv, void *test)
1245 {
1246     PyConfig config;
1247     PyConfig_InitPythonConfig(&config);
1248 
1249     config.argv.length = argc;
1250     config.argv.items = argv;
1251     config.parse_argv = 1;
1252     config.program_name = argv[0];
1253     config.interactive = 1;
1254     config.isolated = 0;
1255     config.use_environment = 1;
1256     config.quiet = 1;
1257 
1258     PySys_AddAuditHook(_audit_hook_run, test);
1259 
1260     PyStatus status = Py_InitializeFromConfig(&config);
1261     if (PyStatus_Exception(status)) {
1262         Py_ExitStatusException(status);
1263     }
1264 
1265     return Py_RunMain();
1266 }
1267 
test_audit_run_interactivehook(void)1268 static int test_audit_run_interactivehook(void)
1269 {
1270     AuditRunCommandTest test = {"cpython.run_interactivehook", 10};
1271     wchar_t *argv[] = {PROGRAM_NAME};
1272     return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
1273 }
1274 
test_audit_run_startup(void)1275 static int test_audit_run_startup(void)
1276 {
1277     AuditRunCommandTest test = {"cpython.run_startup", 10};
1278     wchar_t *argv[] = {PROGRAM_NAME};
1279     return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
1280 }
1281 
test_audit_run_stdin(void)1282 static int test_audit_run_stdin(void)
1283 {
1284     AuditRunCommandTest test = {"cpython.run_stdin"};
1285     wchar_t *argv[] = {PROGRAM_NAME};
1286     return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
1287 }
1288 
test_init_read_set(void)1289 static int test_init_read_set(void)
1290 {
1291     PyStatus status;
1292     PyConfig config;
1293     PyConfig_InitPythonConfig(&config);
1294 
1295     status = PyConfig_SetBytesString(&config, &config.program_name,
1296                                      "./init_read_set");
1297     if (PyStatus_Exception(status)) {
1298         goto fail;
1299     }
1300 
1301     status = PyConfig_Read(&config);
1302     if (PyStatus_Exception(status)) {
1303         goto fail;
1304     }
1305 
1306     status = PyWideStringList_Insert(&config.module_search_paths,
1307                                      1, L"test_path_insert1");
1308     if (PyStatus_Exception(status)) {
1309         goto fail;
1310     }
1311 
1312     status = PyWideStringList_Append(&config.module_search_paths,
1313                                      L"test_path_append");
1314     if (PyStatus_Exception(status)) {
1315         goto fail;
1316     }
1317 
1318     /* override executable computed by PyConfig_Read() */
1319     config_set_string(&config, &config.executable, L"my_executable");
1320     init_from_config_clear(&config);
1321 
1322     dump_config();
1323     Py_Finalize();
1324     return 0;
1325 
1326 fail:
1327     Py_ExitStatusException(status);
1328 }
1329 
1330 
test_init_sys_add(void)1331 static int test_init_sys_add(void)
1332 {
1333     PySys_AddXOption(L"sysadd_xoption");
1334     PySys_AddXOption(L"faulthandler");
1335     PySys_AddWarnOption(L"ignore:::sysadd_warnoption");
1336 
1337     PyConfig config;
1338     PyConfig_InitPythonConfig(&config);
1339 
1340     wchar_t* argv[] = {
1341         L"python3",
1342         L"-W",
1343         L"ignore:::cmdline_warnoption",
1344         L"-X",
1345         L"cmdline_xoption",
1346     };
1347     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
1348     config.parse_argv = 1;
1349 
1350     PyStatus status;
1351     status = PyWideStringList_Append(&config.xoptions,
1352                                      L"config_xoption");
1353     if (PyStatus_Exception(status)) {
1354         goto fail;
1355     }
1356 
1357     status = PyWideStringList_Append(&config.warnoptions,
1358                                      L"ignore:::config_warnoption");
1359     if (PyStatus_Exception(status)) {
1360         goto fail;
1361     }
1362 
1363     config_set_program_name(&config);
1364     init_from_config_clear(&config);
1365 
1366     dump_config();
1367     Py_Finalize();
1368     return 0;
1369 
1370 fail:
1371     PyConfig_Clear(&config);
1372     Py_ExitStatusException(status);
1373 }
1374 
1375 
test_init_setpath(void)1376 static int test_init_setpath(void)
1377 {
1378     char *env = getenv("TESTPATH");
1379     if (!env) {
1380         fprintf(stderr, "missing TESTPATH env var\n");
1381         return 1;
1382     }
1383     wchar_t *path = Py_DecodeLocale(env, NULL);
1384     if (path == NULL) {
1385         fprintf(stderr, "failed to decode TESTPATH\n");
1386         return 1;
1387     }
1388     Py_SetPath(path);
1389     PyMem_RawFree(path);
1390     putenv("TESTPATH=");
1391 
1392     Py_Initialize();
1393     dump_config();
1394     Py_Finalize();
1395     return 0;
1396 }
1397 
1398 
test_init_setpath_config(void)1399 static int test_init_setpath_config(void)
1400 {
1401     PyPreConfig preconfig;
1402     PyPreConfig_InitPythonConfig(&preconfig);
1403 
1404     /* Explicitly preinitializes with Python preconfiguration to avoid
1405       Py_SetPath() implicit preinitialization with compat preconfiguration. */
1406     PyStatus status = Py_PreInitialize(&preconfig);
1407     if (PyStatus_Exception(status)) {
1408         Py_ExitStatusException(status);
1409     }
1410 
1411     char *env = getenv("TESTPATH");
1412     if (!env) {
1413         fprintf(stderr, "missing TESTPATH env var\n");
1414         return 1;
1415     }
1416     wchar_t *path = Py_DecodeLocale(env, NULL);
1417     if (path == NULL) {
1418         fprintf(stderr, "failed to decode TESTPATH\n");
1419         return 1;
1420     }
1421     Py_SetPath(path);
1422     PyMem_RawFree(path);
1423     putenv("TESTPATH=");
1424 
1425     PyConfig config;
1426     PyConfig_InitPythonConfig(&config);
1427 
1428     config_set_string(&config, &config.program_name, L"conf_program_name");
1429     config_set_string(&config, &config.executable, L"conf_executable");
1430     init_from_config_clear(&config);
1431 
1432     dump_config();
1433     Py_Finalize();
1434     return 0;
1435 }
1436 
1437 
test_init_setpythonhome(void)1438 static int test_init_setpythonhome(void)
1439 {
1440     char *env = getenv("TESTHOME");
1441     if (!env) {
1442         fprintf(stderr, "missing TESTHOME env var\n");
1443         return 1;
1444     }
1445     wchar_t *home = Py_DecodeLocale(env, NULL);
1446     if (home == NULL) {
1447         fprintf(stderr, "failed to decode TESTHOME\n");
1448         return 1;
1449     }
1450     Py_SetPythonHome(home);
1451     PyMem_RawFree(home);
1452     putenv("TESTHOME=");
1453 
1454     Py_Initialize();
1455     dump_config();
1456     Py_Finalize();
1457     return 0;
1458 }
1459 
1460 
test_init_warnoptions(void)1461 static int test_init_warnoptions(void)
1462 {
1463     putenv("PYTHONWARNINGS=ignore:::env1,ignore:::env2");
1464 
1465     PySys_AddWarnOption(L"ignore:::PySys_AddWarnOption1");
1466     PySys_AddWarnOption(L"ignore:::PySys_AddWarnOption2");
1467 
1468     PyConfig config;
1469     PyConfig_InitPythonConfig(&config);
1470 
1471     config.dev_mode = 1;
1472     config.bytes_warning = 1;
1473 
1474     config_set_program_name(&config);
1475 
1476     PyStatus status;
1477     status = PyWideStringList_Append(&config.warnoptions,
1478                                      L"ignore:::PyConfig_BeforeRead");
1479     if (PyStatus_Exception(status)) {
1480         Py_ExitStatusException(status);
1481     }
1482 
1483     wchar_t* argv[] = {
1484         L"python3",
1485         L"-Wignore:::cmdline1",
1486         L"-Wignore:::cmdline2"};
1487     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
1488     config.parse_argv = 1;
1489 
1490     status = PyConfig_Read(&config);
1491     if (PyStatus_Exception(status)) {
1492         Py_ExitStatusException(status);
1493     }
1494 
1495     status = PyWideStringList_Append(&config.warnoptions,
1496                                      L"ignore:::PyConfig_AfterRead");
1497     if (PyStatus_Exception(status)) {
1498         Py_ExitStatusException(status);
1499     }
1500 
1501     status = PyWideStringList_Insert(&config.warnoptions,
1502                                      0, L"ignore:::PyConfig_Insert0");
1503     if (PyStatus_Exception(status)) {
1504         Py_ExitStatusException(status);
1505     }
1506 
1507     init_from_config_clear(&config);
1508     dump_config();
1509     Py_Finalize();
1510     return 0;
1511 }
1512 
1513 
configure_init_main(PyConfig * config)1514 static void configure_init_main(PyConfig *config)
1515 {
1516     wchar_t* argv[] = {
1517         L"python3", L"-c",
1518         (L"import _testinternalcapi, json; "
1519          L"print(json.dumps(_testinternalcapi.get_configs()))"),
1520         L"arg2"};
1521 
1522     config->parse_argv = 1;
1523 
1524     config_set_argv(config, Py_ARRAY_LENGTH(argv), argv);
1525     config_set_string(config, &config->program_name, L"./python3");
1526 }
1527 
1528 
test_init_run_main(void)1529 static int test_init_run_main(void)
1530 {
1531     PyConfig config;
1532     PyConfig_InitPythonConfig(&config);
1533 
1534     configure_init_main(&config);
1535     init_from_config_clear(&config);
1536 
1537     return Py_RunMain();
1538 }
1539 
1540 
test_init_main(void)1541 static int test_init_main(void)
1542 {
1543     PyConfig config;
1544     PyConfig_InitPythonConfig(&config);
1545 
1546     configure_init_main(&config);
1547     config._init_main = 0;
1548     init_from_config_clear(&config);
1549 
1550     /* sys.stdout don't exist yet: it is created by _Py_InitializeMain() */
1551     int res = PyRun_SimpleString(
1552         "import sys; "
1553         "print('Run Python code before _Py_InitializeMain', "
1554                "file=sys.stderr)");
1555     if (res < 0) {
1556         exit(1);
1557     }
1558 
1559     PyStatus status = _Py_InitializeMain();
1560     if (PyStatus_Exception(status)) {
1561         Py_ExitStatusException(status);
1562     }
1563 
1564     return Py_RunMain();
1565 }
1566 
1567 
test_run_main(void)1568 static int test_run_main(void)
1569 {
1570     PyConfig config;
1571     PyConfig_InitPythonConfig(&config);
1572 
1573     wchar_t *argv[] = {L"python3", L"-c",
1574                        (L"import sys; "
1575                         L"print(f'Py_RunMain(): sys.argv={sys.argv}')"),
1576                        L"arg2"};
1577     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
1578     config_set_string(&config, &config.program_name, L"./python3");
1579     init_from_config_clear(&config);
1580 
1581     return Py_RunMain();
1582 }
1583 
1584 
1585 /* *********************************************************
1586  * List of test cases and the function that implements it.
1587  *
1588  * Names are compared case-sensitively with the first
1589  * argument. If no match is found, or no first argument was
1590  * provided, the names of all test cases are printed and
1591  * the exit code will be -1.
1592  *
1593  * The int returned from test functions is used as the exit
1594  * code, and test_capi treats all non-zero exit codes as a
1595  * failed test.
1596  *********************************************************/
1597 struct TestCase
1598 {
1599     const char *name;
1600     int (*func)(void);
1601 };
1602 
1603 static struct TestCase TestCases[] = {
1604     {"test_forced_io_encoding", test_forced_io_encoding},
1605     {"test_repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters},
1606     {"test_pre_initialization_api", test_pre_initialization_api},
1607     {"test_pre_initialization_sys_options", test_pre_initialization_sys_options},
1608     {"test_bpo20891", test_bpo20891},
1609     {"test_initialize_twice", test_initialize_twice},
1610     {"test_initialize_pymain", test_initialize_pymain},
1611     {"test_init_initialize_config", test_init_initialize_config},
1612     {"test_preinit_compat_config", test_preinit_compat_config},
1613     {"test_init_compat_config", test_init_compat_config},
1614     {"test_init_global_config", test_init_global_config},
1615     {"test_init_from_config", test_init_from_config},
1616     {"test_init_parse_argv", test_init_parse_argv},
1617     {"test_init_dont_parse_argv", test_init_dont_parse_argv},
1618     {"test_init_compat_env", test_init_compat_env},
1619     {"test_init_python_env", test_init_python_env},
1620     {"test_init_env_dev_mode", test_init_env_dev_mode},
1621     {"test_init_env_dev_mode_alloc", test_init_env_dev_mode_alloc},
1622     {"test_init_dont_configure_locale", test_init_dont_configure_locale},
1623     {"test_init_dev_mode", test_init_dev_mode},
1624     {"test_init_isolated_flag", test_init_isolated_flag},
1625     {"test_preinit_isolated_config", test_preinit_isolated_config},
1626     {"test_init_isolated_config", test_init_isolated_config},
1627     {"test_preinit_python_config", test_preinit_python_config},
1628     {"test_init_python_config", test_init_python_config},
1629     {"test_preinit_isolated1", test_preinit_isolated1},
1630     {"test_preinit_isolated2", test_preinit_isolated2},
1631     {"test_preinit_parse_argv", test_preinit_parse_argv},
1632     {"test_preinit_dont_parse_argv", test_preinit_dont_parse_argv},
1633     {"test_init_read_set", test_init_read_set},
1634     {"test_init_run_main", test_init_run_main},
1635     {"test_init_main", test_init_main},
1636     {"test_init_sys_add", test_init_sys_add},
1637     {"test_init_setpath", test_init_setpath},
1638     {"test_init_setpath_config", test_init_setpath_config},
1639     {"test_init_setpythonhome", test_init_setpythonhome},
1640     {"test_init_warnoptions", test_init_warnoptions},
1641     {"test_run_main", test_run_main},
1642 
1643     {"test_open_code_hook", test_open_code_hook},
1644     {"test_audit", test_audit},
1645     {"test_audit_subinterpreter", test_audit_subinterpreter},
1646     {"test_audit_run_command", test_audit_run_command},
1647     {"test_audit_run_file", test_audit_run_file},
1648     {"test_audit_run_interactivehook", test_audit_run_interactivehook},
1649     {"test_audit_run_startup", test_audit_run_startup},
1650     {"test_audit_run_stdin", test_audit_run_stdin},
1651     {NULL, NULL}
1652 };
1653 
main(int argc,char * argv[])1654 int main(int argc, char *argv[])
1655 {
1656     if (argc > 1) {
1657         for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
1658             if (strcmp(argv[1], tc->name) == 0)
1659                 return (*tc->func)();
1660         }
1661     }
1662 
1663     /* No match found, or no test name provided, so display usage */
1664     printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
1665            "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
1666            "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
1667     for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
1668         printf("  %s\n", tc->name);
1669     }
1670 
1671     /* Non-zero exit code will cause test_embed.py tests to fail.
1672        This is intentional. */
1673     return -1;
1674 }
1675