blob: e08f290d8d14712e90486fdad26e84eea1154514 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
Victor Stinner3bb183d2018-11-22 18:38:38 +01006#undef Yield /* undefine macro conflicting with <winbase.h> */
Victor Stinnerf684d832019-03-01 03:44:13 +01007#include "pycore_coreconfig.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +01008#include "pycore_context.h"
Victor Stinner353933e2018-11-23 13:08:26 +01009#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010010#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010011#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010012#include "pycore_pylifecycle.h"
13#include "pycore_pymem.h"
14#include "pycore_pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100015#include "grammar.h"
16#include "node.h"
17#include "token.h"
18#include "parsetok.h"
19#include "errcode.h"
20#include "code.h"
21#include "symtable.h"
22#include "ast.h"
23#include "marshal.h"
24#include "osdefs.h"
25#include <locale.h>
26
27#ifdef HAVE_SIGNAL_H
28#include <signal.h>
29#endif
30
31#ifdef MS_WINDOWS
32#include "malloc.h" /* for alloca */
33#endif
34
35#ifdef HAVE_LANGINFO_H
36#include <langinfo.h>
37#endif
38
39#ifdef MS_WINDOWS
40#undef BYTE
41#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070042
43extern PyTypeObject PyWindowsConsoleIO_Type;
44#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100045#endif
46
47_Py_IDENTIFIER(flush);
48_Py_IDENTIFIER(name);
49_Py_IDENTIFIER(stdin);
50_Py_IDENTIFIER(stdout);
51_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060052_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100053
54#ifdef __cplusplus
55extern "C" {
56#endif
57
Nick Coghland6009512014-11-20 21:39:37 +100058extern grammar _PyParser_Grammar; /* From graminit.c */
59
60/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061static _PyInitError add_main_module(PyInterpreterState *interp);
62static _PyInitError initfsencoding(PyInterpreterState *interp);
63static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010064static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010066static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100067static void wait_for_thread_shutdown(void);
68static void call_ll_exitfuncs(void);
Nick Coghland6009512014-11-20 21:39:37 +100069
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080070int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010072static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075_PyRuntime_Initialize(void)
76{
77 /* XXX We only initialize once in the process, which aligns with
78 the static initialization of the former globals now found in
79 _PyRuntime. However, _PyRuntime *should* be initialized with
80 every Py_Initialize() call, but doing so breaks the runtime.
81 This is because the runtime state is not properly finalized
82 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010083 if (runtime_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084 return _Py_INIT_OK();
85 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010086 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087
88 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91void
92_PyRuntime_Finalize(void)
93{
94 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010095 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
98int
99_Py_IsFinalizing(void)
100{
101 return _PyRuntime.finalizing != NULL;
102}
103
Nick Coghland6009512014-11-20 21:39:37 +1000104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
Nick Coghland6009512014-11-20 21:39:37 +1000121
Eric Snow1abcf672017-05-23 21:46:51 -0700122int
123_Py_IsCoreInitialized(void)
124{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700126}
Nick Coghland6009512014-11-20 21:39:37 +1000127
128int
129Py_IsInitialized(void)
130{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000132}
133
Nick Coghlan6ea41862017-06-11 13:16:15 +1000134
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000135/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
136 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000137 initializations fail, a fatal error is issued and the function does
138 not return. On return, the first thread and interpreter state have
139 been created.
140
141 Locking: you must hold the interpreter lock while calling this.
142 (If the lock has not yet been initialized, that's equivalent to
143 having the lock, but you cannot use multiple threads.)
144
145*/
146
Nick Coghland6009512014-11-20 21:39:37 +1000147static char*
148get_codec_name(const char *encoding)
149{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200150 const char *name_utf8;
151 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000152 PyObject *codec, *name = NULL;
153
154 codec = _PyCodec_Lookup(encoding);
155 if (!codec)
156 goto error;
157
158 name = _PyObject_GetAttrId(codec, &PyId_name);
159 Py_CLEAR(codec);
160 if (!name)
161 goto error;
162
Serhiy Storchaka06515832016-11-20 09:13:07 +0200163 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000164 if (name_utf8 == NULL)
165 goto error;
166 name_str = _PyMem_RawStrdup(name_utf8);
167 Py_DECREF(name);
168 if (name_str == NULL) {
169 PyErr_NoMemory();
170 return NULL;
171 }
172 return name_str;
173
174error:
175 Py_XDECREF(codec);
176 Py_XDECREF(name);
177 return NULL;
178}
179
Nick Coghland6009512014-11-20 21:39:37 +1000180
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800181static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700182initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000183{
184 PyObject *importlib;
185 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000186 PyObject *value;
187
188 /* Import _importlib through its frozen version, _frozen_importlib. */
189 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800190 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000191 }
192 else if (Py_VerboseFlag) {
193 PySys_FormatStderr("import _frozen_importlib # frozen\n");
194 }
195 importlib = PyImport_AddModule("_frozen_importlib");
196 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800197 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 interp->importlib = importlib;
200 Py_INCREF(interp->importlib);
201
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300202 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
203 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800204 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300205 Py_INCREF(interp->import_func);
206
Victor Stinnercd6e6942015-09-18 09:11:57 +0200207 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800208 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000209 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800210 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000211 }
212 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200213 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000214 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600215 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800216 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000217 }
218
Victor Stinnercd6e6942015-09-18 09:11:57 +0200219 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000220 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
221 if (value == NULL) {
222 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800223 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000224 }
225 Py_DECREF(value);
226 Py_DECREF(impmod);
227
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800228 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000229}
230
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800231static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700232initexternalimport(PyInterpreterState *interp)
233{
234 PyObject *value;
235 value = PyObject_CallMethod(interp->importlib,
236 "_install_external_importers", "");
237 if (value == NULL) {
238 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800239 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700240 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200241 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300242 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700243}
Nick Coghland6009512014-11-20 21:39:37 +1000244
Nick Coghlan6ea41862017-06-11 13:16:15 +1000245/* Helper functions to better handle the legacy C locale
246 *
247 * The legacy C locale assumes ASCII as the default text encoding, which
248 * causes problems not only for the CPython runtime, but also other
249 * components like GNU readline.
250 *
251 * Accordingly, when the CLI detects it, it attempts to coerce it to a
252 * more capable UTF-8 based alternative as follows:
253 *
254 * if (_Py_LegacyLocaleDetected()) {
255 * _Py_CoerceLegacyLocale();
256 * }
257 *
258 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
259 *
260 * Locale coercion also impacts the default error handler for the standard
261 * streams: while the usual default is "strict", the default for the legacy
262 * C locale and for any of the coercion target locales is "surrogateescape".
263 */
264
265int
266_Py_LegacyLocaleDetected(void)
267{
268#ifndef MS_WINDOWS
269 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000270 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
271 * the POSIX locale as a simple alias for the C locale, so
272 * we may also want to check for that explicitly.
273 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000274 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
275 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
276#else
277 /* Windows uses code pages instead of locales, so no locale is legacy */
278 return 0;
279#endif
280}
281
Nick Coghlaneb817952017-06-18 12:29:42 +1000282static const char *_C_LOCALE_WARNING =
283 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
284 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
285 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
286 "locales is recommended.\n";
287
Nick Coghlaneb817952017-06-18 12:29:42 +1000288static void
Victor Stinner94540602017-12-16 04:54:22 +0100289_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000290{
Victor Stinner5a02e0d2019-03-05 12:32:09 +0100291 if (core_config->preconfig.coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200292 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000293 }
294}
295
Nick Coghlan6ea41862017-06-11 13:16:15 +1000296typedef struct _CandidateLocale {
297 const char *locale_name; /* The locale to try as a coercion target */
298} _LocaleCoercionTarget;
299
300static _LocaleCoercionTarget _TARGET_LOCALES[] = {
301 {"C.UTF-8"},
302 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000303 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304 {NULL}
305};
306
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200307
308int
309_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000310{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200311 const _LocaleCoercionTarget *target = NULL;
312 for (target = _TARGET_LOCALES; target->locale_name; target++) {
313 if (strcmp(ctype_loc, target->locale_name) == 0) {
314 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000315 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200316 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200317 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318}
319
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200320
Nick Coghlan6ea41862017-06-11 13:16:15 +1000321#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100322static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
324 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
325
326static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200327_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328{
329 const char *newloc = target->locale_name;
330
331 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100332 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000333
334 /* Set the relevant locale environment variable */
335 if (setenv("LC_CTYPE", newloc, 1)) {
336 fprintf(stderr,
337 "Error setting LC_CTYPE, skipping C locale coercion\n");
338 return;
339 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200340 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100341 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000342 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000343
344 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100345 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000346}
347#endif
348
349void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200350_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351{
352#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200353 char *oldloc = NULL;
354
355 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
356 if (oldloc == NULL) {
357 return;
358 }
359
Victor Stinner94540602017-12-16 04:54:22 +0100360 const char *locale_override = getenv("LC_ALL");
361 if (locale_override == NULL || *locale_override == '\0') {
362 /* LC_ALL is also not set (or is set to an empty string) */
363 const _LocaleCoercionTarget *target = NULL;
364 for (target = _TARGET_LOCALES; target->locale_name; target++) {
365 const char *new_locale = setlocale(LC_CTYPE,
366 target->locale_name);
367 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100368#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100369defined(HAVE_LANGINFO_H) && defined(CODESET)
370 /* Also ensure that nl_langinfo works in this locale */
371 char *codeset = nl_langinfo(CODESET);
372 if (!codeset || *codeset == '\0') {
373 /* CODESET is not set or empty, so skip coercion */
374 new_locale = NULL;
375 _Py_SetLocaleFromEnv(LC_CTYPE);
376 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000377 }
Victor Stinner94540602017-12-16 04:54:22 +0100378#endif
379 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200380 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200381 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000382 }
383 }
384 }
385 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200386
387 setlocale(LC_CTYPE, oldloc);
388
389done:
390 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000391#endif
392}
393
xdegaye1588be62017-11-12 12:45:59 +0100394/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
395 * isolate the idiosyncrasies of different libc implementations. It reads the
396 * appropriate environment variable and uses its value to select the locale for
397 * 'category'. */
398char *
399_Py_SetLocaleFromEnv(int category)
400{
Victor Stinner353933e2018-11-23 13:08:26 +0100401 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100402#ifdef __ANDROID__
403 const char *locale;
404 const char **pvar;
405#ifdef PY_COERCE_C_LOCALE
406 const char *coerce_c_locale;
407#endif
408 const char *utf8_locale = "C.UTF-8";
409 const char *env_var_set[] = {
410 "LC_ALL",
411 "LC_CTYPE",
412 "LANG",
413 NULL,
414 };
415
416 /* Android setlocale(category, "") doesn't check the environment variables
417 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
418 * check the environment variables listed in env_var_set. */
419 for (pvar=env_var_set; *pvar; pvar++) {
420 locale = getenv(*pvar);
421 if (locale != NULL && *locale != '\0') {
422 if (strcmp(locale, utf8_locale) == 0 ||
423 strcmp(locale, "en_US.UTF-8") == 0) {
424 return setlocale(category, utf8_locale);
425 }
426 return setlocale(category, "C");
427 }
428 }
429
430 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
431 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
432 * Quote from POSIX section "8.2 Internationalization Variables":
433 * "4. If the LANG environment variable is not set or is set to the empty
434 * string, the implementation-defined default locale shall be used." */
435
436#ifdef PY_COERCE_C_LOCALE
437 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
438 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
439 /* Some other ported code may check the environment variables (e.g. in
440 * extension modules), so we make sure that they match the locale
441 * configuration */
442 if (setenv("LC_CTYPE", utf8_locale, 1)) {
443 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
444 "environment variable to %s\n", utf8_locale);
445 }
446 }
447#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100448 res = setlocale(category, utf8_locale);
449#else /* !defined(__ANDROID__) */
450 res = setlocale(category, "");
451#endif
452 _Py_ResetForceASCII();
453 return res;
xdegaye1588be62017-11-12 12:45:59 +0100454}
455
Nick Coghlan6ea41862017-06-11 13:16:15 +1000456
Eric Snow1abcf672017-05-23 21:46:51 -0700457/* Global initializations. Can be undone by Py_Finalize(). Don't
458 call this twice without an intervening Py_Finalize() call.
459
Victor Stinner1dc6e392018-07-25 02:49:17 +0200460 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700461 must have a corresponding call to Py_Finalize.
462
463 Locking: you must hold the interpreter lock while calling these APIs.
464 (If the lock has not yet been initialized, that's equivalent to
465 having the lock, but you cannot use multiple threads.)
466
467*/
468
Victor Stinner1dc6e392018-07-25 02:49:17 +0200469static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100470_Py_Initialize_ReconfigureCore(PyInterpreterState **interp_p,
Victor Stinner1dc6e392018-07-25 02:49:17 +0200471 const _PyCoreConfig *core_config)
472{
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100473 PyThreadState *tstate = _PyThreadState_GET();
474 if (!tstate) {
475 return _Py_INIT_ERR("failed to read thread state");
476 }
477
478 PyInterpreterState *interp = tstate->interp;
479 if (interp == NULL) {
480 return _Py_INIT_ERR("can't make main interpreter");
481 }
482 *interp_p = interp;
483
Victor Stinner1dc6e392018-07-25 02:49:17 +0200484 _PyCoreConfig_SetGlobalConfig(core_config);
485
486 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
487 return _Py_INIT_ERR("failed to copy core config");
488 }
489 core_config = &interp->core_config;
490
491 if (core_config->_install_importlib) {
492 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
493 if (_Py_INIT_FAILED(err)) {
494 return err;
495 }
496 }
497 return _Py_INIT_OK();
498}
499
500
Victor Stinner1dc6e392018-07-25 02:49:17 +0200501static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100502pycore_init_runtime(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000503{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200504 if (_PyRuntime.initialized) {
505 return _Py_INIT_ERR("main interpreter already initialized");
506 }
Victor Stinnerda273412017-12-15 01:46:02 +0100507
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200508 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000509
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100510 _PyInitError err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800511 if (_Py_INIT_FAILED(err)) {
512 return err;
513 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600514
Eric Snow1abcf672017-05-23 21:46:51 -0700515 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
516 * threads behave a little more gracefully at interpreter shutdown.
517 * We clobber it here so the new interpreter can start with a clean
518 * slate.
519 *
520 * However, this may still lead to misbehaviour if there are daemon
521 * threads still hanging around from a previous Py_Initialize/Finalize
522 * pair :(
523 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600524 _PyRuntime.finalizing = NULL;
525
Victor Stinnerda273412017-12-15 01:46:02 +0100526 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800527 if (_Py_INIT_FAILED(err)) {
528 return err;
529 }
530
Victor Stinnera7368ac2017-11-15 18:11:45 -0800531 err = _PyInterpreterState_Enable(&_PyRuntime);
532 if (_Py_INIT_FAILED(err)) {
533 return err;
534 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100535 return _Py_INIT_OK();
536}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800537
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100538
539static _PyInitError
540pycore_create_interpreter(const _PyCoreConfig *core_config,
541 PyInterpreterState **interp_p)
542{
543 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100544 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800545 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100546 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200547 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100548
549 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
550 return _Py_INIT_ERR("failed to copy core config");
551 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200552 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000553
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200554 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000555 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800556 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000557 (void) PyThreadState_Swap(tstate);
558
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000559 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000560 destroying the GIL might fail when it is being referenced from
561 another running thread (see issue #9901).
562 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000563 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000564 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100565
Nick Coghland6009512014-11-20 21:39:37 +1000566 /* Auto-thread-state API */
567 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000568
Victor Stinner2914bb32018-01-29 11:57:45 +0100569 /* Create the GIL */
570 PyEval_InitThreads();
571
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100572 return _Py_INIT_OK();
573}
Nick Coghland6009512014-11-20 21:39:37 +1000574
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100575
576static _PyInitError
577pycore_init_types(void)
578{
Victor Stinnerab672812019-01-23 15:04:40 +0100579 _PyInitError err = _PyTypes_Init();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100580 if (_Py_INIT_FAILED(err)) {
581 return err;
582 }
583
584 err = _PyUnicode_Init();
585 if (_Py_INIT_FAILED(err)) {
586 return err;
587 }
588
589 if (_PyStructSequence_Init() < 0) {
590 return _Py_INIT_ERR("can't initialize structseq");
591 }
592
593 if (!_PyLong_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800594 return _Py_INIT_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100595 }
Nick Coghland6009512014-11-20 21:39:37 +1000596
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100597 err = _PyExc_Init();
598 if (_Py_INIT_FAILED(err)) {
599 return err;
600 }
601
602 if (!_PyFloat_Init()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800603 return _Py_INIT_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100604 }
Nick Coghland6009512014-11-20 21:39:37 +1000605
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100606 if (!_PyContext_Init()) {
607 return _Py_INIT_ERR("can't init context");
608 }
609 return _Py_INIT_OK();
610}
611
612
613static _PyInitError
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100614pycore_init_builtins(PyInterpreterState *interp)
615{
616 PyObject *bimod = _PyBuiltin_Init();
617 if (bimod == NULL) {
618 return _Py_INIT_ERR("can't initialize builtins modules");
619 }
620 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
621
622 interp->builtins = PyModule_GetDict(bimod);
623 if (interp->builtins == NULL) {
624 return _Py_INIT_ERR("can't initialize builtins dict");
625 }
626 Py_INCREF(interp->builtins);
627
628 _PyInitError err = _PyBuiltins_AddExceptions(bimod);
629 if (_Py_INIT_FAILED(err)) {
630 return err;
631 }
632 return _Py_INIT_OK();
633}
634
635
636static _PyInitError
637pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
638{
639 _PyInitError err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800640 if (_Py_INIT_FAILED(err)) {
641 return err;
642 }
Nick Coghland6009512014-11-20 21:39:37 +1000643
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800644 err = _PyImportHooks_Init();
645 if (_Py_INIT_FAILED(err)) {
646 return err;
647 }
Nick Coghland6009512014-11-20 21:39:37 +1000648
649 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100650 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100651 return _Py_INIT_ERR("can't initialize warnings");
652 }
Nick Coghland6009512014-11-20 21:39:37 +1000653
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100654 if (interp->core_config._install_importlib) {
655 err = _PyCoreConfig_SetPathConfig(&interp->core_config);
Victor Stinnerb1147e42018-07-21 02:06:16 +0200656 if (_Py_INIT_FAILED(err)) {
657 return err;
658 }
659 }
660
Eric Snow1abcf672017-05-23 21:46:51 -0700661 /* This call sets up builtin and frozen import support */
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100662 if (interp->core_config._install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800663 err = initimport(interp, sysmod);
664 if (_Py_INIT_FAILED(err)) {
665 return err;
666 }
Eric Snow1abcf672017-05-23 21:46:51 -0700667 }
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100668 return _Py_INIT_OK();
669}
670
671
672static _PyInitError
673_Py_InitializeCore_impl(PyInterpreterState **interp_p,
674 const _PyCoreConfig *core_config)
675{
676 PyInterpreterState *interp;
677
678 _PyInitError err = pycore_init_runtime(core_config);
679 if (_Py_INIT_FAILED(err)) {
680 return err;
681 }
682
683 err = pycore_create_interpreter(core_config, &interp);
684 if (_Py_INIT_FAILED(err)) {
685 return err;
686 }
687 core_config = &interp->core_config;
688 *interp_p = interp;
689
690 err = pycore_init_types();
691 if (_Py_INIT_FAILED(err)) {
692 return err;
693 }
694
695 PyObject *sysmod;
Victor Stinnerab672812019-01-23 15:04:40 +0100696 err = _PySys_Create(interp, &sysmod);
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100697 if (_Py_INIT_FAILED(err)) {
698 return err;
699 }
700
701 err = pycore_init_builtins(interp);
702 if (_Py_INIT_FAILED(err)) {
703 return err;
704 }
705
706 err = pycore_init_import_warnings(interp, sysmod);
707 if (_Py_INIT_FAILED(err)) {
708 return err;
709 }
Eric Snow1abcf672017-05-23 21:46:51 -0700710
711 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600712 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800713 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700714}
715
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100716
Victor Stinnerf29084d2019-03-20 02:20:13 +0100717static _PyInitError
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100718pyinit_preinit(_PyPreConfig *config,
719 const _PyPreConfig *src_config,
720 const _PyCoreConfig *coreconfig)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100721{
722 _PyInitError err;
723
724 err = _PyRuntime_Initialize();
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100725 if (_Py_INIT_FAILED(err)) {
726 return err;
727 }
728
Victor Stinnerf72346c2019-03-25 17:54:58 +0100729 if (_PyRuntime.pre_initialized) {
730 /* If it's already configured: ignored the new configuration */
731 return _Py_INIT_OK();
Victor Stinnerf29084d2019-03-20 02:20:13 +0100732 }
733
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100734 if (!src_config && coreconfig) {
735 src_config = &coreconfig->preconfig;
736 }
737
Victor Stinnerf72346c2019-03-25 17:54:58 +0100738 if (src_config) {
739 if (_PyPreConfig_Copy(config, src_config) < 0) {
740 return _Py_INIT_ERR("failed to copy pre config");
741 }
742 }
743
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100744 err = _PyPreConfig_Read(config, NULL, coreconfig);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100745 if (_Py_INIT_FAILED(err)) {
746 return err;
747 }
748
Victor Stinnerf72346c2019-03-25 17:54:58 +0100749 err = _PyPreConfig_Write(config);
750 if (_Py_INIT_FAILED(err)) {
751 return err;
752 }
753
754 _PyRuntime.pre_initialized = 1;
755 return _Py_INIT_OK();
756}
757
758
759_PyInitError
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100760_Py_PreInitialize(void)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100761{
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100762 _PyPreConfig config = _PyPreConfig_INIT;
763 _PyInitError err = pyinit_preinit(&config, NULL, NULL);
764 _PyPreConfig_Clear(&config);
765 return err;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100766}
767
768
769_PyInitError
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100770_Py_PreInitializeFromPreConfig(_PyPreConfig *config)
771{
772 return pyinit_preinit(config, NULL, NULL);
773}
774
775
776_PyInitError
777_Py_PreInitializeFromConfig(const _PyCoreConfig *coreconfig)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100778{
Victor Stinnerf72346c2019-03-25 17:54:58 +0100779 _PyPreConfig config = _PyPreConfig_INIT;
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100780 _PyInitError err = pyinit_preinit(&config, NULL, coreconfig);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100781 _PyPreConfig_Clear(&config);
782 return err;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100783}
784
785
786static _PyInitError
787pyinit_coreconfig(_PyCoreConfig *config, const _PyCoreConfig *src_config,
788 PyInterpreterState **interp_p)
789{
Victor Stinnerc656e252019-03-06 01:13:43 +0100790 if (_PyCoreConfig_Copy(config, src_config) < 0) {
791 return _Py_INIT_ERR("failed to copy core config");
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100792 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100793
Victor Stinnerf72346c2019-03-25 17:54:58 +0100794 _PyInitError err = _PyCoreConfig_Read(config);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100795 if (_Py_INIT_FAILED(err)) {
796 return err;
797 }
798
799 if (!_PyRuntime.core_initialized) {
800 return _Py_InitializeCore_impl(interp_p, config);
801 }
802 else {
803 return _Py_Initialize_ReconfigureCore(interp_p, config);
804 }
805}
806
807
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100808/* Begin interpreter initialization
809 *
810 * On return, the first thread and interpreter state have been created,
811 * but the compiler, signal handling, multithreading and
812 * multiple interpreter support, and codec infrastructure are not yet
813 * available.
814 *
815 * The import system will support builtin and frozen modules only.
816 * The only supported io is writing to sys.stderr
817 *
818 * If any operation invoked by this function fails, a fatal error is
819 * issued and the function does not return.
820 *
821 * Any code invoked from this function should *not* assume it has access
822 * to the Python C API (unless the API is explicitly listed as being
823 * safe to call without calling Py_Initialize first)
824 */
Victor Stinner1dc6e392018-07-25 02:49:17 +0200825_PyInitError
826_Py_InitializeCore(PyInterpreterState **interp_p,
827 const _PyCoreConfig *src_config)
828{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200829 _PyInitError err;
830
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100831 assert(src_config != NULL);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200832
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100833 err = _Py_PreInitializeFromConfig(src_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200834 if (_Py_INIT_FAILED(err)) {
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100835 return err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200836 }
837
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100838 _PyCoreConfig local_config = _PyCoreConfig_INIT;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100839 err = pyinit_coreconfig(&local_config, src_config, interp_p);
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100840 _PyCoreConfig_Clear(&local_config);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200841 return err;
842}
843
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200844/* Py_Initialize() has already been called: update the main interpreter
845 configuration. Example of bpo-34008: Py_Main() called after
846 Py_Initialize(). */
847static _PyInitError
848_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
849 const _PyMainInterpreterConfig *config)
850{
851 if (config->argv != NULL) {
852 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
853 if (res < 0) {
854 return _Py_INIT_ERR("fail to set sys.argv");
855 }
856 }
857 return _Py_INIT_OK();
858}
859
Eric Snowc7ec9982017-05-23 23:00:52 -0700860/* Update interpreter state based on supplied configuration settings
861 *
862 * After calling this function, most of the restrictions on the interpreter
863 * are lifted. The only remaining incomplete settings are those related
864 * to the main module (sys.argv[0], __main__ metadata)
865 *
866 * Calling this when the interpreter is not initializing, is already
867 * initialized or without a valid current thread state is a fatal error.
868 * Other errors should be reported as normal Python exceptions with a
869 * non-zero return code.
870 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800871_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200872_Py_InitializeMainInterpreter(PyInterpreterState *interp,
873 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700874{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600875 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800876 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700877 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700878
Victor Stinner1dc6e392018-07-25 02:49:17 +0200879 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100880 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
881 return _Py_INIT_ERR("failed to copy main interpreter config");
882 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200883 config = &interp->config;
884 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700885
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200886 if (_PyRuntime.initialized) {
887 return _Py_ReconfigureMainInterpreter(interp, config);
888 }
889
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200890 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700891 /* Special mode for freeze_importlib: run with no import system
892 *
893 * This means anything which needs support from extension modules
894 * or pure Python code in the standard library won't work.
895 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600896 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800897 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700898 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100899
Victor Stinner33c377e2017-12-05 15:12:41 +0100900 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100902 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200903
Victor Stinnerab672812019-01-23 15:04:40 +0100904 if (_PySys_InitMain(interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800905 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100906 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800907
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200908 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909 if (_Py_INIT_FAILED(err)) {
910 return err;
911 }
Nick Coghland6009512014-11-20 21:39:37 +1000912
913 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200914 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800915 if (_Py_INIT_FAILED(err)) {
916 return err;
917 }
Nick Coghland6009512014-11-20 21:39:37 +1000918
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 err = initfsencoding(interp);
920 if (_Py_INIT_FAILED(err)) {
921 return err;
922 }
Nick Coghland6009512014-11-20 21:39:37 +1000923
Victor Stinner1f151112017-11-23 10:43:14 +0100924 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 err = initsigs(); /* Signal handling stuff, including initintr() */
926 if (_Py_INIT_FAILED(err)) {
927 return err;
928 }
929 }
Nick Coghland6009512014-11-20 21:39:37 +1000930
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200931 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800932 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200933 }
Nick Coghland6009512014-11-20 21:39:37 +1000934
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800935 err = add_main_module(interp);
936 if (_Py_INIT_FAILED(err)) {
937 return err;
938 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800939
Victor Stinner91106cd2017-12-13 12:29:09 +0100940 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800941 if (_Py_INIT_FAILED(err)) {
942 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800943 }
Nick Coghland6009512014-11-20 21:39:37 +1000944
945 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100946 PyObject *warnoptions = PySys_GetObject("warnoptions");
947 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100948 {
Nick Coghland6009512014-11-20 21:39:37 +1000949 PyObject *warnings_module = PyImport_ImportModule("warnings");
950 if (warnings_module == NULL) {
951 fprintf(stderr, "'import warnings' failed; traceback:\n");
952 PyErr_Print();
953 }
954 Py_XDECREF(warnings_module);
955 }
956
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600957 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700958
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200959 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 err = initsite(); /* Module site */
961 if (_Py_INIT_FAILED(err)) {
962 return err;
963 }
964 }
Victor Stinnercf215042018-08-29 22:56:06 +0200965
966#ifndef MS_WINDOWS
967 _emit_stderr_warning_for_legacy_locale(core_config);
968#endif
969
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800970 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000971}
972
Eric Snowc7ec9982017-05-23 23:00:52 -0700973#undef _INIT_DEBUG_PRINT
974
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800975_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200976_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700977{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700978 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800979 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200980 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800981 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200982 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800983 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200984 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100985
Victor Stinner9cfc0022017-12-20 19:36:46 +0100986 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200987 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100988 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200989 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800990 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100991 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800992 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200993 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800994 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200995 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700996}
997
998
999void
Nick Coghland6009512014-11-20 21:39:37 +10001000Py_InitializeEx(int install_sigs)
1001{
Victor Stinner1dc6e392018-07-25 02:49:17 +02001002 if (_PyRuntime.initialized) {
1003 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1004 return;
1005 }
1006
1007 _PyInitError err;
1008 _PyCoreConfig config = _PyCoreConfig_INIT;
1009 config.install_signal_handlers = install_sigs;
1010
1011 err = _Py_InitializeFromConfig(&config);
1012 _PyCoreConfig_Clear(&config);
1013
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001014 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001015 _Py_ExitInitError(err);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001016 }
Nick Coghland6009512014-11-20 21:39:37 +10001017}
1018
1019void
1020Py_Initialize(void)
1021{
1022 Py_InitializeEx(1);
1023}
1024
1025
1026#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001027extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001028#endif
1029
1030/* Flush stdout and stderr */
1031
1032static int
1033file_is_closed(PyObject *fobj)
1034{
1035 int r;
1036 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1037 if (tmp == NULL) {
1038 PyErr_Clear();
1039 return 0;
1040 }
1041 r = PyObject_IsTrue(tmp);
1042 Py_DECREF(tmp);
1043 if (r < 0)
1044 PyErr_Clear();
1045 return r > 0;
1046}
1047
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001048static int
Nick Coghland6009512014-11-20 21:39:37 +10001049flush_std_files(void)
1050{
1051 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1052 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1053 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001054 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001055
1056 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001057 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001058 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001059 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001060 status = -1;
1061 }
Nick Coghland6009512014-11-20 21:39:37 +10001062 else
1063 Py_DECREF(tmp);
1064 }
1065
1066 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001067 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001068 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001069 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001070 status = -1;
1071 }
Nick Coghland6009512014-11-20 21:39:37 +10001072 else
1073 Py_DECREF(tmp);
1074 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001075
1076 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001077}
1078
1079/* Undo the effect of Py_Initialize().
1080
1081 Beware: if multiple interpreter and/or thread states exist, these
1082 are not wiped out; only the current thread and interpreter state
1083 are deleted. But since everything else is deleted, those other
1084 interpreter and thread states should no longer be used.
1085
1086 (XXX We should do better, e.g. wipe out all interpreters and
1087 threads.)
1088
1089 Locking: as above.
1090
1091*/
1092
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001093int
1094Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001095{
1096 PyInterpreterState *interp;
1097 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001098 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001099
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001100 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001101 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001102
Eric Snow842a2f02019-03-15 15:47:51 -06001103 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001104 wait_for_thread_shutdown();
1105
Marcel Plch776407f2017-12-20 11:17:58 +01001106 /* Get current thread state and interpreter pointer */
Victor Stinner50b48572018-11-01 01:51:40 +01001107 tstate = _PyThreadState_GET();
Marcel Plch776407f2017-12-20 11:17:58 +01001108 interp = tstate->interp;
1109
Eric Snow842a2f02019-03-15 15:47:51 -06001110 // Make any remaining pending calls.
1111 _Py_FinishPendingCalls();
1112
Nick Coghland6009512014-11-20 21:39:37 +10001113 /* The interpreter is still entirely intact at this point, and the
1114 * exit funcs may be relying on that. In particular, if some thread
1115 * or exit func is still waiting to do an import, the import machinery
1116 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001117 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001118 * Note that Threading.py uses an exit func to do a join on all the
1119 * threads created thru it, so this also protects pending imports in
1120 * the threads created via Threading.
1121 */
Nick Coghland6009512014-11-20 21:39:37 +10001122
Marcel Plch776407f2017-12-20 11:17:58 +01001123 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001124
Victor Stinnerda273412017-12-15 01:46:02 +01001125 /* Copy the core config, PyInterpreterState_Delete() free
1126 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001127#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001128 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001129#endif
1130#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001131 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001132#endif
1133#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001134 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001135#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001136
Nick Coghland6009512014-11-20 21:39:37 +10001137 /* Remaining threads (e.g. daemon threads) will automatically exit
1138 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001139 _PyRuntime.finalizing = tstate;
1140 _PyRuntime.initialized = 0;
1141 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001142
Victor Stinnere0deff32015-03-24 13:46:18 +01001143 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001144 if (flush_std_files() < 0) {
1145 status = -1;
1146 }
Nick Coghland6009512014-11-20 21:39:37 +10001147
1148 /* Disable signal handling */
1149 PyOS_FiniInterrupts();
1150
1151 /* Collect garbage. This may call finalizers; it's nice to call these
1152 * before all modules are destroyed.
1153 * XXX If a __del__ or weakref callback is triggered here, and tries to
1154 * XXX import a module, bad things can happen, because Python no
1155 * XXX longer believes it's initialized.
1156 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1157 * XXX is easy to provoke that way. I've also seen, e.g.,
1158 * XXX Exception exceptions.ImportError: 'No module named sha'
1159 * XXX in <function callback at 0x008F5718> ignored
1160 * XXX but I'm unclear on exactly how that one happens. In any case,
1161 * XXX I haven't seen a real-life report of either of these.
1162 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001163 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001164#ifdef COUNT_ALLOCS
1165 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1166 each collection might release some types from the type
1167 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001168 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001169 /* nothing */;
1170#endif
Eric Snowdae02762017-09-14 00:35:58 -07001171
Nick Coghland6009512014-11-20 21:39:37 +10001172 /* Destroy all modules */
1173 PyImport_Cleanup();
1174
Victor Stinnere0deff32015-03-24 13:46:18 +01001175 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001176 if (flush_std_files() < 0) {
1177 status = -1;
1178 }
Nick Coghland6009512014-11-20 21:39:37 +10001179
1180 /* Collect final garbage. This disposes of cycles created by
1181 * class definitions, for example.
1182 * XXX This is disabled because it caused too many problems. If
1183 * XXX a __del__ or weakref callback triggers here, Python code has
1184 * XXX a hard time running, because even the sys module has been
1185 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1186 * XXX One symptom is a sequence of information-free messages
1187 * XXX coming from threads (if a __del__ or callback is invoked,
1188 * XXX other threads can execute too, and any exception they encounter
1189 * XXX triggers a comedy of errors as subsystem after subsystem
1190 * XXX fails to find what it *expects* to find in sys to help report
1191 * XXX the exception and consequent unexpected failures). I've also
1192 * XXX seen segfaults then, after adding print statements to the
1193 * XXX Python code getting called.
1194 */
1195#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001196 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001197#endif
1198
1199 /* Disable tracemalloc after all Python objects have been destroyed,
1200 so it is possible to use tracemalloc in objects destructor. */
1201 _PyTraceMalloc_Fini();
1202
1203 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1204 _PyImport_Fini();
1205
1206 /* Cleanup typeobject.c's internal caches. */
1207 _PyType_Fini();
1208
1209 /* unload faulthandler module */
1210 _PyFaulthandler_Fini();
1211
1212 /* Debugging stuff */
1213#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001214 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001215#endif
1216 /* dump hash stats */
1217 _PyHash_Fini();
1218
Eric Snowdae02762017-09-14 00:35:58 -07001219#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001220 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001221 _PyDebug_PrintTotalRefs();
1222 }
Eric Snowdae02762017-09-14 00:35:58 -07001223#endif
Nick Coghland6009512014-11-20 21:39:37 +10001224
1225#ifdef Py_TRACE_REFS
1226 /* Display all objects still alive -- this can invoke arbitrary
1227 * __repr__ overrides, so requires a mostly-intact interpreter.
1228 * Alas, a lot of stuff may still be alive now that will be cleaned
1229 * up later.
1230 */
Victor Stinnerda273412017-12-15 01:46:02 +01001231 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001232 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001233 }
Nick Coghland6009512014-11-20 21:39:37 +10001234#endif /* Py_TRACE_REFS */
1235
1236 /* Clear interpreter state and all thread states. */
1237 PyInterpreterState_Clear(interp);
1238
1239 /* Now we decref the exception classes. After this point nothing
1240 can raise an exception. That's okay, because each Fini() method
1241 below has been checked to make sure no exceptions are ever
1242 raised.
1243 */
1244
1245 _PyExc_Fini();
1246
1247 /* Sundry finalizers */
1248 PyMethod_Fini();
1249 PyFrame_Fini();
1250 PyCFunction_Fini();
1251 PyTuple_Fini();
1252 PyList_Fini();
1253 PySet_Fini();
1254 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001255 PyLong_Fini();
1256 PyFloat_Fini();
1257 PyDict_Fini();
1258 PySlice_Fini();
1259 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001260 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001261 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001262 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001263 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001264
1265 /* Cleanup Unicode implementation */
1266 _PyUnicode_Fini();
1267
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001268 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001269
1270 /* XXX Still allocated:
1271 - various static ad-hoc pointers to interned strings
1272 - int and float free list blocks
1273 - whatever various modules and libraries allocate
1274 */
1275
1276 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1277
1278 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001279 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001280
1281 /* Delete current thread. After this, many C API calls become crashy. */
1282 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001283
Nick Coghland6009512014-11-20 21:39:37 +10001284 PyInterpreterState_Delete(interp);
1285
1286#ifdef Py_TRACE_REFS
1287 /* Display addresses (& refcnts) of all objects still alive.
1288 * An address can be used to find the repr of the object, printed
1289 * above by _Py_PrintReferences.
1290 */
Victor Stinnerda273412017-12-15 01:46:02 +01001291 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001292 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001293 }
Nick Coghland6009512014-11-20 21:39:37 +10001294#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001295#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001296 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001297 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001298 }
Nick Coghland6009512014-11-20 21:39:37 +10001299#endif
1300
1301 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001302
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001303 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001304 return status;
1305}
1306
1307void
1308Py_Finalize(void)
1309{
1310 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001311}
1312
1313/* Create and initialize a new interpreter and thread, and return the
1314 new thread. This requires that Py_Initialize() has been called
1315 first.
1316
1317 Unsuccessful initialization yields a NULL pointer. Note that *no*
1318 exception information is available even in this case -- the
1319 exception information is held in the thread, and there is no
1320 thread.
1321
1322 Locking: as above.
1323
1324*/
1325
Victor Stinnera7368ac2017-11-15 18:11:45 -08001326static _PyInitError
1327new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001328{
1329 PyInterpreterState *interp;
1330 PyThreadState *tstate, *save_tstate;
1331 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001332 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001333
Victor Stinnera7368ac2017-11-15 18:11:45 -08001334 if (!_PyRuntime.initialized) {
1335 return _Py_INIT_ERR("Py_Initialize must be called first");
1336 }
Nick Coghland6009512014-11-20 21:39:37 +10001337
Victor Stinner8a1be612016-03-14 22:07:55 +01001338 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1339 interpreters: disable PyGILState_Check(). */
1340 _PyGILState_check_enabled = 0;
1341
Nick Coghland6009512014-11-20 21:39:37 +10001342 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001343 if (interp == NULL) {
1344 *tstate_p = NULL;
1345 return _Py_INIT_OK();
1346 }
Nick Coghland6009512014-11-20 21:39:37 +10001347
1348 tstate = PyThreadState_New(interp);
1349 if (tstate == NULL) {
1350 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001351 *tstate_p = NULL;
1352 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001353 }
1354
1355 save_tstate = PyThreadState_Swap(tstate);
1356
Eric Snow1abcf672017-05-23 21:46:51 -07001357 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001358 _PyCoreConfig *core_config;
1359 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001360 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001361 core_config = &save_tstate->interp->core_config;
1362 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001363 } else {
1364 /* No current thread state, copy from the main interpreter */
1365 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001366 core_config = &main_interp->core_config;
1367 config = &main_interp->config;
1368 }
1369
1370 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1371 return _Py_INIT_ERR("failed to copy core config");
1372 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001373 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001374 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1375 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001376 }
1377
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001378 err = _PyExc_Init();
1379 if (_Py_INIT_FAILED(err)) {
1380 return err;
1381 }
1382
Nick Coghland6009512014-11-20 21:39:37 +10001383 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001384 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001385 if (modules == NULL) {
1386 return _Py_INIT_ERR("can't make modules dictionary");
1387 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001388 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001389
Eric Snowd393c1b2017-09-14 12:18:12 -06001390 sysmod = _PyImport_FindBuiltin("sys", modules);
1391 if (sysmod != NULL) {
1392 interp->sysdict = PyModule_GetDict(sysmod);
1393 if (interp->sysdict == NULL)
1394 goto handle_error;
1395 Py_INCREF(interp->sysdict);
1396 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerab672812019-01-23 15:04:40 +01001397 if (_PySys_InitMain(interp) < 0) {
1398 return _Py_INIT_ERR("can't finish initializing sys");
1399 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001400 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001401 else if (PyErr_Occurred()) {
1402 goto handle_error;
1403 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001404
1405 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001406 if (bimod != NULL) {
1407 interp->builtins = PyModule_GetDict(bimod);
1408 if (interp->builtins == NULL)
1409 goto handle_error;
1410 Py_INCREF(interp->builtins);
1411 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001412 else if (PyErr_Occurred()) {
1413 goto handle_error;
1414 }
Nick Coghland6009512014-11-20 21:39:37 +10001415
Nick Coghland6009512014-11-20 21:39:37 +10001416 if (bimod != NULL && sysmod != NULL) {
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001417 err = _PyBuiltins_AddExceptions(bimod);
1418 if (_Py_INIT_FAILED(err)) {
1419 return err;
1420 }
Nick Coghland6009512014-11-20 21:39:37 +10001421
Victor Stinnerab672812019-01-23 15:04:40 +01001422 err = _PySys_SetPreliminaryStderr(interp->sysdict);
1423 if (_Py_INIT_FAILED(err)) {
1424 return err;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001425 }
Nick Coghland6009512014-11-20 21:39:37 +10001426
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001427 err = _PyImportHooks_Init();
1428 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001429 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001430 }
Nick Coghland6009512014-11-20 21:39:37 +10001431
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001432 err = initimport(interp, sysmod);
1433 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001434 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001435 }
Nick Coghland6009512014-11-20 21:39:37 +10001436
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001437 err = initexternalimport(interp);
1438 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001439 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440 }
Nick Coghland6009512014-11-20 21:39:37 +10001441
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442 err = initfsencoding(interp);
1443 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001444 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001445 }
1446
Victor Stinner91106cd2017-12-13 12:29:09 +01001447 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001448 if (_Py_INIT_FAILED(err)) {
1449 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001450 }
1451
1452 err = add_main_module(interp);
1453 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001454 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001455 }
1456
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001457 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001458 err = initsite();
1459 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001460 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461 }
1462 }
Nick Coghland6009512014-11-20 21:39:37 +10001463 }
1464
Victor Stinnera7368ac2017-11-15 18:11:45 -08001465 if (PyErr_Occurred()) {
1466 goto handle_error;
1467 }
Nick Coghland6009512014-11-20 21:39:37 +10001468
Victor Stinnera7368ac2017-11-15 18:11:45 -08001469 *tstate_p = tstate;
1470 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001471
Nick Coghland6009512014-11-20 21:39:37 +10001472handle_error:
1473 /* Oops, it didn't work. Undo it all. */
1474
1475 PyErr_PrintEx(0);
1476 PyThreadState_Clear(tstate);
1477 PyThreadState_Swap(save_tstate);
1478 PyThreadState_Delete(tstate);
1479 PyInterpreterState_Delete(interp);
1480
Victor Stinnera7368ac2017-11-15 18:11:45 -08001481 *tstate_p = NULL;
1482 return _Py_INIT_OK();
1483}
1484
1485PyThreadState *
1486Py_NewInterpreter(void)
1487{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001488 PyThreadState *tstate = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001489 _PyInitError err = new_interpreter(&tstate);
1490 if (_Py_INIT_FAILED(err)) {
Victor Stinnerdfe88472019-03-01 12:14:41 +01001491 _Py_ExitInitError(err);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001492 }
1493 return tstate;
1494
Nick Coghland6009512014-11-20 21:39:37 +10001495}
1496
1497/* Delete an interpreter and its last thread. This requires that the
1498 given thread state is current, that the thread has no remaining
1499 frames, and that it is its interpreter's only remaining thread.
1500 It is a fatal error to violate these constraints.
1501
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001502 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001503 everything, regardless.)
1504
1505 Locking: as above.
1506
1507*/
1508
1509void
1510Py_EndInterpreter(PyThreadState *tstate)
1511{
1512 PyInterpreterState *interp = tstate->interp;
1513
Victor Stinner50b48572018-11-01 01:51:40 +01001514 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001515 Py_FatalError("Py_EndInterpreter: thread is not current");
1516 if (tstate->frame != NULL)
1517 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001518 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001519
Eric Snow842a2f02019-03-15 15:47:51 -06001520 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001521 wait_for_thread_shutdown();
1522
Marcel Plch776407f2017-12-20 11:17:58 +01001523 call_py_exitfuncs(interp);
1524
Nick Coghland6009512014-11-20 21:39:37 +10001525 if (tstate != interp->tstate_head || tstate->next != NULL)
1526 Py_FatalError("Py_EndInterpreter: not the last thread");
1527
1528 PyImport_Cleanup();
1529 PyInterpreterState_Clear(interp);
1530 PyThreadState_Swap(NULL);
1531 PyInterpreterState_Delete(interp);
1532}
1533
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001535
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001536static _PyInitError
1537add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001538{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001539 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001540 m = PyImport_AddModule("__main__");
1541 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542 return _Py_INIT_ERR("can't create __main__ module");
1543
Nick Coghland6009512014-11-20 21:39:37 +10001544 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001545 ann_dict = PyDict_New();
1546 if ((ann_dict == NULL) ||
1547 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001548 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001549 }
1550 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001551
Nick Coghland6009512014-11-20 21:39:37 +10001552 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1553 PyObject *bimod = PyImport_ImportModule("builtins");
1554 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001555 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001556 }
1557 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001559 }
1560 Py_DECREF(bimod);
1561 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001562
Nick Coghland6009512014-11-20 21:39:37 +10001563 /* Main is a little special - imp.is_builtin("__main__") will return
1564 * False, but BuiltinImporter is still the most appropriate initial
1565 * setting for its __loader__ attribute. A more suitable value will
1566 * be set if __main__ gets further initialized later in the startup
1567 * process.
1568 */
1569 loader = PyDict_GetItemString(d, "__loader__");
1570 if (loader == NULL || loader == Py_None) {
1571 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1572 "BuiltinImporter");
1573 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001575 }
1576 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001577 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001578 }
1579 Py_DECREF(loader);
1580 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001581 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001582}
1583
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001584static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001585initfsencoding(PyInterpreterState *interp)
1586{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001587 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001588
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001589 char *encoding = get_codec_name(config->filesystem_encoding);
1590 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001591 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001592 memory, import a module of the standard library failed, etc. */
1593 return _Py_INIT_ERR("failed to get the Python codec "
1594 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001595 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001596
1597 /* Update the filesystem encoding to the normalized Python codec name.
1598 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1599 (Python codec name). */
1600 PyMem_RawFree(config->filesystem_encoding);
1601 config->filesystem_encoding = encoding;
1602
1603 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1604 global configuration variables. */
1605 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1606 config->filesystem_errors) < 0) {
1607 return _Py_INIT_NO_MEMORY();
1608 }
1609
1610 /* PyUnicode can now use the Python codec rather than C implementation
1611 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001612 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001614}
1615
1616/* Import the site module (not into __main__ though) */
1617
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001618static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001619initsite(void)
1620{
1621 PyObject *m;
1622 m = PyImport_ImportModule("site");
1623 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001624 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001625 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626 Py_DECREF(m);
1627 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001628}
1629
Victor Stinner874dbe82015-09-04 17:29:57 +02001630/* Check if a file descriptor is valid or not.
1631 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1632static int
1633is_valid_fd(int fd)
1634{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001635#ifdef __APPLE__
1636 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1637 and the other side of the pipe is closed, dup(1) succeed, whereas
1638 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1639 such error. */
1640 struct stat st;
1641 return (fstat(fd, &st) == 0);
1642#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001643 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001644 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001645 return 0;
1646 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001647 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1648 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1649 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001650 fd2 = dup(fd);
1651 if (fd2 >= 0)
1652 close(fd2);
1653 _Py_END_SUPPRESS_IPH
1654 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001655#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001656}
1657
1658/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001659static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001660create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001661 int fd, int write_mode, const char* name,
1662 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001663{
1664 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1665 const char* mode;
1666 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001667 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001668 int buffering, isatty;
1669 _Py_IDENTIFIER(open);
1670 _Py_IDENTIFIER(isatty);
1671 _Py_IDENTIFIER(TextIOWrapper);
1672 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001673 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001674
Victor Stinner874dbe82015-09-04 17:29:57 +02001675 if (!is_valid_fd(fd))
1676 Py_RETURN_NONE;
1677
Nick Coghland6009512014-11-20 21:39:37 +10001678 /* stdin is always opened in buffered mode, first because it shouldn't
1679 make a difference in common use cases, second because TextIOWrapper
1680 depends on the presence of a read1() method which only exists on
1681 buffered streams.
1682 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001683 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001684 buffering = 0;
1685 else
1686 buffering = -1;
1687 if (write_mode)
1688 mode = "wb";
1689 else
1690 mode = "rb";
1691 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1692 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001693 Py_None, Py_None, /* encoding, errors */
1694 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001695 if (buf == NULL)
1696 goto error;
1697
1698 if (buffering) {
1699 _Py_IDENTIFIER(raw);
1700 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1701 if (raw == NULL)
1702 goto error;
1703 }
1704 else {
1705 raw = buf;
1706 Py_INCREF(raw);
1707 }
1708
Steve Dower39294992016-08-30 21:22:36 -07001709#ifdef MS_WINDOWS
1710 /* Windows console IO is always UTF-8 encoded */
1711 if (PyWindowsConsoleIO_Check(raw))
1712 encoding = "utf-8";
1713#endif
1714
Nick Coghland6009512014-11-20 21:39:37 +10001715 text = PyUnicode_FromString(name);
1716 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1717 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001718 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001719 if (res == NULL)
1720 goto error;
1721 isatty = PyObject_IsTrue(res);
1722 Py_DECREF(res);
1723 if (isatty == -1)
1724 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001725 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001726 write_through = Py_True;
1727 else
1728 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001729 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001730 line_buffering = Py_True;
1731 else
1732 line_buffering = Py_False;
1733
1734 Py_CLEAR(raw);
1735 Py_CLEAR(text);
1736
1737#ifdef MS_WINDOWS
1738 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1739 newlines to "\n".
1740 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1741 newline = NULL;
1742#else
1743 /* sys.stdin: split lines at "\n".
1744 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1745 newline = "\n";
1746#endif
1747
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001748 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001749 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001750 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001751 Py_CLEAR(buf);
1752 if (stream == NULL)
1753 goto error;
1754
1755 if (write_mode)
1756 mode = "w";
1757 else
1758 mode = "r";
1759 text = PyUnicode_FromString(mode);
1760 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1761 goto error;
1762 Py_CLEAR(text);
1763 return stream;
1764
1765error:
1766 Py_XDECREF(buf);
1767 Py_XDECREF(stream);
1768 Py_XDECREF(text);
1769 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001770
Victor Stinner874dbe82015-09-04 17:29:57 +02001771 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1772 /* Issue #24891: the file descriptor was closed after the first
1773 is_valid_fd() check was called. Ignore the OSError and set the
1774 stream to None. */
1775 PyErr_Clear();
1776 Py_RETURN_NONE;
1777 }
1778 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001779}
1780
1781/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001782static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001783init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001784{
1785 PyObject *iomod = NULL, *wrapper;
1786 PyObject *bimod = NULL;
1787 PyObject *m;
1788 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001789 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001790 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001791 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001792 _PyCoreConfig *config = &interp->core_config;
1793
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001794 /* Check that stdin is not a directory
1795 Using shell redirection, you can redirect stdin to a directory,
1796 crashing the Python interpreter. Catch this common mistake here
1797 and output a useful error message. Note that under MS Windows,
1798 the shell already prevents that. */
1799#ifndef MS_WINDOWS
1800 struct _Py_stat_struct sb;
1801 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1802 S_ISDIR(sb.st_mode)) {
1803 return _Py_INIT_USER_ERR("<stdin> is a directory, "
1804 "cannot continue");
1805 }
1806#endif
1807
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001808 char *codec_name = get_codec_name(config->stdio_encoding);
1809 if (codec_name == NULL) {
1810 return _Py_INIT_ERR("failed to get the Python codec name "
1811 "of the stdio encoding");
1812 }
1813 PyMem_RawFree(config->stdio_encoding);
1814 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001815
1816 /* Hack to avoid a nasty recursion issue when Python is invoked
1817 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1818 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1819 goto error;
1820 }
1821 Py_DECREF(m);
1822
1823 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1824 goto error;
1825 }
1826 Py_DECREF(m);
1827
1828 if (!(bimod = PyImport_ImportModule("builtins"))) {
1829 goto error;
1830 }
1831
1832 if (!(iomod = PyImport_ImportModule("io"))) {
1833 goto error;
1834 }
1835 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1836 goto error;
1837 }
1838
1839 /* Set builtins.open */
1840 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1841 Py_DECREF(wrapper);
1842 goto error;
1843 }
1844 Py_DECREF(wrapper);
1845
Nick Coghland6009512014-11-20 21:39:37 +10001846 /* Set sys.stdin */
1847 fd = fileno(stdin);
1848 /* Under some conditions stdin, stdout and stderr may not be connected
1849 * and fileno() may point to an invalid file descriptor. For example
1850 * GUI apps don't have valid standard streams by default.
1851 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001852 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001853 config->stdio_encoding,
1854 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001855 if (std == NULL)
1856 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001857 PySys_SetObject("__stdin__", std);
1858 _PySys_SetObjectId(&PyId_stdin, std);
1859 Py_DECREF(std);
1860
1861 /* Set sys.stdout */
1862 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001863 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001864 config->stdio_encoding,
1865 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001866 if (std == NULL)
1867 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001868 PySys_SetObject("__stdout__", std);
1869 _PySys_SetObjectId(&PyId_stdout, std);
1870 Py_DECREF(std);
1871
1872#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1873 /* Set sys.stderr, replaces the preliminary stderr */
1874 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001875 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001876 config->stdio_encoding,
1877 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001878 if (std == NULL)
1879 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001880
1881 /* Same as hack above, pre-import stderr's codec to avoid recursion
1882 when import.c tries to write to stderr in verbose mode. */
1883 encoding_attr = PyObject_GetAttrString(std, "encoding");
1884 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001885 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001886 if (std_encoding != NULL) {
1887 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1888 Py_XDECREF(codec_info);
1889 }
1890 Py_DECREF(encoding_attr);
1891 }
1892 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1893
1894 if (PySys_SetObject("__stderr__", std) < 0) {
1895 Py_DECREF(std);
1896 goto error;
1897 }
1898 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1899 Py_DECREF(std);
1900 goto error;
1901 }
1902 Py_DECREF(std);
1903#endif
1904
Victor Stinnera7368ac2017-11-15 18:11:45 -08001905 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001906
Victor Stinnera7368ac2017-11-15 18:11:45 -08001907error:
1908 res = _Py_INIT_ERR("can't initialize sys standard streams");
1909
1910done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001911 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001912
Nick Coghland6009512014-11-20 21:39:37 +10001913 Py_XDECREF(bimod);
1914 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001915 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001916}
1917
1918
Victor Stinner10dc4842015-03-24 12:01:30 +01001919static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001920_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001921{
Victor Stinner10dc4842015-03-24 12:01:30 +01001922 fputc('\n', stderr);
1923 fflush(stderr);
1924
1925 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001926 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001927}
Victor Stinner791da1c2016-03-14 16:53:12 +01001928
1929/* Print the current exception (if an exception is set) with its traceback,
1930 or display the current Python stack.
1931
1932 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1933 called on catastrophic cases.
1934
1935 Return 1 if the traceback was displayed, 0 otherwise. */
1936
1937static int
1938_Py_FatalError_PrintExc(int fd)
1939{
1940 PyObject *ferr, *res;
1941 PyObject *exception, *v, *tb;
1942 int has_tb;
1943
Victor Stinner791da1c2016-03-14 16:53:12 +01001944 PyErr_Fetch(&exception, &v, &tb);
1945 if (exception == NULL) {
1946 /* No current exception */
1947 return 0;
1948 }
1949
1950 ferr = _PySys_GetObjectId(&PyId_stderr);
1951 if (ferr == NULL || ferr == Py_None) {
1952 /* sys.stderr is not set yet or set to None,
1953 no need to try to display the exception */
1954 return 0;
1955 }
1956
1957 PyErr_NormalizeException(&exception, &v, &tb);
1958 if (tb == NULL) {
1959 tb = Py_None;
1960 Py_INCREF(tb);
1961 }
1962 PyException_SetTraceback(v, tb);
1963 if (exception == NULL) {
1964 /* PyErr_NormalizeException() failed */
1965 return 0;
1966 }
1967
1968 has_tb = (tb != Py_None);
1969 PyErr_Display(exception, v, tb);
1970 Py_XDECREF(exception);
1971 Py_XDECREF(v);
1972 Py_XDECREF(tb);
1973
1974 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001975 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001976 if (res == NULL)
1977 PyErr_Clear();
1978 else
1979 Py_DECREF(res);
1980
1981 return has_tb;
1982}
1983
Nick Coghland6009512014-11-20 21:39:37 +10001984/* Print fatal error message and abort */
1985
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001986#ifdef MS_WINDOWS
1987static void
1988fatal_output_debug(const char *msg)
1989{
1990 /* buffer of 256 bytes allocated on the stack */
1991 WCHAR buffer[256 / sizeof(WCHAR)];
1992 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1993 size_t msglen;
1994
1995 OutputDebugStringW(L"Fatal Python error: ");
1996
1997 msglen = strlen(msg);
1998 while (msglen) {
1999 size_t i;
2000
2001 if (buflen > msglen) {
2002 buflen = msglen;
2003 }
2004
2005 /* Convert the message to wchar_t. This uses a simple one-to-one
2006 conversion, assuming that the this error message actually uses
2007 ASCII only. If this ceases to be true, we will have to convert. */
2008 for (i=0; i < buflen; ++i) {
2009 buffer[i] = msg[i];
2010 }
2011 buffer[i] = L'\0';
2012 OutputDebugStringW(buffer);
2013
2014 msg += buflen;
2015 msglen -= buflen;
2016 }
2017 OutputDebugStringW(L"\n");
2018}
2019#endif
2020
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002021static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002022fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002023{
2024 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002025 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002026
2027 if (reentrant) {
2028 /* Py_FatalError() caused a second fatal error.
2029 Example: flush_std_files() raises a recursion error. */
2030 goto exit;
2031 }
2032 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002033
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002034 fprintf(stderr, "Fatal Python error: ");
2035 if (prefix) {
2036 fputs(prefix, stderr);
2037 fputs(": ", stderr);
2038 }
2039 if (msg) {
2040 fputs(msg, stderr);
2041 }
2042 else {
2043 fprintf(stderr, "<message not set>");
2044 }
2045 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002046 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002047
Victor Stinner3a228ab2018-11-01 00:26:41 +01002048 /* Check if the current thread has a Python thread state
2049 and holds the GIL */
2050 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2051 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002052 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002053 if (tss_tstate != tstate) {
2054 /* The Python thread does not hold the GIL */
2055 tss_tstate = NULL;
2056 }
2057 }
2058 else {
2059 /* Py_FatalError() has been called from a C thread
2060 which has no Python thread state. */
2061 }
2062 int has_tstate_and_gil = (tss_tstate != NULL);
2063
2064 if (has_tstate_and_gil) {
2065 /* If an exception is set, print the exception with its traceback */
2066 if (!_Py_FatalError_PrintExc(fd)) {
2067 /* No exception is set, or an exception is set without traceback */
2068 _Py_FatalError_DumpTracebacks(fd);
2069 }
2070 }
2071 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002072 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002073 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002074
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002075 /* The main purpose of faulthandler is to display the traceback.
2076 This function already did its best to display a traceback.
2077 Disable faulthandler to prevent writing a second traceback
2078 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002079 _PyFaulthandler_Fini();
2080
Victor Stinner791da1c2016-03-14 16:53:12 +01002081 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002082 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002083 /* Flush sys.stdout and sys.stderr */
2084 flush_std_files();
2085 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002086
Nick Coghland6009512014-11-20 21:39:37 +10002087#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002088 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002089#endif /* MS_WINDOWS */
2090
2091exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002092 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002093#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002094 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002095#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002096 abort();
2097 }
2098 else {
2099 exit(status);
2100 }
2101}
2102
Victor Stinner19760862017-12-20 01:41:59 +01002103void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002104Py_FatalError(const char *msg)
2105{
2106 fatal_error(NULL, msg, -1);
2107}
2108
Victor Stinner19760862017-12-20 01:41:59 +01002109void _Py_NO_RETURN
Victor Stinnerdfe88472019-03-01 12:14:41 +01002110_Py_ExitInitError(_PyInitError err)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002111{
Victor Stinnerdfe88472019-03-01 12:14:41 +01002112 if (err.exitcode >= 0) {
2113 exit(err.exitcode);
2114 }
2115 else {
2116 /* On "user" error: exit with status 1.
2117 For all other errors, call abort(). */
2118 int status = err.user_err ? 1 : -1;
2119 fatal_error(err.prefix, err.msg, status);
2120 }
Nick Coghland6009512014-11-20 21:39:37 +10002121}
2122
2123/* Clean up and exit */
2124
Victor Stinnerd7292b52016-06-17 12:29:00 +02002125# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002126
Nick Coghland6009512014-11-20 21:39:37 +10002127/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002128void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002129{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002130 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002131
Antoine Pitroufc5db952017-12-13 02:29:07 +01002132 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002133 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2134
2135 is->pyexitfunc = func;
2136 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002137}
2138
2139static void
Marcel Plch776407f2017-12-20 11:17:58 +01002140call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002141{
Marcel Plch776407f2017-12-20 11:17:58 +01002142 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002143 return;
2144
Marcel Plch776407f2017-12-20 11:17:58 +01002145 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002146 PyErr_Clear();
2147}
2148
2149/* Wait until threading._shutdown completes, provided
2150 the threading module was imported in the first place.
2151 The shutdown routine will wait until all non-daemon
2152 "threading" threads have completed. */
2153static void
2154wait_for_thread_shutdown(void)
2155{
Nick Coghland6009512014-11-20 21:39:37 +10002156 _Py_IDENTIFIER(_shutdown);
2157 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002158 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002159 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002160 if (PyErr_Occurred()) {
2161 PyErr_WriteUnraisable(NULL);
2162 }
2163 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002164 return;
2165 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002166 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002167 if (result == NULL) {
2168 PyErr_WriteUnraisable(threading);
2169 }
2170 else {
2171 Py_DECREF(result);
2172 }
2173 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002174}
2175
2176#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002177int Py_AtExit(void (*func)(void))
2178{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002179 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002180 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002181 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002182 return 0;
2183}
2184
2185static void
2186call_ll_exitfuncs(void)
2187{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002188 while (_PyRuntime.nexitfuncs > 0)
2189 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002190
2191 fflush(stdout);
2192 fflush(stderr);
2193}
2194
Victor Stinnercfc88312018-08-01 16:41:25 +02002195void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002196Py_Exit(int sts)
2197{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002198 if (Py_FinalizeEx() < 0) {
2199 sts = 120;
2200 }
Nick Coghland6009512014-11-20 21:39:37 +10002201
2202 exit(sts);
2203}
2204
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002205static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002206initsigs(void)
2207{
2208#ifdef SIGPIPE
2209 PyOS_setsig(SIGPIPE, SIG_IGN);
2210#endif
2211#ifdef SIGXFZ
2212 PyOS_setsig(SIGXFZ, SIG_IGN);
2213#endif
2214#ifdef SIGXFSZ
2215 PyOS_setsig(SIGXFSZ, SIG_IGN);
2216#endif
2217 PyOS_InitInterrupts(); /* May imply initsignal() */
2218 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002219 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002220 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002221 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002222}
2223
2224
2225/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2226 *
2227 * All of the code in this function must only use async-signal-safe functions,
2228 * listed at `man 7 signal` or
2229 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2230 */
2231void
2232_Py_RestoreSignals(void)
2233{
2234#ifdef SIGPIPE
2235 PyOS_setsig(SIGPIPE, SIG_DFL);
2236#endif
2237#ifdef SIGXFZ
2238 PyOS_setsig(SIGXFZ, SIG_DFL);
2239#endif
2240#ifdef SIGXFSZ
2241 PyOS_setsig(SIGXFSZ, SIG_DFL);
2242#endif
2243}
2244
2245
2246/*
2247 * The file descriptor fd is considered ``interactive'' if either
2248 * a) isatty(fd) is TRUE, or
2249 * b) the -i flag was given, and the filename associated with
2250 * the descriptor is NULL or "<stdin>" or "???".
2251 */
2252int
2253Py_FdIsInteractive(FILE *fp, const char *filename)
2254{
2255 if (isatty((int)fileno(fp)))
2256 return 1;
2257 if (!Py_InteractiveFlag)
2258 return 0;
2259 return (filename == NULL) ||
2260 (strcmp(filename, "<stdin>") == 0) ||
2261 (strcmp(filename, "???") == 0);
2262}
2263
2264
Nick Coghland6009512014-11-20 21:39:37 +10002265/* Wrappers around sigaction() or signal(). */
2266
2267PyOS_sighandler_t
2268PyOS_getsig(int sig)
2269{
2270#ifdef HAVE_SIGACTION
2271 struct sigaction context;
2272 if (sigaction(sig, NULL, &context) == -1)
2273 return SIG_ERR;
2274 return context.sa_handler;
2275#else
2276 PyOS_sighandler_t handler;
2277/* Special signal handling for the secure CRT in Visual Studio 2005 */
2278#if defined(_MSC_VER) && _MSC_VER >= 1400
2279 switch (sig) {
2280 /* Only these signals are valid */
2281 case SIGINT:
2282 case SIGILL:
2283 case SIGFPE:
2284 case SIGSEGV:
2285 case SIGTERM:
2286 case SIGBREAK:
2287 case SIGABRT:
2288 break;
2289 /* Don't call signal() with other values or it will assert */
2290 default:
2291 return SIG_ERR;
2292 }
2293#endif /* _MSC_VER && _MSC_VER >= 1400 */
2294 handler = signal(sig, SIG_IGN);
2295 if (handler != SIG_ERR)
2296 signal(sig, handler);
2297 return handler;
2298#endif
2299}
2300
2301/*
2302 * All of the code in this function must only use async-signal-safe functions,
2303 * listed at `man 7 signal` or
2304 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2305 */
2306PyOS_sighandler_t
2307PyOS_setsig(int sig, PyOS_sighandler_t handler)
2308{
2309#ifdef HAVE_SIGACTION
2310 /* Some code in Modules/signalmodule.c depends on sigaction() being
2311 * used here if HAVE_SIGACTION is defined. Fix that if this code
2312 * changes to invalidate that assumption.
2313 */
2314 struct sigaction context, ocontext;
2315 context.sa_handler = handler;
2316 sigemptyset(&context.sa_mask);
2317 context.sa_flags = 0;
2318 if (sigaction(sig, &context, &ocontext) == -1)
2319 return SIG_ERR;
2320 return ocontext.sa_handler;
2321#else
2322 PyOS_sighandler_t oldhandler;
2323 oldhandler = signal(sig, handler);
2324#ifdef HAVE_SIGINTERRUPT
2325 siginterrupt(sig, 1);
2326#endif
2327 return oldhandler;
2328#endif
2329}
2330
2331#ifdef __cplusplus
2332}
2333#endif