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