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 
1109 static int _audit_hook_clear_count = 0;
1110 
_audit_hook(const char * event,PyObject * args,void * userdata)1111 static int _audit_hook(const char *event, PyObject *args, void *userdata)
1112 {
1113     assert(args && PyTuple_CheckExact(args));
1114     if (strcmp(event, "_testembed.raise") == 0) {
1115         PyErr_SetString(PyExc_RuntimeError, "Intentional error");
1116         return -1;
1117     } else if (strcmp(event, "_testembed.set") == 0) {
1118         if (!PyArg_ParseTuple(args, "n", userdata)) {
1119             return -1;
1120         }
1121         return 0;
1122     } else if (strcmp(event, "cpython._PySys_ClearAuditHooks") == 0) {
1123         _audit_hook_clear_count += 1;
1124     }
1125     return 0;
1126 }
1127 
_test_audit(Py_ssize_t setValue)1128 static int _test_audit(Py_ssize_t setValue)
1129 {
1130     Py_ssize_t sawSet = 0;
1131 
1132     Py_IgnoreEnvironmentFlag = 0;
1133     PySys_AddAuditHook(_audit_hook, &sawSet);
1134     _testembed_Py_Initialize();
1135 
1136     if (PySys_Audit("_testembed.raise", NULL) == 0) {
1137         printf("No error raised");
1138         return 1;
1139     }
1140     if (PySys_Audit("_testembed.nop", NULL) != 0) {
1141         printf("Nop event failed");
1142         /* Exception from above may still remain */
1143         PyErr_Clear();
1144         return 2;
1145     }
1146     if (!PyErr_Occurred()) {
1147         printf("Exception not preserved");
1148         return 3;
1149     }
1150     PyErr_Clear();
1151 
1152     if (PySys_Audit("_testembed.set", "n", setValue) != 0) {
1153         PyErr_Print();
1154         printf("Set event failed");
1155         return 4;
1156     }
1157 
1158     if (sawSet != 42) {
1159         printf("Failed to see *userData change\n");
1160         return 5;
1161     }
1162     return 0;
1163 }
1164 
test_audit(void)1165 static int test_audit(void)
1166 {
1167     int result = _test_audit(42);
1168     Py_Finalize();
1169     if (_audit_hook_clear_count != 1) {
1170         return 0x1000 | _audit_hook_clear_count;
1171     }
1172     return result;
1173 }
1174 
1175 static volatile int _audit_subinterpreter_interpreter_count = 0;
1176 
_audit_subinterpreter_hook(const char * event,PyObject * args,void * userdata)1177 static int _audit_subinterpreter_hook(const char *event, PyObject *args, void *userdata)
1178 {
1179     printf("%s\n", event);
1180     if (strcmp(event, "cpython.PyInterpreterState_New") == 0) {
1181         _audit_subinterpreter_interpreter_count += 1;
1182     }
1183     return 0;
1184 }
1185 
test_audit_subinterpreter(void)1186 static int test_audit_subinterpreter(void)
1187 {
1188     Py_IgnoreEnvironmentFlag = 0;
1189     PySys_AddAuditHook(_audit_subinterpreter_hook, NULL);
1190     _testembed_Py_Initialize();
1191 
1192     Py_NewInterpreter();
1193     Py_NewInterpreter();
1194     Py_NewInterpreter();
1195 
1196     Py_Finalize();
1197 
1198     switch (_audit_subinterpreter_interpreter_count) {
1199         case 3: return 0;
1200         case 0: return -1;
1201         default: return _audit_subinterpreter_interpreter_count;
1202     }
1203 }
1204 
1205 typedef struct {
1206     const char* expected;
1207     int exit;
1208 } AuditRunCommandTest;
1209 
_audit_hook_run(const char * eventName,PyObject * args,void * userData)1210 static int _audit_hook_run(const char *eventName, PyObject *args, void *userData)
1211 {
1212     AuditRunCommandTest *test = (AuditRunCommandTest*)userData;
1213     if (strcmp(eventName, test->expected)) {
1214         return 0;
1215     }
1216 
1217     if (test->exit) {
1218         PyObject *msg = PyUnicode_FromFormat("detected %s(%R)", eventName, args);
1219         if (msg) {
1220             printf("%s\n", PyUnicode_AsUTF8(msg));
1221             Py_DECREF(msg);
1222         }
1223         exit(test->exit);
1224     }
1225 
1226     PyErr_Format(PyExc_RuntimeError, "detected %s(%R)", eventName, args);
1227     return -1;
1228 }
1229 
test_audit_run_command(void)1230 static int test_audit_run_command(void)
1231 {
1232     AuditRunCommandTest test = {"cpython.run_command"};
1233     wchar_t *argv[] = {PROGRAM_NAME, L"-c", L"pass"};
1234 
1235     Py_IgnoreEnvironmentFlag = 0;
1236     PySys_AddAuditHook(_audit_hook_run, (void*)&test);
1237 
1238     return Py_Main(Py_ARRAY_LENGTH(argv), argv);
1239 }
1240 
test_audit_run_file(void)1241 static int test_audit_run_file(void)
1242 {
1243     AuditRunCommandTest test = {"cpython.run_file"};
1244     wchar_t *argv[] = {PROGRAM_NAME, L"filename.py"};
1245 
1246     Py_IgnoreEnvironmentFlag = 0;
1247     PySys_AddAuditHook(_audit_hook_run, (void*)&test);
1248 
1249     return Py_Main(Py_ARRAY_LENGTH(argv), argv);
1250 }
1251 
run_audit_run_test(int argc,wchar_t ** argv,void * test)1252 static int run_audit_run_test(int argc, wchar_t **argv, void *test)
1253 {
1254     PyConfig config;
1255     PyConfig_InitPythonConfig(&config);
1256 
1257     config.argv.length = argc;
1258     config.argv.items = argv;
1259     config.parse_argv = 1;
1260     config.program_name = argv[0];
1261     config.interactive = 1;
1262     config.isolated = 0;
1263     config.use_environment = 1;
1264     config.quiet = 1;
1265 
1266     PySys_AddAuditHook(_audit_hook_run, test);
1267 
1268     PyStatus status = Py_InitializeFromConfig(&config);
1269     if (PyStatus_Exception(status)) {
1270         Py_ExitStatusException(status);
1271     }
1272 
1273     return Py_RunMain();
1274 }
1275 
test_audit_run_interactivehook(void)1276 static int test_audit_run_interactivehook(void)
1277 {
1278     AuditRunCommandTest test = {"cpython.run_interactivehook", 10};
1279     wchar_t *argv[] = {PROGRAM_NAME};
1280     return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
1281 }
1282 
test_audit_run_startup(void)1283 static int test_audit_run_startup(void)
1284 {
1285     AuditRunCommandTest test = {"cpython.run_startup", 10};
1286     wchar_t *argv[] = {PROGRAM_NAME};
1287     return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
1288 }
1289 
test_audit_run_stdin(void)1290 static int test_audit_run_stdin(void)
1291 {
1292     AuditRunCommandTest test = {"cpython.run_stdin"};
1293     wchar_t *argv[] = {PROGRAM_NAME};
1294     return run_audit_run_test(Py_ARRAY_LENGTH(argv), argv, &test);
1295 }
1296 
test_init_read_set(void)1297 static int test_init_read_set(void)
1298 {
1299     PyStatus status;
1300     PyConfig config;
1301     PyConfig_InitPythonConfig(&config);
1302 
1303     status = PyConfig_SetBytesString(&config, &config.program_name,
1304                                      "./init_read_set");
1305     if (PyStatus_Exception(status)) {
1306         goto fail;
1307     }
1308 
1309     status = PyConfig_Read(&config);
1310     if (PyStatus_Exception(status)) {
1311         goto fail;
1312     }
1313 
1314     status = PyWideStringList_Insert(&config.module_search_paths,
1315                                      1, L"test_path_insert1");
1316     if (PyStatus_Exception(status)) {
1317         goto fail;
1318     }
1319 
1320     status = PyWideStringList_Append(&config.module_search_paths,
1321                                      L"test_path_append");
1322     if (PyStatus_Exception(status)) {
1323         goto fail;
1324     }
1325 
1326     /* override executable computed by PyConfig_Read() */
1327     config_set_string(&config, &config.executable, L"my_executable");
1328     init_from_config_clear(&config);
1329 
1330     dump_config();
1331     Py_Finalize();
1332     return 0;
1333 
1334 fail:
1335     Py_ExitStatusException(status);
1336 }
1337 
1338 
test_init_sys_add(void)1339 static int test_init_sys_add(void)
1340 {
1341     PySys_AddXOption(L"sysadd_xoption");
1342     PySys_AddXOption(L"faulthandler");
1343     PySys_AddWarnOption(L"ignore:::sysadd_warnoption");
1344 
1345     PyConfig config;
1346     PyConfig_InitPythonConfig(&config);
1347 
1348     wchar_t* argv[] = {
1349         L"python3",
1350         L"-W",
1351         L"ignore:::cmdline_warnoption",
1352         L"-X",
1353         L"cmdline_xoption",
1354     };
1355     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
1356     config.parse_argv = 1;
1357 
1358     PyStatus status;
1359     status = PyWideStringList_Append(&config.xoptions,
1360                                      L"config_xoption");
1361     if (PyStatus_Exception(status)) {
1362         goto fail;
1363     }
1364 
1365     status = PyWideStringList_Append(&config.warnoptions,
1366                                      L"ignore:::config_warnoption");
1367     if (PyStatus_Exception(status)) {
1368         goto fail;
1369     }
1370 
1371     config_set_program_name(&config);
1372     init_from_config_clear(&config);
1373 
1374     dump_config();
1375     Py_Finalize();
1376     return 0;
1377 
1378 fail:
1379     PyConfig_Clear(&config);
1380     Py_ExitStatusException(status);
1381 }
1382 
1383 
test_init_setpath(void)1384 static int test_init_setpath(void)
1385 {
1386     char *env = getenv("TESTPATH");
1387     if (!env) {
1388         fprintf(stderr, "missing TESTPATH env var\n");
1389         return 1;
1390     }
1391     wchar_t *path = Py_DecodeLocale(env, NULL);
1392     if (path == NULL) {
1393         fprintf(stderr, "failed to decode TESTPATH\n");
1394         return 1;
1395     }
1396     Py_SetPath(path);
1397     PyMem_RawFree(path);
1398     putenv("TESTPATH=");
1399 
1400     Py_Initialize();
1401     dump_config();
1402     Py_Finalize();
1403     return 0;
1404 }
1405 
1406 
test_init_setpath_config(void)1407 static int test_init_setpath_config(void)
1408 {
1409     PyPreConfig preconfig;
1410     PyPreConfig_InitPythonConfig(&preconfig);
1411 
1412     /* Explicitly preinitializes with Python preconfiguration to avoid
1413       Py_SetPath() implicit preinitialization with compat preconfiguration. */
1414     PyStatus status = Py_PreInitialize(&preconfig);
1415     if (PyStatus_Exception(status)) {
1416         Py_ExitStatusException(status);
1417     }
1418 
1419     char *env = getenv("TESTPATH");
1420     if (!env) {
1421         fprintf(stderr, "missing TESTPATH env var\n");
1422         return 1;
1423     }
1424     wchar_t *path = Py_DecodeLocale(env, NULL);
1425     if (path == NULL) {
1426         fprintf(stderr, "failed to decode TESTPATH\n");
1427         return 1;
1428     }
1429     Py_SetPath(path);
1430     PyMem_RawFree(path);
1431     putenv("TESTPATH=");
1432 
1433     PyConfig config;
1434     PyConfig_InitPythonConfig(&config);
1435 
1436     config_set_string(&config, &config.program_name, L"conf_program_name");
1437     config_set_string(&config, &config.executable, L"conf_executable");
1438     init_from_config_clear(&config);
1439 
1440     dump_config();
1441     Py_Finalize();
1442     return 0;
1443 }
1444 
1445 
test_init_setpythonhome(void)1446 static int test_init_setpythonhome(void)
1447 {
1448     char *env = getenv("TESTHOME");
1449     if (!env) {
1450         fprintf(stderr, "missing TESTHOME env var\n");
1451         return 1;
1452     }
1453     wchar_t *home = Py_DecodeLocale(env, NULL);
1454     if (home == NULL) {
1455         fprintf(stderr, "failed to decode TESTHOME\n");
1456         return 1;
1457     }
1458     Py_SetPythonHome(home);
1459     PyMem_RawFree(home);
1460     putenv("TESTHOME=");
1461 
1462     Py_Initialize();
1463     dump_config();
1464     Py_Finalize();
1465     return 0;
1466 }
1467 
1468 
test_init_warnoptions(void)1469 static int test_init_warnoptions(void)
1470 {
1471     putenv("PYTHONWARNINGS=ignore:::env1,ignore:::env2");
1472 
1473     PySys_AddWarnOption(L"ignore:::PySys_AddWarnOption1");
1474     PySys_AddWarnOption(L"ignore:::PySys_AddWarnOption2");
1475 
1476     PyConfig config;
1477     PyConfig_InitPythonConfig(&config);
1478 
1479     config.dev_mode = 1;
1480     config.bytes_warning = 1;
1481 
1482     config_set_program_name(&config);
1483 
1484     PyStatus status;
1485     status = PyWideStringList_Append(&config.warnoptions,
1486                                      L"ignore:::PyConfig_BeforeRead");
1487     if (PyStatus_Exception(status)) {
1488         Py_ExitStatusException(status);
1489     }
1490 
1491     wchar_t* argv[] = {
1492         L"python3",
1493         L"-Wignore:::cmdline1",
1494         L"-Wignore:::cmdline2"};
1495     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
1496     config.parse_argv = 1;
1497 
1498     status = PyConfig_Read(&config);
1499     if (PyStatus_Exception(status)) {
1500         Py_ExitStatusException(status);
1501     }
1502 
1503     status = PyWideStringList_Append(&config.warnoptions,
1504                                      L"ignore:::PyConfig_AfterRead");
1505     if (PyStatus_Exception(status)) {
1506         Py_ExitStatusException(status);
1507     }
1508 
1509     status = PyWideStringList_Insert(&config.warnoptions,
1510                                      0, L"ignore:::PyConfig_Insert0");
1511     if (PyStatus_Exception(status)) {
1512         Py_ExitStatusException(status);
1513     }
1514 
1515     init_from_config_clear(&config);
1516     dump_config();
1517     Py_Finalize();
1518     return 0;
1519 }
1520 
1521 
configure_init_main(PyConfig * config)1522 static void configure_init_main(PyConfig *config)
1523 {
1524     wchar_t* argv[] = {
1525         L"python3", L"-c",
1526         (L"import _testinternalcapi, json; "
1527          L"print(json.dumps(_testinternalcapi.get_configs()))"),
1528         L"arg2"};
1529 
1530     config->parse_argv = 1;
1531 
1532     config_set_argv(config, Py_ARRAY_LENGTH(argv), argv);
1533     config_set_string(config, &config->program_name, L"./python3");
1534 }
1535 
1536 
test_init_run_main(void)1537 static int test_init_run_main(void)
1538 {
1539     PyConfig config;
1540     PyConfig_InitPythonConfig(&config);
1541 
1542     configure_init_main(&config);
1543     init_from_config_clear(&config);
1544 
1545     return Py_RunMain();
1546 }
1547 
1548 
test_init_main(void)1549 static int test_init_main(void)
1550 {
1551     PyConfig config;
1552     PyConfig_InitPythonConfig(&config);
1553 
1554     configure_init_main(&config);
1555     config._init_main = 0;
1556     init_from_config_clear(&config);
1557 
1558     /* sys.stdout don't exist yet: it is created by _Py_InitializeMain() */
1559     int res = PyRun_SimpleString(
1560         "import sys; "
1561         "print('Run Python code before _Py_InitializeMain', "
1562                "file=sys.stderr)");
1563     if (res < 0) {
1564         exit(1);
1565     }
1566 
1567     PyStatus status = _Py_InitializeMain();
1568     if (PyStatus_Exception(status)) {
1569         Py_ExitStatusException(status);
1570     }
1571 
1572     return Py_RunMain();
1573 }
1574 
1575 
test_run_main(void)1576 static int test_run_main(void)
1577 {
1578     PyConfig config;
1579     PyConfig_InitPythonConfig(&config);
1580 
1581     wchar_t *argv[] = {L"python3", L"-c",
1582                        (L"import sys; "
1583                         L"print(f'Py_RunMain(): sys.argv={sys.argv}')"),
1584                        L"arg2"};
1585     config_set_argv(&config, Py_ARRAY_LENGTH(argv), argv);
1586     config_set_string(&config, &config.program_name, L"./python3");
1587     init_from_config_clear(&config);
1588 
1589     return Py_RunMain();
1590 }
1591 
1592 
1593 /* *********************************************************
1594  * List of test cases and the function that implements it.
1595  *
1596  * Names are compared case-sensitively with the first
1597  * argument. If no match is found, or no first argument was
1598  * provided, the names of all test cases are printed and
1599  * the exit code will be -1.
1600  *
1601  * The int returned from test functions is used as the exit
1602  * code, and test_capi treats all non-zero exit codes as a
1603  * failed test.
1604  *********************************************************/
1605 struct TestCase
1606 {
1607     const char *name;
1608     int (*func)(void);
1609 };
1610 
1611 static struct TestCase TestCases[] = {
1612     {"test_forced_io_encoding", test_forced_io_encoding},
1613     {"test_repeated_init_and_subinterpreters", test_repeated_init_and_subinterpreters},
1614     {"test_pre_initialization_api", test_pre_initialization_api},
1615     {"test_pre_initialization_sys_options", test_pre_initialization_sys_options},
1616     {"test_bpo20891", test_bpo20891},
1617     {"test_initialize_twice", test_initialize_twice},
1618     {"test_initialize_pymain", test_initialize_pymain},
1619     {"test_init_initialize_config", test_init_initialize_config},
1620     {"test_preinit_compat_config", test_preinit_compat_config},
1621     {"test_init_compat_config", test_init_compat_config},
1622     {"test_init_global_config", test_init_global_config},
1623     {"test_init_from_config", test_init_from_config},
1624     {"test_init_parse_argv", test_init_parse_argv},
1625     {"test_init_dont_parse_argv", test_init_dont_parse_argv},
1626     {"test_init_compat_env", test_init_compat_env},
1627     {"test_init_python_env", test_init_python_env},
1628     {"test_init_env_dev_mode", test_init_env_dev_mode},
1629     {"test_init_env_dev_mode_alloc", test_init_env_dev_mode_alloc},
1630     {"test_init_dont_configure_locale", test_init_dont_configure_locale},
1631     {"test_init_dev_mode", test_init_dev_mode},
1632     {"test_init_isolated_flag", test_init_isolated_flag},
1633     {"test_preinit_isolated_config", test_preinit_isolated_config},
1634     {"test_init_isolated_config", test_init_isolated_config},
1635     {"test_preinit_python_config", test_preinit_python_config},
1636     {"test_init_python_config", test_init_python_config},
1637     {"test_preinit_isolated1", test_preinit_isolated1},
1638     {"test_preinit_isolated2", test_preinit_isolated2},
1639     {"test_preinit_parse_argv", test_preinit_parse_argv},
1640     {"test_preinit_dont_parse_argv", test_preinit_dont_parse_argv},
1641     {"test_init_read_set", test_init_read_set},
1642     {"test_init_run_main", test_init_run_main},
1643     {"test_init_main", test_init_main},
1644     {"test_init_sys_add", test_init_sys_add},
1645     {"test_init_setpath", test_init_setpath},
1646     {"test_init_setpath_config", test_init_setpath_config},
1647     {"test_init_setpythonhome", test_init_setpythonhome},
1648     {"test_init_warnoptions", test_init_warnoptions},
1649     {"test_run_main", test_run_main},
1650 
1651     {"test_open_code_hook", test_open_code_hook},
1652     {"test_audit", test_audit},
1653     {"test_audit_subinterpreter", test_audit_subinterpreter},
1654     {"test_audit_run_command", test_audit_run_command},
1655     {"test_audit_run_file", test_audit_run_file},
1656     {"test_audit_run_interactivehook", test_audit_run_interactivehook},
1657     {"test_audit_run_startup", test_audit_run_startup},
1658     {"test_audit_run_stdin", test_audit_run_stdin},
1659     {NULL, NULL}
1660 };
1661 
main(int argc,char * argv[])1662 int main(int argc, char *argv[])
1663 {
1664     if (argc > 1) {
1665         for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
1666             if (strcmp(argv[1], tc->name) == 0)
1667                 return (*tc->func)();
1668         }
1669     }
1670 
1671     /* No match found, or no test name provided, so display usage */
1672     printf("Python " PY_VERSION " _testembed executable for embedded interpreter tests\n"
1673            "Normally executed via 'EmbeddingTests' in Lib/test/test_embed.py\n\n"
1674            "Usage: %s TESTNAME\n\nAll available tests:\n", argv[0]);
1675     for (struct TestCase *tc = TestCases; tc && tc->name; tc++) {
1676         printf("  %s\n", tc->name);
1677     }
1678 
1679     /* Non-zero exit code will cause test_embed.py tests to fail.
1680        This is intentional. */
1681     return -1;
1682 }
1683