1 /* Python interpreter top-level routines, including init/exit */
2
3 #include "Python.h"
4
5 #include "Python-ast.h"
6 #undef Yield /* undefine macro conflicting with <winbase.h> */
7 #include "pycore_ceval.h"
8 #include "pycore_context.h"
9 #include "pycore_initconfig.h"
10 #include "pycore_fileutils.h"
11 #include "pycore_hamt.h"
12 #include "pycore_pathconfig.h"
13 #include "pycore_pylifecycle.h"
14 #include "pycore_pymem.h"
15 #include "pycore_pystate.h"
16 #include "pycore_traceback.h"
17 #include "grammar.h"
18 #include "node.h"
19 #include "token.h"
20 #include "parsetok.h"
21 #include "errcode.h"
22 #include "code.h"
23 #include "symtable.h"
24 #include "ast.h"
25 #include "marshal.h"
26 #include "osdefs.h"
27 #include <locale.h>
28
29 #ifdef HAVE_SIGNAL_H
30 #include <signal.h>
31 #endif
32
33 #ifdef MS_WINDOWS
34 #include "malloc.h" /* for alloca */
35 #endif
36
37 #ifdef HAVE_LANGINFO_H
38 #include <langinfo.h>
39 #endif
40
41 #ifdef MS_WINDOWS
42 #undef BYTE
43 #include "windows.h"
44
45 extern PyTypeObject PyWindowsConsoleIO_Type;
46 #define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
47 #endif
48
49 _Py_IDENTIFIER(flush);
50 _Py_IDENTIFIER(name);
51 _Py_IDENTIFIER(stdin);
52 _Py_IDENTIFIER(stdout);
53 _Py_IDENTIFIER(stderr);
54 _Py_IDENTIFIER(threading);
55
56 #ifdef __cplusplus
57 extern "C" {
58 #endif
59
60 extern grammar _PyParser_Grammar; /* From graminit.c */
61
62 /* Forward */
63 static PyStatus add_main_module(PyInterpreterState *interp);
64 static PyStatus init_import_size(void);
65 static PyStatus init_sys_streams(PyInterpreterState *interp);
66 static PyStatus init_signals(void);
67 static void call_py_exitfuncs(PyInterpreterState *);
68 static void wait_for_thread_shutdown(void);
69 static void call_ll_exitfuncs(_PyRuntimeState *runtime);
70
71 int _Py_UnhandledKeyboardInterrupt = 0;
72 _PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
73 static int runtime_initialized = 0;
74
75 PyStatus
_PyRuntime_Initialize(void)76 _PyRuntime_Initialize(void)
77 {
78 /* XXX We only initialize once in the process, which aligns with
79 the static initialization of the former globals now found in
80 _PyRuntime. However, _PyRuntime *should* be initialized with
81 every Py_Initialize() call, but doing so breaks the runtime.
82 This is because the runtime state is not properly finalized
83 currently. */
84 if (runtime_initialized) {
85 return _PyStatus_OK();
86 }
87 runtime_initialized = 1;
88
89 return _PyRuntimeState_Init(&_PyRuntime);
90 }
91
92 void
_PyRuntime_Finalize(void)93 _PyRuntime_Finalize(void)
94 {
95 _PyRuntimeState_Fini(&_PyRuntime);
96 runtime_initialized = 0;
97 }
98
99 int
_Py_IsFinalizing(void)100 _Py_IsFinalizing(void)
101 {
102 return _PyRuntime.finalizing != NULL;
103 }
104
105 /* Hack to force loading of object files */
106 int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
107 PyOS_mystrnicmp; /* Python/pystrcmp.o */
108
109 /* PyModule_GetWarningsModule is no longer necessary as of 2.6
110 since _warnings is builtin. This API should not be used. */
111 PyObject *
PyModule_GetWarningsModule(void)112 PyModule_GetWarningsModule(void)
113 {
114 return PyImport_ImportModule("warnings");
115 }
116
117
118 /* APIs to access the initialization flags
119 *
120 * Can be called prior to Py_Initialize.
121 */
122
123 int
_Py_IsCoreInitialized(void)124 _Py_IsCoreInitialized(void)
125 {
126 return _PyRuntime.core_initialized;
127 }
128
129 int
Py_IsInitialized(void)130 Py_IsInitialized(void)
131 {
132 return _PyRuntime.initialized;
133 }
134
135
136 /* Global initializations. Can be undone by Py_FinalizeEx(). Don't
137 call this twice without an intervening Py_FinalizeEx() call. When
138 initializations fail, a fatal error is issued and the function does
139 not return. On return, the first thread and interpreter state have
140 been created.
141
142 Locking: you must hold the interpreter lock while calling this.
143 (If the lock has not yet been initialized, that's equivalent to
144 having the lock, but you cannot use multiple threads.)
145
146 */
147
148 static PyStatus
init_importlib(PyInterpreterState * interp,PyObject * sysmod)149 init_importlib(PyInterpreterState *interp, PyObject *sysmod)
150 {
151 PyObject *importlib;
152 PyObject *impmod;
153 PyObject *value;
154 int verbose = interp->config.verbose;
155
156 /* Import _importlib through its frozen version, _frozen_importlib. */
157 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
158 return _PyStatus_ERR("can't import _frozen_importlib");
159 }
160 else if (verbose) {
161 PySys_FormatStderr("import _frozen_importlib # frozen\n");
162 }
163 importlib = PyImport_AddModule("_frozen_importlib");
164 if (importlib == NULL) {
165 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
166 }
167 interp->importlib = importlib;
168 Py_INCREF(interp->importlib);
169
170 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
171 if (interp->import_func == NULL)
172 return _PyStatus_ERR("__import__ not found");
173 Py_INCREF(interp->import_func);
174
175 /* Import the _imp module */
176 impmod = PyInit__imp();
177 if (impmod == NULL) {
178 return _PyStatus_ERR("can't import _imp");
179 }
180 else if (verbose) {
181 PySys_FormatStderr("import _imp # builtin\n");
182 }
183 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
184 return _PyStatus_ERR("can't save _imp to sys.modules");
185 }
186
187 /* Install importlib as the implementation of import */
188 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
189 if (value == NULL) {
190 PyErr_Print();
191 return _PyStatus_ERR("importlib install failed");
192 }
193 Py_DECREF(value);
194 Py_DECREF(impmod);
195
196 return _PyStatus_OK();
197 }
198
199 static PyStatus
init_importlib_external(PyInterpreterState * interp)200 init_importlib_external(PyInterpreterState *interp)
201 {
202 PyObject *value;
203 value = PyObject_CallMethod(interp->importlib,
204 "_install_external_importers", "");
205 if (value == NULL) {
206 PyErr_Print();
207 return _PyStatus_ERR("external importer setup failed");
208 }
209 Py_DECREF(value);
210 return _PyImportZip_Init(interp);
211 }
212
213 /* Helper functions to better handle the legacy C locale
214 *
215 * The legacy C locale assumes ASCII as the default text encoding, which
216 * causes problems not only for the CPython runtime, but also other
217 * components like GNU readline.
218 *
219 * Accordingly, when the CLI detects it, it attempts to coerce it to a
220 * more capable UTF-8 based alternative as follows:
221 *
222 * if (_Py_LegacyLocaleDetected()) {
223 * _Py_CoerceLegacyLocale();
224 * }
225 *
226 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
227 *
228 * Locale coercion also impacts the default error handler for the standard
229 * streams: while the usual default is "strict", the default for the legacy
230 * C locale and for any of the coercion target locales is "surrogateescape".
231 */
232
233 int
_Py_LegacyLocaleDetected(int warn)234 _Py_LegacyLocaleDetected(int warn)
235 {
236 #ifndef MS_WINDOWS
237 if (!warn) {
238 const char *locale_override = getenv("LC_ALL");
239 if (locale_override != NULL && *locale_override != '\0') {
240 /* Don't coerce C locale if the LC_ALL environment variable
241 is set */
242 return 0;
243 }
244 }
245
246 /* On non-Windows systems, the C locale is considered a legacy locale */
247 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
248 * the POSIX locale as a simple alias for the C locale, so
249 * we may also want to check for that explicitly.
250 */
251 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
252 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
253 #else
254 /* Windows uses code pages instead of locales, so no locale is legacy */
255 return 0;
256 #endif
257 }
258
259 static const char *_C_LOCALE_WARNING =
260 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
261 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
262 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
263 "locales is recommended.\n";
264
265 static void
emit_stderr_warning_for_legacy_locale(_PyRuntimeState * runtime)266 emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
267 {
268 const PyPreConfig *preconfig = &runtime->preconfig;
269 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
270 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
271 }
272 }
273
274 typedef struct _CandidateLocale {
275 const char *locale_name; /* The locale to try as a coercion target */
276 } _LocaleCoercionTarget;
277
278 static _LocaleCoercionTarget _TARGET_LOCALES[] = {
279 {"C.UTF-8"},
280 {"C.utf8"},
281 {"UTF-8"},
282 {NULL}
283 };
284
285
286 int
_Py_IsLocaleCoercionTarget(const char * ctype_loc)287 _Py_IsLocaleCoercionTarget(const char *ctype_loc)
288 {
289 const _LocaleCoercionTarget *target = NULL;
290 for (target = _TARGET_LOCALES; target->locale_name; target++) {
291 if (strcmp(ctype_loc, target->locale_name) == 0) {
292 return 1;
293 }
294 }
295 return 0;
296 }
297
298
299 #ifdef PY_COERCE_C_LOCALE
300 static const char C_LOCALE_COERCION_WARNING[] =
301 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
302 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
303
304 static int
_coerce_default_locale_settings(int warn,const _LocaleCoercionTarget * target)305 _coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
306 {
307 const char *newloc = target->locale_name;
308
309 /* Reset locale back to currently configured defaults */
310 _Py_SetLocaleFromEnv(LC_ALL);
311
312 /* Set the relevant locale environment variable */
313 if (setenv("LC_CTYPE", newloc, 1)) {
314 fprintf(stderr,
315 "Error setting LC_CTYPE, skipping C locale coercion\n");
316 return 0;
317 }
318 if (warn) {
319 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
320 }
321
322 /* Reconfigure with the overridden environment variables */
323 _Py_SetLocaleFromEnv(LC_ALL);
324 return 1;
325 }
326 #endif
327
328 int
_Py_CoerceLegacyLocale(int warn)329 _Py_CoerceLegacyLocale(int warn)
330 {
331 int coerced = 0;
332 #ifdef PY_COERCE_C_LOCALE
333 char *oldloc = NULL;
334
335 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
336 if (oldloc == NULL) {
337 return coerced;
338 }
339
340 const char *locale_override = getenv("LC_ALL");
341 if (locale_override == NULL || *locale_override == '\0') {
342 /* LC_ALL is also not set (or is set to an empty string) */
343 const _LocaleCoercionTarget *target = NULL;
344 for (target = _TARGET_LOCALES; target->locale_name; target++) {
345 const char *new_locale = setlocale(LC_CTYPE,
346 target->locale_name);
347 if (new_locale != NULL) {
348 #if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
349 /* Also ensure that nl_langinfo works in this locale */
350 char *codeset = nl_langinfo(CODESET);
351 if (!codeset || *codeset == '\0') {
352 /* CODESET is not set or empty, so skip coercion */
353 new_locale = NULL;
354 _Py_SetLocaleFromEnv(LC_CTYPE);
355 continue;
356 }
357 #endif
358 /* Successfully configured locale, so make it the default */
359 coerced = _coerce_default_locale_settings(warn, target);
360 goto done;
361 }
362 }
363 }
364 /* No C locale warning here, as Py_Initialize will emit one later */
365
366 setlocale(LC_CTYPE, oldloc);
367
368 done:
369 PyMem_RawFree(oldloc);
370 #endif
371 return coerced;
372 }
373
374 /* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
375 * isolate the idiosyncrasies of different libc implementations. It reads the
376 * appropriate environment variable and uses its value to select the locale for
377 * 'category'. */
378 char *
_Py_SetLocaleFromEnv(int category)379 _Py_SetLocaleFromEnv(int category)
380 {
381 char *res;
382 #ifdef __ANDROID__
383 const char *locale;
384 const char **pvar;
385 #ifdef PY_COERCE_C_LOCALE
386 const char *coerce_c_locale;
387 #endif
388 const char *utf8_locale = "C.UTF-8";
389 const char *env_var_set[] = {
390 "LC_ALL",
391 "LC_CTYPE",
392 "LANG",
393 NULL,
394 };
395
396 /* Android setlocale(category, "") doesn't check the environment variables
397 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
398 * check the environment variables listed in env_var_set. */
399 for (pvar=env_var_set; *pvar; pvar++) {
400 locale = getenv(*pvar);
401 if (locale != NULL && *locale != '\0') {
402 if (strcmp(locale, utf8_locale) == 0 ||
403 strcmp(locale, "en_US.UTF-8") == 0) {
404 return setlocale(category, utf8_locale);
405 }
406 return setlocale(category, "C");
407 }
408 }
409
410 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
411 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
412 * Quote from POSIX section "8.2 Internationalization Variables":
413 * "4. If the LANG environment variable is not set or is set to the empty
414 * string, the implementation-defined default locale shall be used." */
415
416 #ifdef PY_COERCE_C_LOCALE
417 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
418 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
419 /* Some other ported code may check the environment variables (e.g. in
420 * extension modules), so we make sure that they match the locale
421 * configuration */
422 if (setenv("LC_CTYPE", utf8_locale, 1)) {
423 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
424 "environment variable to %s\n", utf8_locale);
425 }
426 }
427 #endif
428 res = setlocale(category, utf8_locale);
429 #else /* !defined(__ANDROID__) */
430 res = setlocale(category, "");
431 #endif
432 _Py_ResetForceASCII();
433 return res;
434 }
435
436
437 /* Global initializations. Can be undone by Py_Finalize(). Don't
438 call this twice without an intervening Py_Finalize() call.
439
440 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
441 must have a corresponding call to Py_Finalize.
442
443 Locking: you must hold the interpreter lock while calling these APIs.
444 (If the lock has not yet been initialized, that's equivalent to
445 having the lock, but you cannot use multiple threads.)
446
447 */
448
449 static PyStatus
pyinit_core_reconfigure(_PyRuntimeState * runtime,PyInterpreterState ** interp_p,const PyConfig * config)450 pyinit_core_reconfigure(_PyRuntimeState *runtime,
451 PyInterpreterState **interp_p,
452 const PyConfig *config)
453 {
454 PyStatus status;
455 PyThreadState *tstate = _PyThreadState_GET();
456 if (!tstate) {
457 return _PyStatus_ERR("failed to read thread state");
458 }
459
460 PyInterpreterState *interp = tstate->interp;
461 if (interp == NULL) {
462 return _PyStatus_ERR("can't make main interpreter");
463 }
464 *interp_p = interp;
465
466 _PyConfig_Write(config, runtime);
467
468 status = _PyConfig_Copy(&interp->config, config);
469 if (_PyStatus_EXCEPTION(status)) {
470 return status;
471 }
472 config = &interp->config;
473
474 if (config->_install_importlib) {
475 status = _PyConfig_WritePathConfig(config);
476 if (_PyStatus_EXCEPTION(status)) {
477 return status;
478 }
479 }
480 return _PyStatus_OK();
481 }
482
483
484 static PyStatus
pycore_init_runtime(_PyRuntimeState * runtime,const PyConfig * config)485 pycore_init_runtime(_PyRuntimeState *runtime,
486 const PyConfig *config)
487 {
488 if (runtime->initialized) {
489 return _PyStatus_ERR("main interpreter already initialized");
490 }
491
492 _PyConfig_Write(config, runtime);
493
494 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
495 * threads behave a little more gracefully at interpreter shutdown.
496 * We clobber it here so the new interpreter can start with a clean
497 * slate.
498 *
499 * However, this may still lead to misbehaviour if there are daemon
500 * threads still hanging around from a previous Py_Initialize/Finalize
501 * pair :(
502 */
503 runtime->finalizing = NULL;
504
505 PyStatus status = _Py_HashRandomization_Init(config);
506 if (_PyStatus_EXCEPTION(status)) {
507 return status;
508 }
509
510 status = _PyInterpreterState_Enable(runtime);
511 if (_PyStatus_EXCEPTION(status)) {
512 return status;
513 }
514 return _PyStatus_OK();
515 }
516
517
518 static PyStatus
pycore_create_interpreter(_PyRuntimeState * runtime,const PyConfig * config,PyInterpreterState ** interp_p)519 pycore_create_interpreter(_PyRuntimeState *runtime,
520 const PyConfig *config,
521 PyInterpreterState **interp_p)
522 {
523 PyInterpreterState *interp = PyInterpreterState_New();
524 if (interp == NULL) {
525 return _PyStatus_ERR("can't make main interpreter");
526 }
527 *interp_p = interp;
528
529 PyStatus status = _PyConfig_Copy(&interp->config, config);
530 if (_PyStatus_EXCEPTION(status)) {
531 return status;
532 }
533 config = &interp->config;
534
535 PyThreadState *tstate = PyThreadState_New(interp);
536 if (tstate == NULL)
537 return _PyStatus_ERR("can't make first thread");
538 (void) PyThreadState_Swap(tstate);
539
540 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
541 destroying the GIL might fail when it is being referenced from
542 another running thread (see issue #9901).
543 Instead we destroy the previously created GIL here, which ensures
544 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
545 _PyEval_FiniThreads(&runtime->ceval);
546
547 /* Auto-thread-state API */
548 _PyGILState_Init(runtime, interp, tstate);
549
550 /* Create the GIL */
551 PyEval_InitThreads();
552
553 return _PyStatus_OK();
554 }
555
556
557 static PyStatus
pycore_init_types(void)558 pycore_init_types(void)
559 {
560 PyStatus status = _PyTypes_Init();
561 if (_PyStatus_EXCEPTION(status)) {
562 return status;
563 }
564
565 status = _PyUnicode_Init();
566 if (_PyStatus_EXCEPTION(status)) {
567 return status;
568 }
569
570 if (_PyStructSequence_Init() < 0) {
571 return _PyStatus_ERR("can't initialize structseq");
572 }
573
574 if (!_PyLong_Init()) {
575 return _PyStatus_ERR("can't init longs");
576 }
577
578 status = _PyExc_Init();
579 if (_PyStatus_EXCEPTION(status)) {
580 return status;
581 }
582
583 if (!_PyFloat_Init()) {
584 return _PyStatus_ERR("can't init float");
585 }
586
587 if (!_PyContext_Init()) {
588 return _PyStatus_ERR("can't init context");
589 }
590
591 status = _PyErr_Init();
592 if (_PyStatus_EXCEPTION(status)) {
593 return status;
594 }
595
596 return _PyStatus_OK();
597 }
598
599
600 static PyStatus
pycore_init_builtins(PyInterpreterState * interp)601 pycore_init_builtins(PyInterpreterState *interp)
602 {
603 PyObject *bimod = _PyBuiltin_Init();
604 if (bimod == NULL) {
605 return _PyStatus_ERR("can't initialize builtins modules");
606 }
607 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
608
609 interp->builtins = PyModule_GetDict(bimod);
610 if (interp->builtins == NULL) {
611 return _PyStatus_ERR("can't initialize builtins dict");
612 }
613 Py_INCREF(interp->builtins);
614
615 PyStatus status = _PyBuiltins_AddExceptions(bimod);
616 if (_PyStatus_EXCEPTION(status)) {
617 return status;
618 }
619 return _PyStatus_OK();
620 }
621
622
623 static PyStatus
pycore_init_import_warnings(PyInterpreterState * interp,PyObject * sysmod)624 pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
625 {
626 const PyConfig *config = &interp->config;
627
628 PyStatus status = _PyImport_Init(interp);
629 if (_PyStatus_EXCEPTION(status)) {
630 return status;
631 }
632
633 status = _PyImportHooks_Init();
634 if (_PyStatus_EXCEPTION(status)) {
635 return status;
636 }
637
638 /* Initialize _warnings. */
639 if (_PyWarnings_Init() == NULL) {
640 return _PyStatus_ERR("can't initialize warnings");
641 }
642
643 if (config->_install_importlib) {
644 status = _PyConfig_WritePathConfig(config);
645 if (_PyStatus_EXCEPTION(status)) {
646 return status;
647 }
648 }
649
650 /* This call sets up builtin and frozen import support */
651 if (config->_install_importlib) {
652 status = init_importlib(interp, sysmod);
653 if (_PyStatus_EXCEPTION(status)) {
654 return status;
655 }
656 }
657 return _PyStatus_OK();
658 }
659
660
661 static PyStatus
pyinit_config(_PyRuntimeState * runtime,PyInterpreterState ** interp_p,const PyConfig * config)662 pyinit_config(_PyRuntimeState *runtime,
663 PyInterpreterState **interp_p,
664 const PyConfig *config)
665 {
666 PyInterpreterState *interp;
667
668 _PyConfig_Write(config, runtime);
669
670 PyStatus status = pycore_init_runtime(runtime, config);
671 if (_PyStatus_EXCEPTION(status)) {
672 return status;
673 }
674
675 status = pycore_create_interpreter(runtime, config, &interp);
676 if (_PyStatus_EXCEPTION(status)) {
677 return status;
678 }
679 config = &interp->config;
680 *interp_p = interp;
681
682 status = pycore_init_types();
683 if (_PyStatus_EXCEPTION(status)) {
684 return status;
685 }
686
687 PyObject *sysmod;
688 status = _PySys_Create(runtime, interp, &sysmod);
689 if (_PyStatus_EXCEPTION(status)) {
690 return status;
691 }
692
693 status = pycore_init_builtins(interp);
694 if (_PyStatus_EXCEPTION(status)) {
695 return status;
696 }
697
698 status = pycore_init_import_warnings(interp, sysmod);
699 if (_PyStatus_EXCEPTION(status)) {
700 return status;
701 }
702
703 /* Only when we get here is the runtime core fully initialized */
704 runtime->core_initialized = 1;
705 return _PyStatus_OK();
706 }
707
708
709 PyStatus
_Py_PreInitializeFromPyArgv(const PyPreConfig * src_config,const _PyArgv * args)710 _Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
711 {
712 PyStatus status;
713
714 if (src_config == NULL) {
715 return _PyStatus_ERR("preinitialization config is NULL");
716 }
717
718 status = _PyRuntime_Initialize();
719 if (_PyStatus_EXCEPTION(status)) {
720 return status;
721 }
722 _PyRuntimeState *runtime = &_PyRuntime;
723
724 if (runtime->preinitialized) {
725 /* If it's already configured: ignored the new configuration */
726 return _PyStatus_OK();
727 }
728
729 /* Note: preinitialized remains 1 on error, it is only set to 0
730 at exit on success. */
731 runtime->preinitializing = 1;
732
733 PyPreConfig config;
734
735 status = _PyPreConfig_InitFromPreConfig(&config, src_config);
736 if (_PyStatus_EXCEPTION(status)) {
737 return status;
738 }
739
740 status = _PyPreConfig_Read(&config, args);
741 if (_PyStatus_EXCEPTION(status)) {
742 return status;
743 }
744
745 status = _PyPreConfig_Write(&config);
746 if (_PyStatus_EXCEPTION(status)) {
747 return status;
748 }
749
750 runtime->preinitializing = 0;
751 runtime->preinitialized = 1;
752 return _PyStatus_OK();
753 }
754
755
756 PyStatus
Py_PreInitializeFromBytesArgs(const PyPreConfig * src_config,Py_ssize_t argc,char ** argv)757 Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
758 {
759 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
760 return _Py_PreInitializeFromPyArgv(src_config, &args);
761 }
762
763
764 PyStatus
Py_PreInitializeFromArgs(const PyPreConfig * src_config,Py_ssize_t argc,wchar_t ** argv)765 Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
766 {
767 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
768 return _Py_PreInitializeFromPyArgv(src_config, &args);
769 }
770
771
772 PyStatus
Py_PreInitialize(const PyPreConfig * src_config)773 Py_PreInitialize(const PyPreConfig *src_config)
774 {
775 return _Py_PreInitializeFromPyArgv(src_config, NULL);
776 }
777
778
779 PyStatus
_Py_PreInitializeFromConfig(const PyConfig * config,const _PyArgv * args)780 _Py_PreInitializeFromConfig(const PyConfig *config,
781 const _PyArgv *args)
782 {
783 assert(config != NULL);
784
785 PyStatus status = _PyRuntime_Initialize();
786 if (_PyStatus_EXCEPTION(status)) {
787 return status;
788 }
789 _PyRuntimeState *runtime = &_PyRuntime;
790
791 if (runtime->preinitialized) {
792 /* Already initialized: do nothing */
793 return _PyStatus_OK();
794 }
795
796 PyPreConfig preconfig;
797
798 _PyPreConfig_InitFromConfig(&preconfig, config);
799
800 if (!config->parse_argv) {
801 return Py_PreInitialize(&preconfig);
802 }
803 else if (args == NULL) {
804 _PyArgv config_args = {
805 .use_bytes_argv = 0,
806 .argc = config->argv.length,
807 .wchar_argv = config->argv.items};
808 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
809 }
810 else {
811 return _Py_PreInitializeFromPyArgv(&preconfig, args);
812 }
813 }
814
815
816 /* Begin interpreter initialization
817 *
818 * On return, the first thread and interpreter state have been created,
819 * but the compiler, signal handling, multithreading and
820 * multiple interpreter support, and codec infrastructure are not yet
821 * available.
822 *
823 * The import system will support builtin and frozen modules only.
824 * The only supported io is writing to sys.stderr
825 *
826 * If any operation invoked by this function fails, a fatal error is
827 * issued and the function does not return.
828 *
829 * Any code invoked from this function should *not* assume it has access
830 * to the Python C API (unless the API is explicitly listed as being
831 * safe to call without calling Py_Initialize first)
832 */
833 static PyStatus
pyinit_core(_PyRuntimeState * runtime,const PyConfig * src_config,PyInterpreterState ** interp_p)834 pyinit_core(_PyRuntimeState *runtime,
835 const PyConfig *src_config,
836 PyInterpreterState **interp_p)
837 {
838 PyStatus status;
839
840 status = _Py_PreInitializeFromConfig(src_config, NULL);
841 if (_PyStatus_EXCEPTION(status)) {
842 return status;
843 }
844
845 PyConfig config;
846 _PyConfig_InitCompatConfig(&config);
847
848 status = _PyConfig_Copy(&config, src_config);
849 if (_PyStatus_EXCEPTION(status)) {
850 goto done;
851 }
852
853 status = PyConfig_Read(&config);
854 if (_PyStatus_EXCEPTION(status)) {
855 goto done;
856 }
857
858 if (!runtime->core_initialized) {
859 status = pyinit_config(runtime, interp_p, &config);
860 }
861 else {
862 status = pyinit_core_reconfigure(runtime, interp_p, &config);
863 }
864 if (_PyStatus_EXCEPTION(status)) {
865 goto done;
866 }
867
868 done:
869 PyConfig_Clear(&config);
870 return status;
871 }
872
873
874 /* Py_Initialize() has already been called: update the main interpreter
875 configuration. Example of bpo-34008: Py_Main() called after
876 Py_Initialize(). */
877 static PyStatus
_Py_ReconfigureMainInterpreter(PyInterpreterState * interp)878 _Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
879 {
880 PyConfig *config = &interp->config;
881
882 PyObject *argv = _PyWideStringList_AsList(&config->argv);
883 if (argv == NULL) {
884 return _PyStatus_NO_MEMORY(); \
885 }
886
887 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
888 Py_DECREF(argv);
889 if (res < 0) {
890 return _PyStatus_ERR("fail to set sys.argv");
891 }
892 return _PyStatus_OK();
893 }
894
895 /* Update interpreter state based on supplied configuration settings
896 *
897 * After calling this function, most of the restrictions on the interpreter
898 * are lifted. The only remaining incomplete settings are those related
899 * to the main module (sys.argv[0], __main__ metadata)
900 *
901 * Calling this when the interpreter is not initializing, is already
902 * initialized or without a valid current thread state is a fatal error.
903 * Other errors should be reported as normal Python exceptions with a
904 * non-zero return code.
905 */
906 static PyStatus
pyinit_main(_PyRuntimeState * runtime,PyInterpreterState * interp)907 pyinit_main(_PyRuntimeState *runtime, PyInterpreterState *interp)
908 {
909 if (!runtime->core_initialized) {
910 return _PyStatus_ERR("runtime core not initialized");
911 }
912
913 /* Configure the main interpreter */
914 PyConfig *config = &interp->config;
915
916 if (runtime->initialized) {
917 return _Py_ReconfigureMainInterpreter(interp);
918 }
919
920 if (!config->_install_importlib) {
921 /* Special mode for freeze_importlib: run with no import system
922 *
923 * This means anything which needs support from extension modules
924 * or pure Python code in the standard library won't work.
925 */
926 runtime->initialized = 1;
927 return _PyStatus_OK();
928 }
929
930 if (_PyTime_Init() < 0) {
931 return _PyStatus_ERR("can't initialize time");
932 }
933
934 if (_PySys_InitMain(runtime, interp) < 0) {
935 return _PyStatus_ERR("can't finish initializing sys");
936 }
937
938 PyStatus status = init_importlib_external(interp);
939 if (_PyStatus_EXCEPTION(status)) {
940 return status;
941 }
942
943 /* initialize the faulthandler module */
944 status = _PyFaulthandler_Init(config->faulthandler);
945 if (_PyStatus_EXCEPTION(status)) {
946 return status;
947 }
948
949 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
950 status = _PyUnicode_InitEncodings(tstate);
951 if (_PyStatus_EXCEPTION(status)) {
952 return status;
953 }
954
955 if (config->install_signal_handlers) {
956 status = init_signals();
957 if (_PyStatus_EXCEPTION(status)) {
958 return status;
959 }
960 }
961
962 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
963 return _PyStatus_ERR("can't initialize tracemalloc");
964 }
965
966 status = add_main_module(interp);
967 if (_PyStatus_EXCEPTION(status)) {
968 return status;
969 }
970
971 status = init_sys_streams(interp);
972 if (_PyStatus_EXCEPTION(status)) {
973 return status;
974 }
975
976 /* Initialize warnings. */
977 PyObject *warnoptions = PySys_GetObject("warnoptions");
978 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
979 {
980 PyObject *warnings_module = PyImport_ImportModule("warnings");
981 if (warnings_module == NULL) {
982 fprintf(stderr, "'import warnings' failed; traceback:\n");
983 PyErr_Print();
984 }
985 Py_XDECREF(warnings_module);
986 }
987
988 runtime->initialized = 1;
989
990 if (config->site_import) {
991 status = init_import_size(); /* Module site */
992 if (_PyStatus_EXCEPTION(status)) {
993 return status;
994 }
995 }
996
997 #ifndef MS_WINDOWS
998 emit_stderr_warning_for_legacy_locale(runtime);
999 #endif
1000
1001 return _PyStatus_OK();
1002 }
1003
1004
1005 PyStatus
_Py_InitializeMain(void)1006 _Py_InitializeMain(void)
1007 {
1008 PyStatus status = _PyRuntime_Initialize();
1009 if (_PyStatus_EXCEPTION(status)) {
1010 return status;
1011 }
1012 _PyRuntimeState *runtime = &_PyRuntime;
1013 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1014
1015 return pyinit_main(runtime, interp);
1016 }
1017
1018
1019 PyStatus
Py_InitializeFromConfig(const PyConfig * config)1020 Py_InitializeFromConfig(const PyConfig *config)
1021 {
1022 if (config == NULL) {
1023 return _PyStatus_ERR("initialization config is NULL");
1024 }
1025
1026 PyStatus status;
1027
1028 status = _PyRuntime_Initialize();
1029 if (_PyStatus_EXCEPTION(status)) {
1030 return status;
1031 }
1032 _PyRuntimeState *runtime = &_PyRuntime;
1033
1034 PyInterpreterState *interp = NULL;
1035 status = pyinit_core(runtime, config, &interp);
1036 if (_PyStatus_EXCEPTION(status)) {
1037 return status;
1038 }
1039 config = &interp->config;
1040
1041 if (config->_init_main) {
1042 status = pyinit_main(runtime, interp);
1043 if (_PyStatus_EXCEPTION(status)) {
1044 return status;
1045 }
1046 }
1047
1048 return _PyStatus_OK();
1049 }
1050
1051
1052 void
Py_InitializeEx(int install_sigs)1053 Py_InitializeEx(int install_sigs)
1054 {
1055 PyStatus status;
1056
1057 status = _PyRuntime_Initialize();
1058 if (_PyStatus_EXCEPTION(status)) {
1059 Py_ExitStatusException(status);
1060 }
1061 _PyRuntimeState *runtime = &_PyRuntime;
1062
1063 if (runtime->initialized) {
1064 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1065 return;
1066 }
1067
1068 PyConfig config;
1069 _PyConfig_InitCompatConfig(&config);
1070
1071 config.install_signal_handlers = install_sigs;
1072
1073 status = Py_InitializeFromConfig(&config);
1074 if (_PyStatus_EXCEPTION(status)) {
1075 Py_ExitStatusException(status);
1076 }
1077 }
1078
1079 void
Py_Initialize(void)1080 Py_Initialize(void)
1081 {
1082 Py_InitializeEx(1);
1083 }
1084
1085
1086 #ifdef COUNT_ALLOCS
1087 extern void _Py_dump_counts(FILE*);
1088 #endif
1089
1090 /* Flush stdout and stderr */
1091
1092 static int
file_is_closed(PyObject * fobj)1093 file_is_closed(PyObject *fobj)
1094 {
1095 int r;
1096 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1097 if (tmp == NULL) {
1098 PyErr_Clear();
1099 return 0;
1100 }
1101 r = PyObject_IsTrue(tmp);
1102 Py_DECREF(tmp);
1103 if (r < 0)
1104 PyErr_Clear();
1105 return r > 0;
1106 }
1107
1108 static int
flush_std_files(void)1109 flush_std_files(void)
1110 {
1111 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1112 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1113 PyObject *tmp;
1114 int status = 0;
1115
1116 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
1117 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
1118 if (tmp == NULL) {
1119 PyErr_WriteUnraisable(fout);
1120 status = -1;
1121 }
1122 else
1123 Py_DECREF(tmp);
1124 }
1125
1126 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
1127 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
1128 if (tmp == NULL) {
1129 PyErr_Clear();
1130 status = -1;
1131 }
1132 else
1133 Py_DECREF(tmp);
1134 }
1135
1136 return status;
1137 }
1138
1139 /* Undo the effect of Py_Initialize().
1140
1141 Beware: if multiple interpreter and/or thread states exist, these
1142 are not wiped out; only the current thread and interpreter state
1143 are deleted. But since everything else is deleted, those other
1144 interpreter and thread states should no longer be used.
1145
1146 (XXX We should do better, e.g. wipe out all interpreters and
1147 threads.)
1148
1149 Locking: as above.
1150
1151 */
1152
1153 int
Py_FinalizeEx(void)1154 Py_FinalizeEx(void)
1155 {
1156 int status = 0;
1157
1158 _PyRuntimeState *runtime = &_PyRuntime;
1159 if (!runtime->initialized) {
1160 return status;
1161 }
1162
1163 // Wrap up existing "threading"-module-created, non-daemon threads.
1164 wait_for_thread_shutdown();
1165
1166 // Make any remaining pending calls.
1167 _Py_FinishPendingCalls(runtime);
1168
1169 /* Get current thread state and interpreter pointer */
1170 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1171 PyInterpreterState *interp = tstate->interp;
1172
1173 /* The interpreter is still entirely intact at this point, and the
1174 * exit funcs may be relying on that. In particular, if some thread
1175 * or exit func is still waiting to do an import, the import machinery
1176 * expects Py_IsInitialized() to return true. So don't say the
1177 * runtime is uninitialized until after the exit funcs have run.
1178 * Note that Threading.py uses an exit func to do a join on all the
1179 * threads created thru it, so this also protects pending imports in
1180 * the threads created via Threading.
1181 */
1182
1183 call_py_exitfuncs(interp);
1184
1185 /* Copy the core config, PyInterpreterState_Delete() free
1186 the core config memory */
1187 #ifdef Py_REF_DEBUG
1188 int show_ref_count = interp->config.show_ref_count;
1189 #endif
1190 #ifdef Py_TRACE_REFS
1191 int dump_refs = interp->config.dump_refs;
1192 #endif
1193 #ifdef WITH_PYMALLOC
1194 int malloc_stats = interp->config.malloc_stats;
1195 #endif
1196
1197 /* Remaining threads (e.g. daemon threads) will automatically exit
1198 after taking the GIL (in PyEval_RestoreThread()). */
1199 runtime->finalizing = tstate;
1200 runtime->initialized = 0;
1201 runtime->core_initialized = 0;
1202
1203 /* Flush sys.stdout and sys.stderr */
1204 if (flush_std_files() < 0) {
1205 status = -1;
1206 }
1207
1208 /* Disable signal handling */
1209 PyOS_FiniInterrupts();
1210
1211 /* Collect garbage. This may call finalizers; it's nice to call these
1212 * before all modules are destroyed.
1213 * XXX If a __del__ or weakref callback is triggered here, and tries to
1214 * XXX import a module, bad things can happen, because Python no
1215 * XXX longer believes it's initialized.
1216 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1217 * XXX is easy to provoke that way. I've also seen, e.g.,
1218 * XXX Exception exceptions.ImportError: 'No module named sha'
1219 * XXX in <function callback at 0x008F5718> ignored
1220 * XXX but I'm unclear on exactly how that one happens. In any case,
1221 * XXX I haven't seen a real-life report of either of these.
1222 */
1223 _PyGC_CollectIfEnabled();
1224 #ifdef COUNT_ALLOCS
1225 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1226 each collection might release some types from the type
1227 list, so they become garbage. */
1228 while (_PyGC_CollectIfEnabled() > 0)
1229 /* nothing */;
1230 #endif
1231
1232 /* Clear all loghooks */
1233 /* We want minimal exposure of this function, so define the extern
1234 * here. The linker should discover the correct function without
1235 * exporting a symbol. */
1236 extern void _PySys_ClearAuditHooks(void);
1237 _PySys_ClearAuditHooks();
1238
1239 /* Destroy all modules */
1240 PyImport_Cleanup();
1241
1242 /* Print debug stats if any */
1243 _PyEval_Fini();
1244
1245 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
1246 if (flush_std_files() < 0) {
1247 status = -1;
1248 }
1249
1250 /* Collect final garbage. This disposes of cycles created by
1251 * class definitions, for example.
1252 * XXX This is disabled because it caused too many problems. If
1253 * XXX a __del__ or weakref callback triggers here, Python code has
1254 * XXX a hard time running, because even the sys module has been
1255 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1256 * XXX One symptom is a sequence of information-free messages
1257 * XXX coming from threads (if a __del__ or callback is invoked,
1258 * XXX other threads can execute too, and any exception they encounter
1259 * XXX triggers a comedy of errors as subsystem after subsystem
1260 * XXX fails to find what it *expects* to find in sys to help report
1261 * XXX the exception and consequent unexpected failures). I've also
1262 * XXX seen segfaults then, after adding print statements to the
1263 * XXX Python code getting called.
1264 */
1265 #if 0
1266 _PyGC_CollectIfEnabled();
1267 #endif
1268
1269 /* Disable tracemalloc after all Python objects have been destroyed,
1270 so it is possible to use tracemalloc in objects destructor. */
1271 _PyTraceMalloc_Fini();
1272
1273 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1274 _PyImport_Fini();
1275
1276 /* Cleanup typeobject.c's internal caches. */
1277 _PyType_Fini();
1278
1279 /* unload faulthandler module */
1280 _PyFaulthandler_Fini();
1281
1282 /* Debugging stuff */
1283 #ifdef COUNT_ALLOCS
1284 _Py_dump_counts(stderr);
1285 #endif
1286 /* dump hash stats */
1287 _PyHash_Fini();
1288
1289 #ifdef Py_REF_DEBUG
1290 if (show_ref_count) {
1291 _PyDebug_PrintTotalRefs();
1292 }
1293 #endif
1294
1295 #ifdef Py_TRACE_REFS
1296 /* Display all objects still alive -- this can invoke arbitrary
1297 * __repr__ overrides, so requires a mostly-intact interpreter.
1298 * Alas, a lot of stuff may still be alive now that will be cleaned
1299 * up later.
1300 */
1301 if (dump_refs) {
1302 _Py_PrintReferences(stderr);
1303 }
1304 #endif /* Py_TRACE_REFS */
1305
1306 /* Clear interpreter state and all thread states. */
1307 PyInterpreterState_Clear(interp);
1308
1309 /* Now we decref the exception classes. After this point nothing
1310 can raise an exception. That's okay, because each Fini() method
1311 below has been checked to make sure no exceptions are ever
1312 raised.
1313 */
1314
1315 _PyExc_Fini();
1316
1317 /* Sundry finalizers */
1318 PyMethod_Fini();
1319 PyFrame_Fini();
1320 PyCFunction_Fini();
1321 PyTuple_Fini();
1322 PyList_Fini();
1323 PySet_Fini();
1324 PyBytes_Fini();
1325 PyLong_Fini();
1326 PyFloat_Fini();
1327 PyDict_Fini();
1328 PySlice_Fini();
1329 _PyGC_Fini(runtime);
1330 _PyWarnings_Fini(interp);
1331 _Py_HashRandomization_Fini();
1332 _PyArg_Fini();
1333 PyAsyncGen_Fini();
1334 _PyContext_Fini();
1335
1336 /* Cleanup Unicode implementation */
1337 _PyUnicode_Fini();
1338
1339 _Py_ClearFileSystemEncoding();
1340
1341 /* XXX Still allocated:
1342 - various static ad-hoc pointers to interned strings
1343 - int and float free list blocks
1344 - whatever various modules and libraries allocate
1345 */
1346
1347 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1348
1349 /* Cleanup auto-thread-state */
1350 _PyGILState_Fini(runtime);
1351
1352 /* Delete current thread. After this, many C API calls become crashy. */
1353 PyThreadState_Swap(NULL);
1354
1355 PyInterpreterState_Delete(interp);
1356
1357 #ifdef Py_TRACE_REFS
1358 /* Display addresses (& refcnts) of all objects still alive.
1359 * An address can be used to find the repr of the object, printed
1360 * above by _Py_PrintReferences.
1361 */
1362 if (dump_refs) {
1363 _Py_PrintReferenceAddresses(stderr);
1364 }
1365 #endif /* Py_TRACE_REFS */
1366 #ifdef WITH_PYMALLOC
1367 if (malloc_stats) {
1368 _PyObject_DebugMallocStats(stderr);
1369 }
1370 #endif
1371
1372 call_ll_exitfuncs(runtime);
1373
1374 _PyRuntime_Finalize();
1375 return status;
1376 }
1377
1378 void
Py_Finalize(void)1379 Py_Finalize(void)
1380 {
1381 Py_FinalizeEx();
1382 }
1383
1384 /* Create and initialize a new interpreter and thread, and return the
1385 new thread. This requires that Py_Initialize() has been called
1386 first.
1387
1388 Unsuccessful initialization yields a NULL pointer. Note that *no*
1389 exception information is available even in this case -- the
1390 exception information is held in the thread, and there is no
1391 thread.
1392
1393 Locking: as above.
1394
1395 */
1396
1397 static PyStatus
new_interpreter(PyThreadState ** tstate_p)1398 new_interpreter(PyThreadState **tstate_p)
1399 {
1400 PyStatus status;
1401
1402 status = _PyRuntime_Initialize();
1403 if (_PyStatus_EXCEPTION(status)) {
1404 return status;
1405 }
1406 _PyRuntimeState *runtime = &_PyRuntime;
1407
1408 if (!runtime->initialized) {
1409 return _PyStatus_ERR("Py_Initialize must be called first");
1410 }
1411
1412 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1413 interpreters: disable PyGILState_Check(). */
1414 _PyGILState_check_enabled = 0;
1415
1416 PyInterpreterState *interp = PyInterpreterState_New();
1417 if (interp == NULL) {
1418 *tstate_p = NULL;
1419 return _PyStatus_OK();
1420 }
1421
1422 PyThreadState *tstate = PyThreadState_New(interp);
1423 if (tstate == NULL) {
1424 PyInterpreterState_Delete(interp);
1425 *tstate_p = NULL;
1426 return _PyStatus_OK();
1427 }
1428
1429 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
1430
1431 /* Copy the current interpreter config into the new interpreter */
1432 PyConfig *config;
1433 if (save_tstate != NULL) {
1434 config = &save_tstate->interp->config;
1435 } else {
1436 /* No current thread state, copy from the main interpreter */
1437 PyInterpreterState *main_interp = PyInterpreterState_Main();
1438 config = &main_interp->config;
1439 }
1440
1441 status = _PyConfig_Copy(&interp->config, config);
1442 if (_PyStatus_EXCEPTION(status)) {
1443 return status;
1444 }
1445 config = &interp->config;
1446
1447 status = _PyExc_Init();
1448 if (_PyStatus_EXCEPTION(status)) {
1449 return status;
1450 }
1451
1452 status = _PyErr_Init();
1453 if (_PyStatus_EXCEPTION(status)) {
1454 return status;
1455 }
1456
1457
1458 /* XXX The following is lax in error checking */
1459 PyObject *modules = PyDict_New();
1460 if (modules == NULL) {
1461 return _PyStatus_ERR("can't make modules dictionary");
1462 }
1463 interp->modules = modules;
1464
1465 PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
1466 if (sysmod != NULL) {
1467 interp->sysdict = PyModule_GetDict(sysmod);
1468 if (interp->sysdict == NULL) {
1469 goto handle_error;
1470 }
1471 Py_INCREF(interp->sysdict);
1472 PyDict_SetItemString(interp->sysdict, "modules", modules);
1473 if (_PySys_InitMain(runtime, interp) < 0) {
1474 return _PyStatus_ERR("can't finish initializing sys");
1475 }
1476 }
1477 else if (PyErr_Occurred()) {
1478 goto handle_error;
1479 }
1480
1481 PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
1482 if (bimod != NULL) {
1483 interp->builtins = PyModule_GetDict(bimod);
1484 if (interp->builtins == NULL)
1485 goto handle_error;
1486 Py_INCREF(interp->builtins);
1487 }
1488 else if (PyErr_Occurred()) {
1489 goto handle_error;
1490 }
1491
1492 if (bimod != NULL && sysmod != NULL) {
1493 status = _PyBuiltins_AddExceptions(bimod);
1494 if (_PyStatus_EXCEPTION(status)) {
1495 return status;
1496 }
1497
1498 status = _PySys_SetPreliminaryStderr(interp->sysdict);
1499 if (_PyStatus_EXCEPTION(status)) {
1500 return status;
1501 }
1502
1503 status = _PyImportHooks_Init();
1504 if (_PyStatus_EXCEPTION(status)) {
1505 return status;
1506 }
1507
1508 status = init_importlib(interp, sysmod);
1509 if (_PyStatus_EXCEPTION(status)) {
1510 return status;
1511 }
1512
1513 status = init_importlib_external(interp);
1514 if (_PyStatus_EXCEPTION(status)) {
1515 return status;
1516 }
1517
1518 status = _PyUnicode_InitEncodings(tstate);
1519 if (_PyStatus_EXCEPTION(status)) {
1520 return status;
1521 }
1522
1523 status = init_sys_streams(interp);
1524 if (_PyStatus_EXCEPTION(status)) {
1525 return status;
1526 }
1527
1528 status = add_main_module(interp);
1529 if (_PyStatus_EXCEPTION(status)) {
1530 return status;
1531 }
1532
1533 if (config->site_import) {
1534 status = init_import_size();
1535 if (_PyStatus_EXCEPTION(status)) {
1536 return status;
1537 }
1538 }
1539 }
1540
1541 if (PyErr_Occurred()) {
1542 goto handle_error;
1543 }
1544
1545 *tstate_p = tstate;
1546 return _PyStatus_OK();
1547
1548 handle_error:
1549 /* Oops, it didn't work. Undo it all. */
1550
1551 PyErr_PrintEx(0);
1552 PyThreadState_Clear(tstate);
1553 PyThreadState_Swap(save_tstate);
1554 PyThreadState_Delete(tstate);
1555 PyInterpreterState_Delete(interp);
1556
1557 *tstate_p = NULL;
1558 return _PyStatus_OK();
1559 }
1560
1561 PyThreadState *
Py_NewInterpreter(void)1562 Py_NewInterpreter(void)
1563 {
1564 PyThreadState *tstate = NULL;
1565 PyStatus status = new_interpreter(&tstate);
1566 if (_PyStatus_EXCEPTION(status)) {
1567 Py_ExitStatusException(status);
1568 }
1569 return tstate;
1570
1571 }
1572
1573 /* Delete an interpreter and its last thread. This requires that the
1574 given thread state is current, that the thread has no remaining
1575 frames, and that it is its interpreter's only remaining thread.
1576 It is a fatal error to violate these constraints.
1577
1578 (Py_FinalizeEx() doesn't have these constraints -- it zaps
1579 everything, regardless.)
1580
1581 Locking: as above.
1582
1583 */
1584
1585 void
Py_EndInterpreter(PyThreadState * tstate)1586 Py_EndInterpreter(PyThreadState *tstate)
1587 {
1588 PyInterpreterState *interp = tstate->interp;
1589
1590 if (tstate != _PyThreadState_GET())
1591 Py_FatalError("Py_EndInterpreter: thread is not current");
1592 if (tstate->frame != NULL)
1593 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1594 interp->finalizing = 1;
1595
1596 // Wrap up existing "threading"-module-created, non-daemon threads.
1597 wait_for_thread_shutdown();
1598
1599 call_py_exitfuncs(interp);
1600
1601 if (tstate != interp->tstate_head || tstate->next != NULL)
1602 Py_FatalError("Py_EndInterpreter: not the last thread");
1603
1604 PyImport_Cleanup();
1605 PyInterpreterState_Clear(interp);
1606 PyThreadState_Swap(NULL);
1607 PyInterpreterState_Delete(interp);
1608 }
1609
1610 /* Add the __main__ module */
1611
1612 static PyStatus
add_main_module(PyInterpreterState * interp)1613 add_main_module(PyInterpreterState *interp)
1614 {
1615 PyObject *m, *d, *loader, *ann_dict;
1616 m = PyImport_AddModule("__main__");
1617 if (m == NULL)
1618 return _PyStatus_ERR("can't create __main__ module");
1619
1620 d = PyModule_GetDict(m);
1621 ann_dict = PyDict_New();
1622 if ((ann_dict == NULL) ||
1623 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1624 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
1625 }
1626 Py_DECREF(ann_dict);
1627
1628 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1629 PyObject *bimod = PyImport_ImportModule("builtins");
1630 if (bimod == NULL) {
1631 return _PyStatus_ERR("Failed to retrieve builtins module");
1632 }
1633 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1634 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
1635 }
1636 Py_DECREF(bimod);
1637 }
1638
1639 /* Main is a little special - imp.is_builtin("__main__") will return
1640 * False, but BuiltinImporter is still the most appropriate initial
1641 * setting for its __loader__ attribute. A more suitable value will
1642 * be set if __main__ gets further initialized later in the startup
1643 * process.
1644 */
1645 loader = PyDict_GetItemString(d, "__loader__");
1646 if (loader == NULL || loader == Py_None) {
1647 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1648 "BuiltinImporter");
1649 if (loader == NULL) {
1650 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
1651 }
1652 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1653 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
1654 }
1655 Py_DECREF(loader);
1656 }
1657 return _PyStatus_OK();
1658 }
1659
1660 /* Import the site module (not into __main__ though) */
1661
1662 static PyStatus
init_import_size(void)1663 init_import_size(void)
1664 {
1665 PyObject *m;
1666 m = PyImport_ImportModule("site");
1667 if (m == NULL) {
1668 return _PyStatus_ERR("Failed to import the site module");
1669 }
1670 Py_DECREF(m);
1671 return _PyStatus_OK();
1672 }
1673
1674 /* Check if a file descriptor is valid or not.
1675 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1676 static int
is_valid_fd(int fd)1677 is_valid_fd(int fd)
1678 {
1679 /* dup() is faster than fstat(): fstat() can require input/output operations,
1680 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1681 startup. Problem: dup() doesn't check if the file descriptor is valid on
1682 some platforms.
1683
1684 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1685 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1686 EBADF. FreeBSD has similar issue (bpo-32849).
1687
1688 Only use dup() on platforms where dup() is enough to detect invalid FD in
1689 corner cases: on Linux and Windows (bpo-32849). */
1690 #if defined(__linux__) || defined(MS_WINDOWS)
1691 if (fd < 0) {
1692 return 0;
1693 }
1694 int fd2;
1695
1696 _Py_BEGIN_SUPPRESS_IPH
1697 fd2 = dup(fd);
1698 if (fd2 >= 0) {
1699 close(fd2);
1700 }
1701 _Py_END_SUPPRESS_IPH
1702
1703 return (fd2 >= 0);
1704 #else
1705 struct stat st;
1706 return (fstat(fd, &st) == 0);
1707 #endif
1708 }
1709
1710 /* returns Py_None if the fd is not valid */
1711 static PyObject*
create_stdio(const PyConfig * config,PyObject * io,int fd,int write_mode,const char * name,const wchar_t * encoding,const wchar_t * errors)1712 create_stdio(const PyConfig *config, PyObject* io,
1713 int fd, int write_mode, const char* name,
1714 const wchar_t* encoding, const wchar_t* errors)
1715 {
1716 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1717 const char* mode;
1718 const char* newline;
1719 PyObject *line_buffering, *write_through;
1720 int buffering, isatty;
1721 _Py_IDENTIFIER(open);
1722 _Py_IDENTIFIER(isatty);
1723 _Py_IDENTIFIER(TextIOWrapper);
1724 _Py_IDENTIFIER(mode);
1725 const int buffered_stdio = config->buffered_stdio;
1726
1727 if (!is_valid_fd(fd))
1728 Py_RETURN_NONE;
1729
1730 /* stdin is always opened in buffered mode, first because it shouldn't
1731 make a difference in common use cases, second because TextIOWrapper
1732 depends on the presence of a read1() method which only exists on
1733 buffered streams.
1734 */
1735 if (!buffered_stdio && write_mode)
1736 buffering = 0;
1737 else
1738 buffering = -1;
1739 if (write_mode)
1740 mode = "wb";
1741 else
1742 mode = "rb";
1743 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1744 fd, mode, buffering,
1745 Py_None, Py_None, /* encoding, errors */
1746 Py_None, 0); /* newline, closefd */
1747 if (buf == NULL)
1748 goto error;
1749
1750 if (buffering) {
1751 _Py_IDENTIFIER(raw);
1752 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1753 if (raw == NULL)
1754 goto error;
1755 }
1756 else {
1757 raw = buf;
1758 Py_INCREF(raw);
1759 }
1760
1761 #ifdef MS_WINDOWS
1762 /* Windows console IO is always UTF-8 encoded */
1763 if (PyWindowsConsoleIO_Check(raw))
1764 encoding = L"utf-8";
1765 #endif
1766
1767 text = PyUnicode_FromString(name);
1768 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1769 goto error;
1770 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
1771 if (res == NULL)
1772 goto error;
1773 isatty = PyObject_IsTrue(res);
1774 Py_DECREF(res);
1775 if (isatty == -1)
1776 goto error;
1777 if (!buffered_stdio)
1778 write_through = Py_True;
1779 else
1780 write_through = Py_False;
1781 if (isatty && buffered_stdio)
1782 line_buffering = Py_True;
1783 else
1784 line_buffering = Py_False;
1785
1786 Py_CLEAR(raw);
1787 Py_CLEAR(text);
1788
1789 #ifdef MS_WINDOWS
1790 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1791 newlines to "\n".
1792 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1793 newline = NULL;
1794 #else
1795 /* sys.stdin: split lines at "\n".
1796 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1797 newline = "\n";
1798 #endif
1799
1800 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1801 if (encoding_str == NULL) {
1802 Py_CLEAR(buf);
1803 goto error;
1804 }
1805
1806 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1807 if (errors_str == NULL) {
1808 Py_CLEAR(buf);
1809 Py_CLEAR(encoding_str);
1810 goto error;
1811 }
1812
1813 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1814 buf, encoding_str, errors_str,
1815 newline, line_buffering, write_through);
1816 Py_CLEAR(buf);
1817 Py_CLEAR(encoding_str);
1818 Py_CLEAR(errors_str);
1819 if (stream == NULL)
1820 goto error;
1821
1822 if (write_mode)
1823 mode = "w";
1824 else
1825 mode = "r";
1826 text = PyUnicode_FromString(mode);
1827 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1828 goto error;
1829 Py_CLEAR(text);
1830 return stream;
1831
1832 error:
1833 Py_XDECREF(buf);
1834 Py_XDECREF(stream);
1835 Py_XDECREF(text);
1836 Py_XDECREF(raw);
1837
1838 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1839 /* Issue #24891: the file descriptor was closed after the first
1840 is_valid_fd() check was called. Ignore the OSError and set the
1841 stream to None. */
1842 PyErr_Clear();
1843 Py_RETURN_NONE;
1844 }
1845 return NULL;
1846 }
1847
1848 /* Initialize sys.stdin, stdout, stderr and builtins.open */
1849 static PyStatus
init_sys_streams(PyInterpreterState * interp)1850 init_sys_streams(PyInterpreterState *interp)
1851 {
1852 PyObject *iomod = NULL, *wrapper;
1853 PyObject *bimod = NULL;
1854 PyObject *m;
1855 PyObject *std = NULL;
1856 int fd;
1857 PyObject * encoding_attr;
1858 PyStatus res = _PyStatus_OK();
1859 PyConfig *config = &interp->config;
1860
1861 /* Check that stdin is not a directory
1862 Using shell redirection, you can redirect stdin to a directory,
1863 crashing the Python interpreter. Catch this common mistake here
1864 and output a useful error message. Note that under MS Windows,
1865 the shell already prevents that. */
1866 #ifndef MS_WINDOWS
1867 struct _Py_stat_struct sb;
1868 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1869 S_ISDIR(sb.st_mode)) {
1870 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
1871 }
1872 #endif
1873
1874 /* Hack to avoid a nasty recursion issue when Python is invoked
1875 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1876 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1877 goto error;
1878 }
1879 Py_DECREF(m);
1880
1881 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1882 goto error;
1883 }
1884 Py_DECREF(m);
1885
1886 if (!(bimod = PyImport_ImportModule("builtins"))) {
1887 goto error;
1888 }
1889
1890 if (!(iomod = PyImport_ImportModule("io"))) {
1891 goto error;
1892 }
1893 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1894 goto error;
1895 }
1896
1897 /* Set builtins.open */
1898 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1899 Py_DECREF(wrapper);
1900 goto error;
1901 }
1902 Py_DECREF(wrapper);
1903
1904 /* Set sys.stdin */
1905 fd = fileno(stdin);
1906 /* Under some conditions stdin, stdout and stderr may not be connected
1907 * and fileno() may point to an invalid file descriptor. For example
1908 * GUI apps don't have valid standard streams by default.
1909 */
1910 std = create_stdio(config, iomod, fd, 0, "<stdin>",
1911 config->stdio_encoding,
1912 config->stdio_errors);
1913 if (std == NULL)
1914 goto error;
1915 PySys_SetObject("__stdin__", std);
1916 _PySys_SetObjectId(&PyId_stdin, std);
1917 Py_DECREF(std);
1918
1919 /* Set sys.stdout */
1920 fd = fileno(stdout);
1921 std = create_stdio(config, iomod, fd, 1, "<stdout>",
1922 config->stdio_encoding,
1923 config->stdio_errors);
1924 if (std == NULL)
1925 goto error;
1926 PySys_SetObject("__stdout__", std);
1927 _PySys_SetObjectId(&PyId_stdout, std);
1928 Py_DECREF(std);
1929
1930 #if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1931 /* Set sys.stderr, replaces the preliminary stderr */
1932 fd = fileno(stderr);
1933 std = create_stdio(config, iomod, fd, 1, "<stderr>",
1934 config->stdio_encoding,
1935 L"backslashreplace");
1936 if (std == NULL)
1937 goto error;
1938
1939 /* Same as hack above, pre-import stderr's codec to avoid recursion
1940 when import.c tries to write to stderr in verbose mode. */
1941 encoding_attr = PyObject_GetAttrString(std, "encoding");
1942 if (encoding_attr != NULL) {
1943 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
1944 if (std_encoding != NULL) {
1945 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1946 Py_XDECREF(codec_info);
1947 }
1948 Py_DECREF(encoding_attr);
1949 }
1950 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1951
1952 if (PySys_SetObject("__stderr__", std) < 0) {
1953 Py_DECREF(std);
1954 goto error;
1955 }
1956 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1957 Py_DECREF(std);
1958 goto error;
1959 }
1960 Py_DECREF(std);
1961 #endif
1962
1963 goto done;
1964
1965 error:
1966 res = _PyStatus_ERR("can't initialize sys standard streams");
1967
1968 done:
1969 _Py_ClearStandardStreamEncoding();
1970
1971 Py_XDECREF(bimod);
1972 Py_XDECREF(iomod);
1973 return res;
1974 }
1975
1976
1977 static void
_Py_FatalError_DumpTracebacks(int fd,PyInterpreterState * interp,PyThreadState * tstate)1978 _Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
1979 PyThreadState *tstate)
1980 {
1981 fputc('\n', stderr);
1982 fflush(stderr);
1983
1984 /* display the current Python stack */
1985 _Py_DumpTracebackThreads(fd, interp, tstate);
1986 }
1987
1988 /* Print the current exception (if an exception is set) with its traceback,
1989 or display the current Python stack.
1990
1991 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1992 called on catastrophic cases.
1993
1994 Return 1 if the traceback was displayed, 0 otherwise. */
1995
1996 static int
_Py_FatalError_PrintExc(int fd)1997 _Py_FatalError_PrintExc(int fd)
1998 {
1999 PyObject *ferr, *res;
2000 PyObject *exception, *v, *tb;
2001 int has_tb;
2002
2003 PyErr_Fetch(&exception, &v, &tb);
2004 if (exception == NULL) {
2005 /* No current exception */
2006 return 0;
2007 }
2008
2009 ferr = _PySys_GetObjectId(&PyId_stderr);
2010 if (ferr == NULL || ferr == Py_None) {
2011 /* sys.stderr is not set yet or set to None,
2012 no need to try to display the exception */
2013 return 0;
2014 }
2015
2016 PyErr_NormalizeException(&exception, &v, &tb);
2017 if (tb == NULL) {
2018 tb = Py_None;
2019 Py_INCREF(tb);
2020 }
2021 PyException_SetTraceback(v, tb);
2022 if (exception == NULL) {
2023 /* PyErr_NormalizeException() failed */
2024 return 0;
2025 }
2026
2027 has_tb = (tb != Py_None);
2028 PyErr_Display(exception, v, tb);
2029 Py_XDECREF(exception);
2030 Py_XDECREF(v);
2031 Py_XDECREF(tb);
2032
2033 /* sys.stderr may be buffered: call sys.stderr.flush() */
2034 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
2035 if (res == NULL)
2036 PyErr_Clear();
2037 else
2038 Py_DECREF(res);
2039
2040 return has_tb;
2041 }
2042
2043 /* Print fatal error message and abort */
2044
2045 #ifdef MS_WINDOWS
2046 static void
fatal_output_debug(const char * msg)2047 fatal_output_debug(const char *msg)
2048 {
2049 /* buffer of 256 bytes allocated on the stack */
2050 WCHAR buffer[256 / sizeof(WCHAR)];
2051 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2052 size_t msglen;
2053
2054 OutputDebugStringW(L"Fatal Python error: ");
2055
2056 msglen = strlen(msg);
2057 while (msglen) {
2058 size_t i;
2059
2060 if (buflen > msglen) {
2061 buflen = msglen;
2062 }
2063
2064 /* Convert the message to wchar_t. This uses a simple one-to-one
2065 conversion, assuming that the this error message actually uses
2066 ASCII only. If this ceases to be true, we will have to convert. */
2067 for (i=0; i < buflen; ++i) {
2068 buffer[i] = msg[i];
2069 }
2070 buffer[i] = L'\0';
2071 OutputDebugStringW(buffer);
2072
2073 msg += buflen;
2074 msglen -= buflen;
2075 }
2076 OutputDebugStringW(L"\n");
2077 }
2078 #endif
2079
2080
2081 static void
fatal_error_dump_runtime(FILE * stream,_PyRuntimeState * runtime)2082 fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2083 {
2084 fprintf(stream, "Python runtime state: ");
2085 if (runtime->finalizing) {
2086 fprintf(stream, "finalizing (tstate=%p)", runtime->finalizing);
2087 }
2088 else if (runtime->initialized) {
2089 fprintf(stream, "initialized");
2090 }
2091 else if (runtime->core_initialized) {
2092 fprintf(stream, "core initialized");
2093 }
2094 else if (runtime->preinitialized) {
2095 fprintf(stream, "preinitialized");
2096 }
2097 else if (runtime->preinitializing) {
2098 fprintf(stream, "preinitializing");
2099 }
2100 else {
2101 fprintf(stream, "unknown");
2102 }
2103 fprintf(stream, "\n");
2104 fflush(stream);
2105 }
2106
2107
2108 static void _Py_NO_RETURN
fatal_error(const char * prefix,const char * msg,int status)2109 fatal_error(const char *prefix, const char *msg, int status)
2110 {
2111 FILE *stream = stderr;
2112 const int fd = fileno(stream);
2113 static int reentrant = 0;
2114
2115 if (reentrant) {
2116 /* Py_FatalError() caused a second fatal error.
2117 Example: flush_std_files() raises a recursion error. */
2118 goto exit;
2119 }
2120 reentrant = 1;
2121
2122 fprintf(stream, "Fatal Python error: ");
2123 if (prefix) {
2124 fputs(prefix, stream);
2125 fputs(": ", stream);
2126 }
2127 if (msg) {
2128 fputs(msg, stream);
2129 }
2130 else {
2131 fprintf(stream, "<message not set>");
2132 }
2133 fputs("\n", stream);
2134 fflush(stream); /* it helps in Windows debug build */
2135
2136 _PyRuntimeState *runtime = &_PyRuntime;
2137 fatal_error_dump_runtime(stream, runtime);
2138
2139 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2140 PyInterpreterState *interp = NULL;
2141 if (tstate != NULL) {
2142 interp = tstate->interp;
2143 }
2144
2145 /* Check if the current thread has a Python thread state
2146 and holds the GIL.
2147
2148 tss_tstate is NULL if Py_FatalError() is called from a C thread which
2149 has no Python thread state.
2150
2151 tss_tstate != tstate if the current Python thread does not hold the GIL.
2152 */
2153 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2154 int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
2155 if (has_tstate_and_gil) {
2156 /* If an exception is set, print the exception with its traceback */
2157 if (!_Py_FatalError_PrintExc(fd)) {
2158 /* No exception is set, or an exception is set without traceback */
2159 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
2160 }
2161 }
2162 else {
2163 _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
2164 }
2165
2166 /* The main purpose of faulthandler is to display the traceback.
2167 This function already did its best to display a traceback.
2168 Disable faulthandler to prevent writing a second traceback
2169 on abort(). */
2170 _PyFaulthandler_Fini();
2171
2172 /* Check if the current Python thread hold the GIL */
2173 if (has_tstate_and_gil) {
2174 /* Flush sys.stdout and sys.stderr */
2175 flush_std_files();
2176 }
2177
2178 #ifdef MS_WINDOWS
2179 fatal_output_debug(msg);
2180 #endif /* MS_WINDOWS */
2181
2182 exit:
2183 if (status < 0) {
2184 #if defined(MS_WINDOWS) && defined(_DEBUG)
2185 DebugBreak();
2186 #endif
2187 abort();
2188 }
2189 else {
2190 exit(status);
2191 }
2192 }
2193
2194 void _Py_NO_RETURN
Py_FatalError(const char * msg)2195 Py_FatalError(const char *msg)
2196 {
2197 fatal_error(NULL, msg, -1);
2198 }
2199
2200 void _Py_NO_RETURN
Py_ExitStatusException(PyStatus status)2201 Py_ExitStatusException(PyStatus status)
2202 {
2203 if (_PyStatus_IS_EXIT(status)) {
2204 exit(status.exitcode);
2205 }
2206 else if (_PyStatus_IS_ERROR(status)) {
2207 fatal_error(status.func, status.err_msg, 1);
2208 }
2209 else {
2210 Py_FatalError("Py_ExitStatusException() must not be called on success");
2211 }
2212 }
2213
2214 /* Clean up and exit */
2215
2216 # include "pythread.h"
2217
2218 /* For the atexit module. */
_Py_PyAtExit(void (* func)(PyObject *),PyObject * module)2219 void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
2220 {
2221 PyInterpreterState *is = _PyInterpreterState_Get();
2222
2223 /* Guard against API misuse (see bpo-17852) */
2224 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2225
2226 is->pyexitfunc = func;
2227 is->pyexitmodule = module;
2228 }
2229
2230 static void
call_py_exitfuncs(PyInterpreterState * istate)2231 call_py_exitfuncs(PyInterpreterState *istate)
2232 {
2233 if (istate->pyexitfunc == NULL)
2234 return;
2235
2236 (*istate->pyexitfunc)(istate->pyexitmodule);
2237 PyErr_Clear();
2238 }
2239
2240 /* Wait until threading._shutdown completes, provided
2241 the threading module was imported in the first place.
2242 The shutdown routine will wait until all non-daemon
2243 "threading" threads have completed. */
2244 static void
wait_for_thread_shutdown(void)2245 wait_for_thread_shutdown(void)
2246 {
2247 _Py_IDENTIFIER(_shutdown);
2248 PyObject *result;
2249 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
2250 if (threading == NULL) {
2251 if (PyErr_Occurred()) {
2252 PyErr_WriteUnraisable(NULL);
2253 }
2254 /* else: threading not imported */
2255 return;
2256 }
2257 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
2258 if (result == NULL) {
2259 PyErr_WriteUnraisable(threading);
2260 }
2261 else {
2262 Py_DECREF(result);
2263 }
2264 Py_DECREF(threading);
2265 }
2266
2267 #define NEXITFUNCS 32
Py_AtExit(void (* func)(void))2268 int Py_AtExit(void (*func)(void))
2269 {
2270 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
2271 return -1;
2272 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
2273 return 0;
2274 }
2275
2276 static void
call_ll_exitfuncs(_PyRuntimeState * runtime)2277 call_ll_exitfuncs(_PyRuntimeState *runtime)
2278 {
2279 while (runtime->nexitfuncs > 0) {
2280 /* pop last function from the list */
2281 runtime->nexitfuncs--;
2282 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2283 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2284
2285 exitfunc();
2286 }
2287
2288 fflush(stdout);
2289 fflush(stderr);
2290 }
2291
2292 void _Py_NO_RETURN
Py_Exit(int sts)2293 Py_Exit(int sts)
2294 {
2295 if (Py_FinalizeEx() < 0) {
2296 sts = 120;
2297 }
2298
2299 exit(sts);
2300 }
2301
2302 static PyStatus
init_signals(void)2303 init_signals(void)
2304 {
2305 #ifdef SIGPIPE
2306 PyOS_setsig(SIGPIPE, SIG_IGN);
2307 #endif
2308 #ifdef SIGXFZ
2309 PyOS_setsig(SIGXFZ, SIG_IGN);
2310 #endif
2311 #ifdef SIGXFSZ
2312 PyOS_setsig(SIGXFSZ, SIG_IGN);
2313 #endif
2314 PyOS_InitInterrupts(); /* May imply initsignal() */
2315 if (PyErr_Occurred()) {
2316 return _PyStatus_ERR("can't import signal");
2317 }
2318 return _PyStatus_OK();
2319 }
2320
2321
2322 /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2323 *
2324 * All of the code in this function must only use async-signal-safe functions,
2325 * listed at `man 7 signal` or
2326 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2327 */
2328 void
_Py_RestoreSignals(void)2329 _Py_RestoreSignals(void)
2330 {
2331 #ifdef SIGPIPE
2332 PyOS_setsig(SIGPIPE, SIG_DFL);
2333 #endif
2334 #ifdef SIGXFZ
2335 PyOS_setsig(SIGXFZ, SIG_DFL);
2336 #endif
2337 #ifdef SIGXFSZ
2338 PyOS_setsig(SIGXFSZ, SIG_DFL);
2339 #endif
2340 }
2341
2342
2343 /*
2344 * The file descriptor fd is considered ``interactive'' if either
2345 * a) isatty(fd) is TRUE, or
2346 * b) the -i flag was given, and the filename associated with
2347 * the descriptor is NULL or "<stdin>" or "???".
2348 */
2349 int
Py_FdIsInteractive(FILE * fp,const char * filename)2350 Py_FdIsInteractive(FILE *fp, const char *filename)
2351 {
2352 if (isatty((int)fileno(fp)))
2353 return 1;
2354 if (!Py_InteractiveFlag)
2355 return 0;
2356 return (filename == NULL) ||
2357 (strcmp(filename, "<stdin>") == 0) ||
2358 (strcmp(filename, "???") == 0);
2359 }
2360
2361
2362 /* Wrappers around sigaction() or signal(). */
2363
2364 PyOS_sighandler_t
PyOS_getsig(int sig)2365 PyOS_getsig(int sig)
2366 {
2367 #ifdef HAVE_SIGACTION
2368 struct sigaction context;
2369 if (sigaction(sig, NULL, &context) == -1)
2370 return SIG_ERR;
2371 return context.sa_handler;
2372 #else
2373 PyOS_sighandler_t handler;
2374 /* Special signal handling for the secure CRT in Visual Studio 2005 */
2375 #if defined(_MSC_VER) && _MSC_VER >= 1400
2376 switch (sig) {
2377 /* Only these signals are valid */
2378 case SIGINT:
2379 case SIGILL:
2380 case SIGFPE:
2381 case SIGSEGV:
2382 case SIGTERM:
2383 case SIGBREAK:
2384 case SIGABRT:
2385 break;
2386 /* Don't call signal() with other values or it will assert */
2387 default:
2388 return SIG_ERR;
2389 }
2390 #endif /* _MSC_VER && _MSC_VER >= 1400 */
2391 handler = signal(sig, SIG_IGN);
2392 if (handler != SIG_ERR)
2393 signal(sig, handler);
2394 return handler;
2395 #endif
2396 }
2397
2398 /*
2399 * All of the code in this function must only use async-signal-safe functions,
2400 * listed at `man 7 signal` or
2401 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2402 */
2403 PyOS_sighandler_t
PyOS_setsig(int sig,PyOS_sighandler_t handler)2404 PyOS_setsig(int sig, PyOS_sighandler_t handler)
2405 {
2406 #ifdef HAVE_SIGACTION
2407 /* Some code in Modules/signalmodule.c depends on sigaction() being
2408 * used here if HAVE_SIGACTION is defined. Fix that if this code
2409 * changes to invalidate that assumption.
2410 */
2411 struct sigaction context, ocontext;
2412 context.sa_handler = handler;
2413 sigemptyset(&context.sa_mask);
2414 context.sa_flags = 0;
2415 if (sigaction(sig, &context, &ocontext) == -1)
2416 return SIG_ERR;
2417 return ocontext.sa_handler;
2418 #else
2419 PyOS_sighandler_t oldhandler;
2420 oldhandler = signal(sig, handler);
2421 #ifdef HAVE_SIGINTERRUPT
2422 siginterrupt(sig, 1);
2423 #endif
2424 return oldhandler;
2425 #endif
2426 }
2427
2428 #ifdef __cplusplus
2429 }
2430 #endif
2431