blob: 4a97295102f793452ac91013c7a51a20d2004229 [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 Stinner09532fe2019-05-10 23:39:09 +02007#include "pycore_ceval.h"
Victor Stinner99fcc612019-04-29 13:04:07 +02008#include "pycore_context.h"
Victor Stinner0a28f8d2019-06-19 02:54:39 +02009#include "pycore_import.h" /* _PyImport_FindBuiltin */
Victor Stinner331a6a52019-05-27 16:39:22 +020010#include "pycore_initconfig.h"
Victor Stinner353933e2018-11-23 13:08:26 +010011#include "pycore_fileutils.h"
Victor Stinner27e2d1f2018-11-01 00:52:28 +010012#include "pycore_hamt.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010013#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010014#include "pycore_pylifecycle.h"
15#include "pycore_pymem.h"
16#include "pycore_pystate.h"
Victor Stinnered488662019-05-20 00:14:57 +020017#include "pycore_traceback.h"
Nick Coghland6009512014-11-20 21:39:37 +100018#include "grammar.h"
19#include "node.h"
20#include "token.h"
21#include "parsetok.h"
22#include "errcode.h"
23#include "code.h"
24#include "symtable.h"
25#include "ast.h"
26#include "marshal.h"
27#include "osdefs.h"
28#include <locale.h>
29
30#ifdef HAVE_SIGNAL_H
31#include <signal.h>
32#endif
33
34#ifdef MS_WINDOWS
35#include "malloc.h" /* for alloca */
36#endif
37
38#ifdef HAVE_LANGINFO_H
39#include <langinfo.h>
40#endif
41
42#ifdef MS_WINDOWS
43#undef BYTE
44#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070045
46extern PyTypeObject PyWindowsConsoleIO_Type;
47#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100048#endif
49
50_Py_IDENTIFIER(flush);
51_Py_IDENTIFIER(name);
52_Py_IDENTIFIER(stdin);
53_Py_IDENTIFIER(stdout);
54_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060055_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100056
57#ifdef __cplusplus
58extern "C" {
59#endif
60
Nick Coghland6009512014-11-20 21:39:37 +100061extern grammar _PyParser_Grammar; /* From graminit.c */
62
63/* Forward */
Victor Stinner331a6a52019-05-27 16:39:22 +020064static PyStatus add_main_module(PyInterpreterState *interp);
65static PyStatus init_import_size(void);
66static PyStatus init_sys_streams(PyInterpreterState *interp);
67static PyStatus init_signals(void);
Marcel Plch776407f2017-12-20 11:17:58 +010068static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100069static void wait_for_thread_shutdown(void);
Victor Stinner8e91c242019-04-24 17:24:01 +020070static void call_ll_exitfuncs(_PyRuntimeState *runtime);
Nick Coghland6009512014-11-20 21:39:37 +100071
Gregory P. Smith38f11cc2019-02-16 12:57:40 -080072int _Py_UnhandledKeyboardInterrupt = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080073_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010074static int runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075
Victor Stinner331a6a52019-05-27 16:39:22 +020076PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077_PyRuntime_Initialize(void)
78{
79 /* XXX We only initialize once in the process, which aligns with
80 the static initialization of the former globals now found in
81 _PyRuntime. However, _PyRuntime *should* be initialized with
82 every Py_Initialize() call, but doing so breaks the runtime.
83 This is because the runtime state is not properly finalized
84 currently. */
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010085 if (runtime_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +020086 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087 }
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010088 runtime_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089
90 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060091}
92
93void
94_PyRuntime_Finalize(void)
95{
96 _PyRuntimeState_Fini(&_PyRuntime);
Victor Stinnerfd23cfa2019-03-20 00:03:01 +010097 runtime_initialized = 0;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060098}
99
100int
101_Py_IsFinalizing(void)
102{
103 return _PyRuntime.finalizing != NULL;
104}
105
Nick Coghland6009512014-11-20 21:39:37 +1000106/* Hack to force loading of object files */
107int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
108 PyOS_mystrnicmp; /* Python/pystrcmp.o */
109
110/* PyModule_GetWarningsModule is no longer necessary as of 2.6
111since _warnings is builtin. This API should not be used. */
112PyObject *
113PyModule_GetWarningsModule(void)
114{
115 return PyImport_ImportModule("warnings");
116}
117
Eric Snowc7ec9982017-05-23 23:00:52 -0700118
Eric Snow1abcf672017-05-23 21:46:51 -0700119/* APIs to access the initialization flags
120 *
121 * Can be called prior to Py_Initialize.
122 */
Nick Coghland6009512014-11-20 21:39:37 +1000123
Eric Snow1abcf672017-05-23 21:46:51 -0700124int
125_Py_IsCoreInitialized(void)
126{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600127 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700128}
Nick Coghland6009512014-11-20 21:39:37 +1000129
130int
131Py_IsInitialized(void)
132{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600133 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000134}
135
Nick Coghlan6ea41862017-06-11 13:16:15 +1000136
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000137/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
138 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000139 initializations fail, a fatal error is issued and the function does
140 not return. On return, the first thread and interpreter state have
141 been created.
142
143 Locking: you must hold the interpreter lock while calling this.
144 (If the lock has not yet been initialized, that's equivalent to
145 having the lock, but you cannot use multiple threads.)
146
147*/
148
Victor Stinner331a6a52019-05-27 16:39:22 +0200149static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -0400150init_importlib(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000151{
152 PyObject *importlib;
153 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000154 PyObject *value;
Victor Stinner331a6a52019-05-27 16:39:22 +0200155 int verbose = interp->config.verbose;
Nick Coghland6009512014-11-20 21:39:37 +1000156
157 /* Import _importlib through its frozen version, _frozen_importlib. */
158 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200159 return _PyStatus_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000160 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200161 else if (verbose) {
Nick Coghland6009512014-11-20 21:39:37 +1000162 PySys_FormatStderr("import _frozen_importlib # frozen\n");
163 }
164 importlib = PyImport_AddModule("_frozen_importlib");
165 if (importlib == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200166 return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000167 }
168 interp->importlib = importlib;
169 Py_INCREF(interp->importlib);
170
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300171 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
172 if (interp->import_func == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200173 return _PyStatus_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300174 Py_INCREF(interp->import_func);
175
Victor Stinnercd6e6942015-09-18 09:11:57 +0200176 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800177 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000178 if (impmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200179 return _PyStatus_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000180 }
Victor Stinnerc96be812019-05-14 17:34:56 +0200181 else if (verbose) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200182 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000183 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600184 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200185 return _PyStatus_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000186 }
187
Victor Stinnercd6e6942015-09-18 09:11:57 +0200188 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000189 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
190 if (value == NULL) {
191 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200192 return _PyStatus_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000193 }
194 Py_DECREF(value);
195 Py_DECREF(impmod);
196
Victor Stinner331a6a52019-05-27 16:39:22 +0200197 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000198}
199
Victor Stinner331a6a52019-05-27 16:39:22 +0200200static PyStatus
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200201init_importlib_external(PyThreadState *tstate)
Eric Snow1abcf672017-05-23 21:46:51 -0700202{
203 PyObject *value;
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200204 value = PyObject_CallMethod(tstate->interp->importlib,
Eric Snow1abcf672017-05-23 21:46:51 -0700205 "_install_external_importers", "");
206 if (value == NULL) {
207 PyErr_Print();
Victor Stinner331a6a52019-05-27 16:39:22 +0200208 return _PyStatus_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700209 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200210 Py_DECREF(value);
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200211 return _PyImportZip_Init(tstate);
Eric Snow1abcf672017-05-23 21:46:51 -0700212}
Nick Coghland6009512014-11-20 21:39:37 +1000213
Nick Coghlan6ea41862017-06-11 13:16:15 +1000214/* Helper functions to better handle the legacy C locale
215 *
216 * The legacy C locale assumes ASCII as the default text encoding, which
217 * causes problems not only for the CPython runtime, but also other
218 * components like GNU readline.
219 *
220 * Accordingly, when the CLI detects it, it attempts to coerce it to a
221 * more capable UTF-8 based alternative as follows:
222 *
223 * if (_Py_LegacyLocaleDetected()) {
224 * _Py_CoerceLegacyLocale();
225 * }
226 *
227 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
228 *
229 * Locale coercion also impacts the default error handler for the standard
230 * streams: while the usual default is "strict", the default for the legacy
231 * C locale and for any of the coercion target locales is "surrogateescape".
232 */
233
234int
Victor Stinner0f721472019-05-20 17:16:38 +0200235_Py_LegacyLocaleDetected(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000236{
237#ifndef MS_WINDOWS
Victor Stinner0f721472019-05-20 17:16:38 +0200238 if (!warn) {
239 const char *locale_override = getenv("LC_ALL");
240 if (locale_override != NULL && *locale_override != '\0') {
241 /* Don't coerce C locale if the LC_ALL environment variable
242 is set */
243 return 0;
244 }
245 }
246
Nick Coghlan6ea41862017-06-11 13:16:15 +1000247 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000248 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
249 * the POSIX locale as a simple alias for the C locale, so
250 * we may also want to check for that explicitly.
251 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000252 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
253 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
254#else
255 /* Windows uses code pages instead of locales, so no locale is legacy */
256 return 0;
257#endif
258}
259
Nick Coghlaneb817952017-06-18 12:29:42 +1000260static const char *_C_LOCALE_WARNING =
261 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
262 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
263 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
264 "locales is recommended.\n";
265
Nick Coghlaneb817952017-06-18 12:29:42 +1000266static void
Victor Stinner43125222019-04-24 18:23:53 +0200267emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
Nick Coghlaneb817952017-06-18 12:29:42 +1000268{
Victor Stinner331a6a52019-05-27 16:39:22 +0200269 const PyPreConfig *preconfig = &runtime->preconfig;
Victor Stinner0f721472019-05-20 17:16:38 +0200270 if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
Victor Stinnercf215042018-08-29 22:56:06 +0200271 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000272 }
273}
274
Nick Coghlan6ea41862017-06-11 13:16:15 +1000275typedef struct _CandidateLocale {
276 const char *locale_name; /* The locale to try as a coercion target */
277} _LocaleCoercionTarget;
278
279static _LocaleCoercionTarget _TARGET_LOCALES[] = {
280 {"C.UTF-8"},
281 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000282 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000283 {NULL}
284};
285
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200286
287int
288_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000289{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200290 const _LocaleCoercionTarget *target = NULL;
291 for (target = _TARGET_LOCALES; target->locale_name; target++) {
292 if (strcmp(ctype_loc, target->locale_name) == 0) {
293 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000294 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200295 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200296 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000297}
298
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200299
Nick Coghlan6ea41862017-06-11 13:16:15 +1000300#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100301static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000302 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
303 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
304
Victor Stinner0f721472019-05-20 17:16:38 +0200305static int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200306_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000307{
308 const char *newloc = target->locale_name;
309
310 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100311 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312
313 /* Set the relevant locale environment variable */
314 if (setenv("LC_CTYPE", newloc, 1)) {
315 fprintf(stderr,
316 "Error setting LC_CTYPE, skipping C locale coercion\n");
Victor Stinner0f721472019-05-20 17:16:38 +0200317 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200319 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100320 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000321 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000322
323 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100324 _Py_SetLocaleFromEnv(LC_ALL);
Victor Stinner0f721472019-05-20 17:16:38 +0200325 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326}
327#endif
328
Victor Stinner0f721472019-05-20 17:16:38 +0200329int
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200330_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000331{
Victor Stinner0f721472019-05-20 17:16:38 +0200332 int coerced = 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000333#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200334 char *oldloc = NULL;
335
336 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
337 if (oldloc == NULL) {
Victor Stinner0f721472019-05-20 17:16:38 +0200338 return coerced;
Victor Stinner8ea09112018-09-03 17:05:18 +0200339 }
340
Victor Stinner94540602017-12-16 04:54:22 +0100341 const char *locale_override = getenv("LC_ALL");
342 if (locale_override == NULL || *locale_override == '\0') {
343 /* LC_ALL is also not set (or is set to an empty string) */
344 const _LocaleCoercionTarget *target = NULL;
345 for (target = _TARGET_LOCALES; target->locale_name; target++) {
346 const char *new_locale = setlocale(LC_CTYPE,
347 target->locale_name);
348 if (new_locale != NULL) {
Victor Stinnere2510952019-05-02 11:28:57 -0400349#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94540602017-12-16 04:54:22 +0100350 /* Also ensure that nl_langinfo works in this locale */
351 char *codeset = nl_langinfo(CODESET);
352 if (!codeset || *codeset == '\0') {
353 /* CODESET is not set or empty, so skip coercion */
354 new_locale = NULL;
355 _Py_SetLocaleFromEnv(LC_CTYPE);
356 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357 }
Victor Stinner94540602017-12-16 04:54:22 +0100358#endif
359 /* Successfully configured locale, so make it the default */
Victor Stinner0f721472019-05-20 17:16:38 +0200360 coerced = _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200361 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000362 }
363 }
364 }
365 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200366
367 setlocale(LC_CTYPE, oldloc);
368
369done:
370 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000371#endif
Victor Stinner0f721472019-05-20 17:16:38 +0200372 return coerced;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000373}
374
xdegaye1588be62017-11-12 12:45:59 +0100375/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
376 * isolate the idiosyncrasies of different libc implementations. It reads the
377 * appropriate environment variable and uses its value to select the locale for
378 * 'category'. */
379char *
380_Py_SetLocaleFromEnv(int category)
381{
Victor Stinner353933e2018-11-23 13:08:26 +0100382 char *res;
xdegaye1588be62017-11-12 12:45:59 +0100383#ifdef __ANDROID__
384 const char *locale;
385 const char **pvar;
386#ifdef PY_COERCE_C_LOCALE
387 const char *coerce_c_locale;
388#endif
389 const char *utf8_locale = "C.UTF-8";
390 const char *env_var_set[] = {
391 "LC_ALL",
392 "LC_CTYPE",
393 "LANG",
394 NULL,
395 };
396
397 /* Android setlocale(category, "") doesn't check the environment variables
398 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
399 * check the environment variables listed in env_var_set. */
400 for (pvar=env_var_set; *pvar; pvar++) {
401 locale = getenv(*pvar);
402 if (locale != NULL && *locale != '\0') {
403 if (strcmp(locale, utf8_locale) == 0 ||
404 strcmp(locale, "en_US.UTF-8") == 0) {
405 return setlocale(category, utf8_locale);
406 }
407 return setlocale(category, "C");
408 }
409 }
410
411 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
412 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
413 * Quote from POSIX section "8.2 Internationalization Variables":
414 * "4. If the LANG environment variable is not set or is set to the empty
415 * string, the implementation-defined default locale shall be used." */
416
417#ifdef PY_COERCE_C_LOCALE
418 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
419 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
420 /* Some other ported code may check the environment variables (e.g. in
421 * extension modules), so we make sure that they match the locale
422 * configuration */
423 if (setenv("LC_CTYPE", utf8_locale, 1)) {
424 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
425 "environment variable to %s\n", utf8_locale);
426 }
427 }
428#endif
Victor Stinner353933e2018-11-23 13:08:26 +0100429 res = setlocale(category, utf8_locale);
430#else /* !defined(__ANDROID__) */
431 res = setlocale(category, "");
432#endif
433 _Py_ResetForceASCII();
434 return res;
xdegaye1588be62017-11-12 12:45:59 +0100435}
436
Nick Coghlan6ea41862017-06-11 13:16:15 +1000437
Eric Snow1abcf672017-05-23 21:46:51 -0700438/* Global initializations. Can be undone by Py_Finalize(). Don't
439 call this twice without an intervening Py_Finalize() call.
440
Victor Stinner331a6a52019-05-27 16:39:22 +0200441 Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700442 must have a corresponding call to Py_Finalize.
443
444 Locking: you must hold the interpreter lock while calling these APIs.
445 (If the lock has not yet been initialized, that's equivalent to
446 having the lock, but you cannot use multiple threads.)
447
448*/
449
Victor Stinner331a6a52019-05-27 16:39:22 +0200450static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200451pyinit_core_reconfigure(_PyRuntimeState *runtime,
452 PyInterpreterState **interp_p,
Victor Stinner331a6a52019-05-27 16:39:22 +0200453 const PyConfig *config)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200454{
Victor Stinner331a6a52019-05-27 16:39:22 +0200455 PyStatus status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100456 PyThreadState *tstate = _PyThreadState_GET();
457 if (!tstate) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200458 return _PyStatus_ERR("failed to read thread state");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100459 }
460
461 PyInterpreterState *interp = tstate->interp;
462 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200463 return _PyStatus_ERR("can't make main interpreter");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100464 }
465 *interp_p = interp;
466
Victor Stinner331a6a52019-05-27 16:39:22 +0200467 _PyConfig_Write(config, runtime);
Victor Stinner1dc6e392018-07-25 02:49:17 +0200468
Victor Stinner331a6a52019-05-27 16:39:22 +0200469 status = _PyConfig_Copy(&interp->config, config);
470 if (_PyStatus_EXCEPTION(status)) {
471 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200472 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200473 config = &interp->config;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200474
Victor Stinner331a6a52019-05-27 16:39:22 +0200475 if (config->_install_importlib) {
476 status = _PyConfig_SetPathConfig(config);
477 if (_PyStatus_EXCEPTION(status)) {
478 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200479 }
480 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200481 return _PyStatus_OK();
Victor Stinner1dc6e392018-07-25 02:49:17 +0200482}
483
484
Victor Stinner331a6a52019-05-27 16:39:22 +0200485static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200486pycore_init_runtime(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200487 const PyConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000488{
Victor Stinner43125222019-04-24 18:23:53 +0200489 if (runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200490 return _PyStatus_ERR("main interpreter already initialized");
Victor Stinner1dc6e392018-07-25 02:49:17 +0200491 }
Victor Stinnerda273412017-12-15 01:46:02 +0100492
Victor Stinner331a6a52019-05-27 16:39:22 +0200493 _PyConfig_Write(config, runtime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600494
Eric Snow1abcf672017-05-23 21:46:51 -0700495 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
496 * threads behave a little more gracefully at interpreter shutdown.
497 * We clobber it here so the new interpreter can start with a clean
498 * slate.
499 *
500 * However, this may still lead to misbehaviour if there are daemon
501 * threads still hanging around from a previous Py_Initialize/Finalize
502 * pair :(
503 */
Victor Stinner43125222019-04-24 18:23:53 +0200504 runtime->finalizing = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600505
Victor Stinner331a6a52019-05-27 16:39:22 +0200506 PyStatus status = _Py_HashRandomization_Init(config);
507 if (_PyStatus_EXCEPTION(status)) {
508 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800509 }
510
Victor Stinner331a6a52019-05-27 16:39:22 +0200511 status = _PyInterpreterState_Enable(runtime);
512 if (_PyStatus_EXCEPTION(status)) {
513 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -0800514 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200515 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100516}
Victor Stinnera7368ac2017-11-15 18:11:45 -0800517
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100518
Victor Stinner331a6a52019-05-27 16:39:22 +0200519static PyStatus
Victor Stinner43125222019-04-24 18:23:53 +0200520pycore_create_interpreter(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200521 const PyConfig *config,
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100522 PyInterpreterState **interp_p)
523{
524 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100525 if (interp == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200526 return _PyStatus_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100527 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200528 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100529
Victor Stinner331a6a52019-05-27 16:39:22 +0200530 PyStatus status = _PyConfig_Copy(&interp->config, config);
531 if (_PyStatus_EXCEPTION(status)) {
532 return status;
Victor Stinnerda273412017-12-15 01:46:02 +0100533 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200534 config = &interp->config;
Nick Coghland6009512014-11-20 21:39:37 +1000535
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200536 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000537 if (tstate == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +0200538 return _PyStatus_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000539 (void) PyThreadState_Swap(tstate);
540
Victor Stinner99fcc612019-04-29 13:04:07 +0200541 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
542 destroying the GIL might fail when it is being referenced from
543 another running thread (see issue #9901).
Nick Coghland6009512014-11-20 21:39:37 +1000544 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000545 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Victor Stinner09532fe2019-05-10 23:39:09 +0200546 _PyEval_FiniThreads(&runtime->ceval);
Victor Stinner2914bb32018-01-29 11:57:45 +0100547
Nick Coghland6009512014-11-20 21:39:37 +1000548 /* Auto-thread-state API */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200549 _PyGILState_Init(runtime, interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000550
Victor Stinner2914bb32018-01-29 11:57:45 +0100551 /* Create the GIL */
552 PyEval_InitThreads();
553
Victor Stinner331a6a52019-05-27 16:39:22 +0200554 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100555}
Nick Coghland6009512014-11-20 21:39:37 +1000556
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100557
Victor Stinner331a6a52019-05-27 16:39:22 +0200558static PyStatus
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100559pycore_init_types(void)
560{
Victor Stinner331a6a52019-05-27 16:39:22 +0200561 PyStatus status = _PyTypes_Init();
562 if (_PyStatus_EXCEPTION(status)) {
563 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100564 }
565
Victor Stinner331a6a52019-05-27 16:39:22 +0200566 status = _PyUnicode_Init();
567 if (_PyStatus_EXCEPTION(status)) {
568 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100569 }
570
571 if (_PyStructSequence_Init() < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200572 return _PyStatus_ERR("can't initialize structseq");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100573 }
574
575 if (!_PyLong_Init()) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200576 return _PyStatus_ERR("can't init longs");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100577 }
Nick Coghland6009512014-11-20 21:39:37 +1000578
Victor Stinner331a6a52019-05-27 16:39:22 +0200579 status = _PyExc_Init();
580 if (_PyStatus_EXCEPTION(status)) {
581 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100582 }
583
584 if (!_PyFloat_Init()) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200585 return _PyStatus_ERR("can't init float");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100586 }
Nick Coghland6009512014-11-20 21:39:37 +1000587
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100588 if (!_PyContext_Init()) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200589 return _PyStatus_ERR("can't init context");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100590 }
Victor Stinneref9d9b62019-05-22 11:28:22 +0200591
Victor Stinner331a6a52019-05-27 16:39:22 +0200592 status = _PyErr_Init();
593 if (_PyStatus_EXCEPTION(status)) {
594 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +0200595 }
596
Victor Stinner331a6a52019-05-27 16:39:22 +0200597 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100598}
599
600
Victor Stinner331a6a52019-05-27 16:39:22 +0200601static PyStatus
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100602pycore_init_builtins(PyInterpreterState *interp)
603{
604 PyObject *bimod = _PyBuiltin_Init();
605 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200606 return _PyStatus_ERR("can't initialize builtins modules");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100607 }
608 _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
609
610 interp->builtins = PyModule_GetDict(bimod);
611 if (interp->builtins == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200612 return _PyStatus_ERR("can't initialize builtins dict");
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100613 }
614 Py_INCREF(interp->builtins);
615
Victor Stinner331a6a52019-05-27 16:39:22 +0200616 PyStatus status = _PyBuiltins_AddExceptions(bimod);
617 if (_PyStatus_EXCEPTION(status)) {
618 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100619 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200620 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100621}
622
623
Victor Stinner331a6a52019-05-27 16:39:22 +0200624static PyStatus
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100625pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
626{
Victor Stinner331a6a52019-05-27 16:39:22 +0200627 PyStatus status = _PyImport_Init(interp);
628 if (_PyStatus_EXCEPTION(status)) {
629 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800630 }
Nick Coghland6009512014-11-20 21:39:37 +1000631
Victor Stinner331a6a52019-05-27 16:39:22 +0200632 status = _PyImportHooks_Init();
633 if (_PyStatus_EXCEPTION(status)) {
634 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800635 }
Nick Coghland6009512014-11-20 21:39:37 +1000636
637 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100638 if (_PyWarnings_Init() == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200639 return _PyStatus_ERR("can't initialize warnings");
Victor Stinner1f151112017-11-23 10:43:14 +0100640 }
Nick Coghland6009512014-11-20 21:39:37 +1000641
Victor Stinner331a6a52019-05-27 16:39:22 +0200642 if (interp->config._install_importlib) {
643 status = _PyConfig_SetPathConfig(&interp->config);
644 if (_PyStatus_EXCEPTION(status)) {
645 return status;
Victor Stinnerb1147e42018-07-21 02:06:16 +0200646 }
647 }
648
Eric Snow1abcf672017-05-23 21:46:51 -0700649 /* This call sets up builtin and frozen import support */
Victor Stinner331a6a52019-05-27 16:39:22 +0200650 if (interp->config._install_importlib) {
651 status = init_importlib(interp, sysmod);
652 if (_PyStatus_EXCEPTION(status)) {
653 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800654 }
Eric Snow1abcf672017-05-23 21:46:51 -0700655 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200656 return _PyStatus_OK();
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100657}
658
659
Victor Stinner331a6a52019-05-27 16:39:22 +0200660static PyStatus
661pyinit_config(_PyRuntimeState *runtime,
662 PyInterpreterState **interp_p,
663 const PyConfig *config)
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100664{
665 PyInterpreterState *interp;
666
Victor Stinner331a6a52019-05-27 16:39:22 +0200667 _PyConfig_Write(config, runtime);
Victor Stinner20004952019-03-26 02:31:11 +0100668
Victor Stinner331a6a52019-05-27 16:39:22 +0200669 PyStatus status = pycore_init_runtime(runtime, config);
670 if (_PyStatus_EXCEPTION(status)) {
671 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100672 }
673
Victor Stinner331a6a52019-05-27 16:39:22 +0200674 status = pycore_create_interpreter(runtime, config, &interp);
675 if (_PyStatus_EXCEPTION(status)) {
676 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100677 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200678 config = &interp->config;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100679 *interp_p = interp;
680
Victor Stinner331a6a52019-05-27 16:39:22 +0200681 status = pycore_init_types();
682 if (_PyStatus_EXCEPTION(status)) {
683 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100684 }
685
686 PyObject *sysmod;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200687 status = _PySys_Create(runtime, interp, &sysmod);
Victor Stinner331a6a52019-05-27 16:39:22 +0200688 if (_PyStatus_EXCEPTION(status)) {
689 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100690 }
691
Victor Stinner331a6a52019-05-27 16:39:22 +0200692 status = pycore_init_builtins(interp);
693 if (_PyStatus_EXCEPTION(status)) {
694 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100695 }
696
Victor Stinner331a6a52019-05-27 16:39:22 +0200697 status = pycore_init_import_warnings(interp, sysmod);
698 if (_PyStatus_EXCEPTION(status)) {
699 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100700 }
Eric Snow1abcf672017-05-23 21:46:51 -0700701
702 /* Only when we get here is the runtime core fully initialized */
Victor Stinner43125222019-04-24 18:23:53 +0200703 runtime->core_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200704 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700705}
706
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100707
Victor Stinner331a6a52019-05-27 16:39:22 +0200708PyStatus
709_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100710{
Victor Stinner331a6a52019-05-27 16:39:22 +0200711 PyStatus status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100712
Victor Stinner6d1c4672019-05-20 11:02:00 +0200713 if (src_config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200714 return _PyStatus_ERR("preinitialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +0200715 }
716
Victor Stinner331a6a52019-05-27 16:39:22 +0200717 status = _PyRuntime_Initialize();
718 if (_PyStatus_EXCEPTION(status)) {
719 return status;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100720 }
Victor Stinner43125222019-04-24 18:23:53 +0200721 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100722
Victor Stinner43125222019-04-24 18:23:53 +0200723 if (runtime->pre_initialized) {
Victor Stinnerf72346c2019-03-25 17:54:58 +0100724 /* If it's already configured: ignored the new configuration */
Victor Stinner331a6a52019-05-27 16:39:22 +0200725 return _PyStatus_OK();
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100726 }
727
Victor Stinner331a6a52019-05-27 16:39:22 +0200728 PyPreConfig config;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200729 _PyPreConfig_InitFromPreConfig(&config, src_config);
Victor Stinnerf72346c2019-03-25 17:54:58 +0100730
Victor Stinner331a6a52019-05-27 16:39:22 +0200731 status = _PyPreConfig_Read(&config, args);
732 if (_PyStatus_EXCEPTION(status)) {
733 return status;
Victor Stinnerf29084d2019-03-20 02:20:13 +0100734 }
735
Victor Stinner331a6a52019-05-27 16:39:22 +0200736 status = _PyPreConfig_Write(&config);
737 if (_PyStatus_EXCEPTION(status)) {
738 return status;
Victor Stinnerf72346c2019-03-25 17:54:58 +0100739 }
740
Victor Stinner43125222019-04-24 18:23:53 +0200741 runtime->pre_initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200742 return _PyStatus_OK();
Victor Stinnerf72346c2019-03-25 17:54:58 +0100743}
744
Victor Stinner70005ac2019-05-02 15:25:34 -0400745
Victor Stinner331a6a52019-05-27 16:39:22 +0200746PyStatus
747Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
Victor Stinnerf72346c2019-03-25 17:54:58 +0100748{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100749 _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400750 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinnerf29084d2019-03-20 02:20:13 +0100751}
752
753
Victor Stinner331a6a52019-05-27 16:39:22 +0200754PyStatus
755Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
Victor Stinner20004952019-03-26 02:31:11 +0100756{
Victor Stinner5ac27a52019-03-27 13:40:14 +0100757 _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
Victor Stinner70005ac2019-05-02 15:25:34 -0400758 return _Py_PreInitializeFromPyArgv(src_config, &args);
Victor Stinner20004952019-03-26 02:31:11 +0100759}
760
761
Victor Stinner331a6a52019-05-27 16:39:22 +0200762PyStatus
763Py_PreInitialize(const PyPreConfig *src_config)
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100764{
Victor Stinner70005ac2019-05-02 15:25:34 -0400765 return _Py_PreInitializeFromPyArgv(src_config, NULL);
Victor Stinnera6fbc4e2019-03-25 18:37:10 +0100766}
767
768
Victor Stinner331a6a52019-05-27 16:39:22 +0200769PyStatus
770_Py_PreInitializeFromConfig(const PyConfig *config,
771 const _PyArgv *args)
Victor Stinnerf29084d2019-03-20 02:20:13 +0100772{
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 assert(config != NULL);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200774
Victor Stinner331a6a52019-05-27 16:39:22 +0200775 PyStatus status = _PyRuntime_Initialize();
776 if (_PyStatus_EXCEPTION(status)) {
777 return status;
Victor Stinner6d1c4672019-05-20 11:02:00 +0200778 }
779 _PyRuntimeState *runtime = &_PyRuntime;
780
781 if (runtime->pre_initialized) {
782 /* Already initialized: do nothing */
Victor Stinner331a6a52019-05-27 16:39:22 +0200783 return _PyStatus_OK();
Victor Stinner70005ac2019-05-02 15:25:34 -0400784 }
Victor Stinnercab5d072019-05-17 19:01:14 +0200785
Victor Stinner331a6a52019-05-27 16:39:22 +0200786 PyPreConfig preconfig;
787 _PyPreConfig_InitFromConfig(&preconfig, config);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200788
Victor Stinner331a6a52019-05-27 16:39:22 +0200789 if (!config->parse_argv) {
790 return Py_PreInitialize(&preconfig);
Victor Stinner6d1c4672019-05-20 11:02:00 +0200791 }
792 else if (args == NULL) {
Victor Stinnercab5d072019-05-17 19:01:14 +0200793 _PyArgv config_args = {
794 .use_bytes_argv = 0,
Victor Stinner331a6a52019-05-27 16:39:22 +0200795 .argc = config->argv.length,
796 .wchar_argv = config->argv.items};
Victor Stinner6d1c4672019-05-20 11:02:00 +0200797 return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200798 }
799 else {
Victor Stinner6d1c4672019-05-20 11:02:00 +0200800 return _Py_PreInitializeFromPyArgv(&preconfig, args);
Victor Stinnercab5d072019-05-17 19:01:14 +0200801 }
Victor Stinner7d2ef3e2019-03-06 00:36:56 +0100802}
803
804
Victor Stinner6d43f6f2019-01-22 21:18:05 +0100805/* Begin interpreter initialization
806 *
807 * On return, the first thread and interpreter state have been created,
808 * but the compiler, signal handling, multithreading and
809 * multiple interpreter support, and codec infrastructure are not yet
810 * available.
811 *
812 * The import system will support builtin and frozen modules only.
813 * The only supported io is writing to sys.stderr
814 *
815 * If any operation invoked by this function fails, a fatal error is
816 * issued and the function does not return.
817 *
818 * Any code invoked from this function should *not* assume it has access
819 * to the Python C API (unless the API is explicitly listed as being
820 * safe to call without calling Py_Initialize first)
821 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200822static PyStatus
Victor Stinner5edcf262019-05-23 00:57:57 +0200823pyinit_core(_PyRuntimeState *runtime,
Victor Stinner331a6a52019-05-27 16:39:22 +0200824 const PyConfig *src_config,
Victor Stinner5edcf262019-05-23 00:57:57 +0200825 PyInterpreterState **interp_p)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200826{
Victor Stinner331a6a52019-05-27 16:39:22 +0200827 PyStatus status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200828
Victor Stinner331a6a52019-05-27 16:39:22 +0200829 status = _Py_PreInitializeFromConfig(src_config, NULL);
830 if (_PyStatus_EXCEPTION(status)) {
831 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200832 }
833
Victor Stinner331a6a52019-05-27 16:39:22 +0200834 PyConfig config;
835 _PyConfig_InitCompatConfig(&config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200836
Victor Stinner331a6a52019-05-27 16:39:22 +0200837 status = _PyConfig_Copy(&config, src_config);
838 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200839 goto done;
840 }
841
Victor Stinner331a6a52019-05-27 16:39:22 +0200842 status = PyConfig_Read(&config);
843 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200844 goto done;
845 }
846
847 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200848 status = pyinit_config(runtime, interp_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200849 }
850 else {
Victor Stinner331a6a52019-05-27 16:39:22 +0200851 status = pyinit_core_reconfigure(runtime, interp_p, &config);
Victor Stinner5edcf262019-05-23 00:57:57 +0200852 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200853 if (_PyStatus_EXCEPTION(status)) {
Victor Stinner5edcf262019-05-23 00:57:57 +0200854 goto done;
855 }
856
857done:
Victor Stinner331a6a52019-05-27 16:39:22 +0200858 PyConfig_Clear(&config);
859 return status;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200860}
861
Victor Stinner5ac27a52019-03-27 13:40:14 +0100862
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200863/* Py_Initialize() has already been called: update the main interpreter
864 configuration. Example of bpo-34008: Py_Main() called after
865 Py_Initialize(). */
Victor Stinner331a6a52019-05-27 16:39:22 +0200866static PyStatus
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100867_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200868{
Victor Stinner331a6a52019-05-27 16:39:22 +0200869 PyConfig *config = &interp->config;
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100870
Victor Stinner331a6a52019-05-27 16:39:22 +0200871 PyObject *argv = _PyWideStringList_AsList(&config->argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100872 if (argv == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200873 return _PyStatus_NO_MEMORY(); \
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100874 }
875
876 int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
877 Py_DECREF(argv);
878 if (res < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200879 return _PyStatus_ERR("fail to set sys.argv");
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200880 }
Victor Stinner331a6a52019-05-27 16:39:22 +0200881 return _PyStatus_OK();
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200882}
883
Eric Snowc7ec9982017-05-23 23:00:52 -0700884/* Update interpreter state based on supplied configuration settings
885 *
886 * After calling this function, most of the restrictions on the interpreter
887 * are lifted. The only remaining incomplete settings are those related
888 * to the main module (sys.argv[0], __main__ metadata)
889 *
890 * Calling this when the interpreter is not initializing, is already
891 * initialized or without a valid current thread state is a fatal error.
892 * Other errors should be reported as normal Python exceptions with a
893 * non-zero return code.
894 */
Victor Stinner331a6a52019-05-27 16:39:22 +0200895static PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +0200896pyinit_main(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow1abcf672017-05-23 21:46:51 -0700897{
Victor Stinner43125222019-04-24 18:23:53 +0200898 if (!runtime->core_initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200899 return _PyStatus_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700900 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700901
Victor Stinner1dc6e392018-07-25 02:49:17 +0200902 /* Configure the main interpreter */
Victor Stinner838f2642019-06-13 22:41:23 +0200903 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
Victor Stinner331a6a52019-05-27 16:39:22 +0200904 PyConfig *config = &interp->config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700905
Victor Stinner43125222019-04-24 18:23:53 +0200906 if (runtime->initialized) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +0100907 return _Py_ReconfigureMainInterpreter(interp);
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200908 }
909
Victor Stinner331a6a52019-05-27 16:39:22 +0200910 if (!config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700911 /* Special mode for freeze_importlib: run with no import system
912 *
913 * This means anything which needs support from extension modules
914 * or pure Python code in the standard library won't work.
915 */
Victor Stinner43125222019-04-24 18:23:53 +0200916 runtime->initialized = 1;
Victor Stinner331a6a52019-05-27 16:39:22 +0200917 return _PyStatus_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700918 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100919
Victor Stinner33c377e2017-12-05 15:12:41 +0100920 if (_PyTime_Init() < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200921 return _PyStatus_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100922 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200923
Victor Stinner838f2642019-06-13 22:41:23 +0200924 if (_PySys_InitMain(runtime, tstate) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200925 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100926 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800927
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200928 PyStatus status = init_importlib_external(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +0200929 if (_PyStatus_EXCEPTION(status)) {
930 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 }
Nick Coghland6009512014-11-20 21:39:37 +1000932
933 /* initialize the faulthandler module */
Victor Stinner331a6a52019-05-27 16:39:22 +0200934 status = _PyFaulthandler_Init(config->faulthandler);
935 if (_PyStatus_EXCEPTION(status)) {
936 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800937 }
Nick Coghland6009512014-11-20 21:39:37 +1000938
Victor Stinner331a6a52019-05-27 16:39:22 +0200939 status = _PyUnicode_InitEncodings(interp);
940 if (_PyStatus_EXCEPTION(status)) {
941 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800942 }
Nick Coghland6009512014-11-20 21:39:37 +1000943
Victor Stinner331a6a52019-05-27 16:39:22 +0200944 if (config->install_signal_handlers) {
945 status = init_signals();
946 if (_PyStatus_EXCEPTION(status)) {
947 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800948 }
949 }
Nick Coghland6009512014-11-20 21:39:37 +1000950
Victor Stinner331a6a52019-05-27 16:39:22 +0200951 if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
952 return _PyStatus_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200953 }
Nick Coghland6009512014-11-20 21:39:37 +1000954
Victor Stinner331a6a52019-05-27 16:39:22 +0200955 status = add_main_module(interp);
956 if (_PyStatus_EXCEPTION(status)) {
957 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800958 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800959
Victor Stinner331a6a52019-05-27 16:39:22 +0200960 status = init_sys_streams(interp);
961 if (_PyStatus_EXCEPTION(status)) {
962 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800963 }
Nick Coghland6009512014-11-20 21:39:37 +1000964
965 /* Initialize warnings. */
Victor Stinner37cd9822018-11-16 11:55:35 +0100966 PyObject *warnoptions = PySys_GetObject("warnoptions");
967 if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
Victor Stinner5d862462017-12-19 11:35:58 +0100968 {
Nick Coghland6009512014-11-20 21:39:37 +1000969 PyObject *warnings_module = PyImport_ImportModule("warnings");
970 if (warnings_module == NULL) {
971 fprintf(stderr, "'import warnings' failed; traceback:\n");
972 PyErr_Print();
973 }
974 Py_XDECREF(warnings_module);
975 }
976
Victor Stinner43125222019-04-24 18:23:53 +0200977 runtime->initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700978
Victor Stinner331a6a52019-05-27 16:39:22 +0200979 if (config->site_import) {
980 status = init_import_size(); /* Module site */
981 if (_PyStatus_EXCEPTION(status)) {
982 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800983 }
984 }
Victor Stinnercf215042018-08-29 22:56:06 +0200985
986#ifndef MS_WINDOWS
Victor Stinner43125222019-04-24 18:23:53 +0200987 emit_stderr_warning_for_legacy_locale(runtime);
Victor Stinnercf215042018-08-29 22:56:06 +0200988#endif
989
Victor Stinner331a6a52019-05-27 16:39:22 +0200990 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000991}
992
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200993
Victor Stinner331a6a52019-05-27 16:39:22 +0200994PyStatus
Victor Stinner9ef5dca2019-05-16 17:38:16 +0200995_Py_InitializeMain(void)
996{
Victor Stinner331a6a52019-05-27 16:39:22 +0200997 PyStatus status = _PyRuntime_Initialize();
998 if (_PyStatus_EXCEPTION(status)) {
999 return status;
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001000 }
1001 _PyRuntimeState *runtime = &_PyRuntime;
1002 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1003
Victor Stinner0fd2c302019-06-04 03:15:09 +02001004 return pyinit_main(runtime, interp);
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001005}
1006
1007
Victor Stinner331a6a52019-05-27 16:39:22 +02001008PyStatus
1009Py_InitializeFromConfig(const PyConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -07001010{
Victor Stinner6d1c4672019-05-20 11:02:00 +02001011 if (config == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001012 return _PyStatus_ERR("initialization config is NULL");
Victor Stinner6d1c4672019-05-20 11:02:00 +02001013 }
1014
Victor Stinner331a6a52019-05-27 16:39:22 +02001015 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001016
Victor Stinner331a6a52019-05-27 16:39:22 +02001017 status = _PyRuntime_Initialize();
1018 if (_PyStatus_EXCEPTION(status)) {
1019 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001020 }
1021 _PyRuntimeState *runtime = &_PyRuntime;
1022
1023 PyInterpreterState *interp = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001024 status = pyinit_core(runtime, config, &interp);
1025 if (_PyStatus_EXCEPTION(status)) {
1026 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001027 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001028 config = &interp->config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +01001029
Victor Stinner9ef5dca2019-05-16 17:38:16 +02001030 if (config->_init_main) {
Victor Stinner0fd2c302019-06-04 03:15:09 +02001031 status = pyinit_main(runtime, interp);
Victor Stinner331a6a52019-05-27 16:39:22 +02001032 if (_PyStatus_EXCEPTION(status)) {
1033 return status;
Victor Stinner484f20d2019-03-27 02:04:16 +01001034 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001035 }
Victor Stinner484f20d2019-03-27 02:04:16 +01001036
Victor Stinner331a6a52019-05-27 16:39:22 +02001037 return _PyStatus_OK();
Victor Stinner5ac27a52019-03-27 13:40:14 +01001038}
1039
1040
Eric Snow1abcf672017-05-23 21:46:51 -07001041void
Nick Coghland6009512014-11-20 21:39:37 +10001042Py_InitializeEx(int install_sigs)
1043{
Victor Stinner331a6a52019-05-27 16:39:22 +02001044 PyStatus status;
Victor Stinner43125222019-04-24 18:23:53 +02001045
Victor Stinner331a6a52019-05-27 16:39:22 +02001046 status = _PyRuntime_Initialize();
1047 if (_PyStatus_EXCEPTION(status)) {
1048 Py_ExitStatusException(status);
Victor Stinner43125222019-04-24 18:23:53 +02001049 }
1050 _PyRuntimeState *runtime = &_PyRuntime;
1051
1052 if (runtime->initialized) {
Victor Stinner1dc6e392018-07-25 02:49:17 +02001053 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1054 return;
1055 }
1056
Victor Stinner331a6a52019-05-27 16:39:22 +02001057 PyConfig config;
1058 _PyConfig_InitCompatConfig(&config);
Victor Stinner1dc6e392018-07-25 02:49:17 +02001059 config.install_signal_handlers = install_sigs;
1060
Victor Stinner331a6a52019-05-27 16:39:22 +02001061 status = Py_InitializeFromConfig(&config);
1062 if (_PyStatus_EXCEPTION(status)) {
1063 Py_ExitStatusException(status);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001064 }
Nick Coghland6009512014-11-20 21:39:37 +10001065}
1066
1067void
1068Py_Initialize(void)
1069{
1070 Py_InitializeEx(1);
1071}
1072
1073
1074#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001075extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +10001076#endif
1077
1078/* Flush stdout and stderr */
1079
1080static int
1081file_is_closed(PyObject *fobj)
1082{
1083 int r;
1084 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1085 if (tmp == NULL) {
1086 PyErr_Clear();
1087 return 0;
1088 }
1089 r = PyObject_IsTrue(tmp);
1090 Py_DECREF(tmp);
1091 if (r < 0)
1092 PyErr_Clear();
1093 return r > 0;
1094}
1095
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001096static int
Nick Coghland6009512014-11-20 21:39:37 +10001097flush_std_files(void)
1098{
1099 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1100 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1101 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001102 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001103
1104 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001105 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001106 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001107 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001108 status = -1;
1109 }
Nick Coghland6009512014-11-20 21:39:37 +10001110 else
1111 Py_DECREF(tmp);
1112 }
1113
1114 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001115 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001116 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001117 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001118 status = -1;
1119 }
Nick Coghland6009512014-11-20 21:39:37 +10001120 else
1121 Py_DECREF(tmp);
1122 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001123
1124 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001125}
1126
1127/* Undo the effect of Py_Initialize().
1128
1129 Beware: if multiple interpreter and/or thread states exist, these
1130 are not wiped out; only the current thread and interpreter state
1131 are deleted. But since everything else is deleted, those other
1132 interpreter and thread states should no longer be used.
1133
1134 (XXX We should do better, e.g. wipe out all interpreters and
1135 threads.)
1136
1137 Locking: as above.
1138
1139*/
1140
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001141int
1142Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001143{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001144 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001145
Victor Stinner8e91c242019-04-24 17:24:01 +02001146 _PyRuntimeState *runtime = &_PyRuntime;
1147 if (!runtime->initialized) {
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001148 return status;
Victor Stinner8e91c242019-04-24 17:24:01 +02001149 }
Nick Coghland6009512014-11-20 21:39:37 +10001150
Eric Snow842a2f02019-03-15 15:47:51 -06001151 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001152 wait_for_thread_shutdown();
1153
Eric Snow842a2f02019-03-15 15:47:51 -06001154 // Make any remaining pending calls.
Victor Stinnere225beb2019-06-03 18:14:24 +02001155 _Py_FinishPendingCalls(runtime);
1156
1157 /* Get current thread state and interpreter pointer */
1158 PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1159 PyInterpreterState *interp = tstate->interp;
Victor Stinner8e91c242019-04-24 17:24:01 +02001160
Nick Coghland6009512014-11-20 21:39:37 +10001161 /* The interpreter is still entirely intact at this point, and the
1162 * exit funcs may be relying on that. In particular, if some thread
1163 * or exit func is still waiting to do an import, the import machinery
1164 * expects Py_IsInitialized() to return true. So don't say the
Eric Snow842a2f02019-03-15 15:47:51 -06001165 * runtime is uninitialized until after the exit funcs have run.
Nick Coghland6009512014-11-20 21:39:37 +10001166 * Note that Threading.py uses an exit func to do a join on all the
1167 * threads created thru it, so this also protects pending imports in
1168 * the threads created via Threading.
1169 */
Nick Coghland6009512014-11-20 21:39:37 +10001170
Marcel Plch776407f2017-12-20 11:17:58 +01001171 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001172
Victor Stinnerda273412017-12-15 01:46:02 +01001173 /* Copy the core config, PyInterpreterState_Delete() free
1174 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001175#ifdef Py_REF_DEBUG
Victor Stinner331a6a52019-05-27 16:39:22 +02001176 int show_ref_count = interp->config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001177#endif
1178#ifdef Py_TRACE_REFS
Victor Stinner331a6a52019-05-27 16:39:22 +02001179 int dump_refs = interp->config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001180#endif
1181#ifdef WITH_PYMALLOC
Victor Stinner331a6a52019-05-27 16:39:22 +02001182 int malloc_stats = interp->config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001183#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001184
Nick Coghland6009512014-11-20 21:39:37 +10001185 /* Remaining threads (e.g. daemon threads) will automatically exit
1186 after taking the GIL (in PyEval_RestoreThread()). */
Victor Stinner8e91c242019-04-24 17:24:01 +02001187 runtime->finalizing = tstate;
1188 runtime->initialized = 0;
1189 runtime->core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001190
Victor Stinnere0deff32015-03-24 13:46:18 +01001191 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001192 if (flush_std_files() < 0) {
1193 status = -1;
1194 }
Nick Coghland6009512014-11-20 21:39:37 +10001195
1196 /* Disable signal handling */
1197 PyOS_FiniInterrupts();
1198
1199 /* Collect garbage. This may call finalizers; it's nice to call these
1200 * before all modules are destroyed.
1201 * XXX If a __del__ or weakref callback is triggered here, and tries to
1202 * XXX import a module, bad things can happen, because Python no
1203 * XXX longer believes it's initialized.
1204 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1205 * XXX is easy to provoke that way. I've also seen, e.g.,
1206 * XXX Exception exceptions.ImportError: 'No module named sha'
1207 * XXX in <function callback at 0x008F5718> ignored
1208 * XXX but I'm unclear on exactly how that one happens. In any case,
1209 * XXX I haven't seen a real-life report of either of these.
1210 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001211 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001212#ifdef COUNT_ALLOCS
1213 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1214 each collection might release some types from the type
1215 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001216 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001217 /* nothing */;
1218#endif
Eric Snowdae02762017-09-14 00:35:58 -07001219
Steve Dowerb82e17e2019-05-23 08:45:22 -07001220 /* Clear all loghooks */
1221 /* We want minimal exposure of this function, so define the extern
1222 * here. The linker should discover the correct function without
1223 * exporting a symbol. */
1224 extern void _PySys_ClearAuditHooks(void);
1225 _PySys_ClearAuditHooks();
1226
Nick Coghland6009512014-11-20 21:39:37 +10001227 /* Destroy all modules */
1228 PyImport_Cleanup();
1229
Inada Naoki91234a12019-06-03 21:30:58 +09001230 /* Print debug stats if any */
1231 _PyEval_Fini();
1232
Victor Stinnere0deff32015-03-24 13:46:18 +01001233 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001234 if (flush_std_files() < 0) {
1235 status = -1;
1236 }
Nick Coghland6009512014-11-20 21:39:37 +10001237
1238 /* Collect final garbage. This disposes of cycles created by
1239 * class definitions, for example.
1240 * XXX This is disabled because it caused too many problems. If
1241 * XXX a __del__ or weakref callback triggers here, Python code has
1242 * XXX a hard time running, because even the sys module has been
1243 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1244 * XXX One symptom is a sequence of information-free messages
1245 * XXX coming from threads (if a __del__ or callback is invoked,
1246 * XXX other threads can execute too, and any exception they encounter
1247 * XXX triggers a comedy of errors as subsystem after subsystem
1248 * XXX fails to find what it *expects* to find in sys to help report
1249 * XXX the exception and consequent unexpected failures). I've also
1250 * XXX seen segfaults then, after adding print statements to the
1251 * XXX Python code getting called.
1252 */
1253#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001254 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001255#endif
1256
1257 /* Disable tracemalloc after all Python objects have been destroyed,
1258 so it is possible to use tracemalloc in objects destructor. */
1259 _PyTraceMalloc_Fini();
1260
1261 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1262 _PyImport_Fini();
1263
1264 /* Cleanup typeobject.c's internal caches. */
1265 _PyType_Fini();
1266
1267 /* unload faulthandler module */
1268 _PyFaulthandler_Fini();
1269
1270 /* Debugging stuff */
1271#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001272 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001273#endif
1274 /* dump hash stats */
1275 _PyHash_Fini();
1276
Eric Snowdae02762017-09-14 00:35:58 -07001277#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001278 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001279 _PyDebug_PrintTotalRefs();
1280 }
Eric Snowdae02762017-09-14 00:35:58 -07001281#endif
Nick Coghland6009512014-11-20 21:39:37 +10001282
1283#ifdef Py_TRACE_REFS
1284 /* Display all objects still alive -- this can invoke arbitrary
1285 * __repr__ overrides, so requires a mostly-intact interpreter.
1286 * Alas, a lot of stuff may still be alive now that will be cleaned
1287 * up later.
1288 */
Victor Stinnerda273412017-12-15 01:46:02 +01001289 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001290 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001291 }
Nick Coghland6009512014-11-20 21:39:37 +10001292#endif /* Py_TRACE_REFS */
1293
1294 /* Clear interpreter state and all thread states. */
1295 PyInterpreterState_Clear(interp);
1296
1297 /* Now we decref the exception classes. After this point nothing
1298 can raise an exception. That's okay, because each Fini() method
1299 below has been checked to make sure no exceptions are ever
1300 raised.
1301 */
1302
1303 _PyExc_Fini();
1304
1305 /* Sundry finalizers */
1306 PyMethod_Fini();
1307 PyFrame_Fini();
1308 PyCFunction_Fini();
1309 PyTuple_Fini();
1310 PyList_Fini();
1311 PySet_Fini();
1312 PyBytes_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001313 PyLong_Fini();
1314 PyFloat_Fini();
1315 PyDict_Fini();
1316 PySlice_Fini();
Victor Stinner8e91c242019-04-24 17:24:01 +02001317 _PyGC_Fini(runtime);
Eric Snow86ea5812019-05-10 13:29:55 -04001318 _PyWarnings_Fini(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07001319 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001320 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001321 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001322 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001323
1324 /* Cleanup Unicode implementation */
1325 _PyUnicode_Fini();
1326
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001327 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001328
1329 /* XXX Still allocated:
1330 - various static ad-hoc pointers to interned strings
1331 - int and float free list blocks
1332 - whatever various modules and libraries allocate
1333 */
1334
1335 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1336
1337 /* Cleanup auto-thread-state */
Victor Stinner8e91c242019-04-24 17:24:01 +02001338 _PyGILState_Fini(runtime);
Nick Coghland6009512014-11-20 21:39:37 +10001339
1340 /* Delete current thread. After this, many C API calls become crashy. */
1341 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001342
Nick Coghland6009512014-11-20 21:39:37 +10001343 PyInterpreterState_Delete(interp);
1344
1345#ifdef Py_TRACE_REFS
1346 /* Display addresses (& refcnts) of all objects still alive.
1347 * An address can be used to find the repr of the object, printed
1348 * above by _Py_PrintReferences.
1349 */
Victor Stinnerda273412017-12-15 01:46:02 +01001350 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001351 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001352 }
Nick Coghland6009512014-11-20 21:39:37 +10001353#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001354#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001355 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001356 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001357 }
Nick Coghland6009512014-11-20 21:39:37 +10001358#endif
1359
Victor Stinner8e91c242019-04-24 17:24:01 +02001360 call_ll_exitfuncs(runtime);
Victor Stinner9316ee42017-11-25 03:17:57 +01001361
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001362 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001363 return status;
1364}
1365
1366void
1367Py_Finalize(void)
1368{
1369 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001370}
1371
1372/* Create and initialize a new interpreter and thread, and return the
1373 new thread. This requires that Py_Initialize() has been called
1374 first.
1375
1376 Unsuccessful initialization yields a NULL pointer. Note that *no*
1377 exception information is available even in this case -- the
1378 exception information is held in the thread, and there is no
1379 thread.
1380
1381 Locking: as above.
1382
1383*/
1384
Victor Stinner331a6a52019-05-27 16:39:22 +02001385static PyStatus
Victor Stinnera7368ac2017-11-15 18:11:45 -08001386new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001387{
Victor Stinner331a6a52019-05-27 16:39:22 +02001388 PyStatus status;
Nick Coghland6009512014-11-20 21:39:37 +10001389
Victor Stinner331a6a52019-05-27 16:39:22 +02001390 status = _PyRuntime_Initialize();
1391 if (_PyStatus_EXCEPTION(status)) {
1392 return status;
Victor Stinner43125222019-04-24 18:23:53 +02001393 }
1394 _PyRuntimeState *runtime = &_PyRuntime;
1395
1396 if (!runtime->initialized) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001397 return _PyStatus_ERR("Py_Initialize must be called first");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001398 }
Nick Coghland6009512014-11-20 21:39:37 +10001399
Victor Stinner8a1be612016-03-14 22:07:55 +01001400 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1401 interpreters: disable PyGILState_Check(). */
1402 _PyGILState_check_enabled = 0;
1403
Victor Stinner43125222019-04-24 18:23:53 +02001404 PyInterpreterState *interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001405 if (interp == NULL) {
1406 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001407 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001408 }
Nick Coghland6009512014-11-20 21:39:37 +10001409
Victor Stinner43125222019-04-24 18:23:53 +02001410 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001411 if (tstate == NULL) {
1412 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001413 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001414 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001415 }
1416
Victor Stinner43125222019-04-24 18:23:53 +02001417 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Nick Coghland6009512014-11-20 21:39:37 +10001418
Eric Snow1abcf672017-05-23 21:46:51 -07001419 /* Copy the current interpreter config into the new interpreter */
Victor Stinner331a6a52019-05-27 16:39:22 +02001420 PyConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001421 if (save_tstate != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001422 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001423 } else {
1424 /* No current thread state, copy from the main interpreter */
1425 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinner331a6a52019-05-27 16:39:22 +02001426 config = &main_interp->config;
Victor Stinnerda273412017-12-15 01:46:02 +01001427 }
1428
Victor Stinner331a6a52019-05-27 16:39:22 +02001429 status = _PyConfig_Copy(&interp->config, config);
1430 if (_PyStatus_EXCEPTION(status)) {
1431 return status;
Victor Stinnerda273412017-12-15 01:46:02 +01001432 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001433 config = &interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001434
Victor Stinner331a6a52019-05-27 16:39:22 +02001435 status = _PyExc_Init();
1436 if (_PyStatus_EXCEPTION(status)) {
1437 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001438 }
1439
Victor Stinner331a6a52019-05-27 16:39:22 +02001440 status = _PyErr_Init();
1441 if (_PyStatus_EXCEPTION(status)) {
1442 return status;
Victor Stinneref9d9b62019-05-22 11:28:22 +02001443 }
1444
1445
Nick Coghland6009512014-11-20 21:39:37 +10001446 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001447 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001448 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001449 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001450 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001451 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001452
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001453 PyObject *sysmod = _PyImport_FindBuiltin(tstate, "sys");
Eric Snowd393c1b2017-09-14 12:18:12 -06001454 if (sysmod != NULL) {
1455 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinner43125222019-04-24 18:23:53 +02001456 if (interp->sysdict == NULL) {
Eric Snowd393c1b2017-09-14 12:18:12 -06001457 goto handle_error;
Victor Stinner43125222019-04-24 18:23:53 +02001458 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001459 Py_INCREF(interp->sysdict);
1460 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner838f2642019-06-13 22:41:23 +02001461 if (_PySys_InitMain(runtime, tstate) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001462 return _PyStatus_ERR("can't finish initializing sys");
Victor Stinnerab672812019-01-23 15:04:40 +01001463 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001464 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001465 else if (PyErr_Occurred()) {
1466 goto handle_error;
1467 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001468
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001469 PyObject *bimod = _PyImport_FindBuiltin(tstate, "builtins");
Nick Coghland6009512014-11-20 21:39:37 +10001470 if (bimod != NULL) {
1471 interp->builtins = PyModule_GetDict(bimod);
1472 if (interp->builtins == NULL)
1473 goto handle_error;
1474 Py_INCREF(interp->builtins);
1475 }
Serhiy Storchaka8905fcc2018-12-11 08:38:03 +02001476 else if (PyErr_Occurred()) {
1477 goto handle_error;
1478 }
Nick Coghland6009512014-11-20 21:39:37 +10001479
Nick Coghland6009512014-11-20 21:39:37 +10001480 if (bimod != NULL && sysmod != NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001481 status = _PyBuiltins_AddExceptions(bimod);
1482 if (_PyStatus_EXCEPTION(status)) {
1483 return status;
Victor Stinner6d43f6f2019-01-22 21:18:05 +01001484 }
Nick Coghland6009512014-11-20 21:39:37 +10001485
Victor Stinner331a6a52019-05-27 16:39:22 +02001486 status = _PySys_SetPreliminaryStderr(interp->sysdict);
1487 if (_PyStatus_EXCEPTION(status)) {
1488 return status;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001489 }
Nick Coghland6009512014-11-20 21:39:37 +10001490
Victor Stinner331a6a52019-05-27 16:39:22 +02001491 status = _PyImportHooks_Init();
1492 if (_PyStatus_EXCEPTION(status)) {
1493 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001494 }
Nick Coghland6009512014-11-20 21:39:37 +10001495
Victor Stinner331a6a52019-05-27 16:39:22 +02001496 status = init_importlib(interp, sysmod);
1497 if (_PyStatus_EXCEPTION(status)) {
1498 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001499 }
Nick Coghland6009512014-11-20 21:39:37 +10001500
Victor Stinner0a28f8d2019-06-19 02:54:39 +02001501 status = init_importlib_external(tstate);
Victor Stinner331a6a52019-05-27 16:39:22 +02001502 if (_PyStatus_EXCEPTION(status)) {
1503 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 }
Nick Coghland6009512014-11-20 21:39:37 +10001505
Victor Stinner331a6a52019-05-27 16:39:22 +02001506 status = _PyUnicode_InitEncodings(interp);
1507 if (_PyStatus_EXCEPTION(status)) {
1508 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001509 }
1510
Victor Stinner331a6a52019-05-27 16:39:22 +02001511 status = init_sys_streams(interp);
1512 if (_PyStatus_EXCEPTION(status)) {
1513 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514 }
1515
Victor Stinner331a6a52019-05-27 16:39:22 +02001516 status = add_main_module(interp);
1517 if (_PyStatus_EXCEPTION(status)) {
1518 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001519 }
1520
Victor Stinner331a6a52019-05-27 16:39:22 +02001521 if (config->site_import) {
1522 status = init_import_size();
1523 if (_PyStatus_EXCEPTION(status)) {
1524 return status;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525 }
1526 }
Nick Coghland6009512014-11-20 21:39:37 +10001527 }
1528
Victor Stinnera7368ac2017-11-15 18:11:45 -08001529 if (PyErr_Occurred()) {
1530 goto handle_error;
1531 }
Nick Coghland6009512014-11-20 21:39:37 +10001532
Victor Stinnera7368ac2017-11-15 18:11:45 -08001533 *tstate_p = tstate;
Victor Stinner331a6a52019-05-27 16:39:22 +02001534 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001535
Nick Coghland6009512014-11-20 21:39:37 +10001536handle_error:
1537 /* Oops, it didn't work. Undo it all. */
1538
1539 PyErr_PrintEx(0);
1540 PyThreadState_Clear(tstate);
1541 PyThreadState_Swap(save_tstate);
1542 PyThreadState_Delete(tstate);
1543 PyInterpreterState_Delete(interp);
1544
Victor Stinnera7368ac2017-11-15 18:11:45 -08001545 *tstate_p = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001546 return _PyStatus_OK();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001547}
1548
1549PyThreadState *
1550Py_NewInterpreter(void)
1551{
Stéphane Wirtel9e06d2b2019-03-18 17:10:29 +01001552 PyThreadState *tstate = NULL;
Victor Stinner331a6a52019-05-27 16:39:22 +02001553 PyStatus status = new_interpreter(&tstate);
1554 if (_PyStatus_EXCEPTION(status)) {
1555 Py_ExitStatusException(status);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001556 }
1557 return tstate;
1558
Nick Coghland6009512014-11-20 21:39:37 +10001559}
1560
1561/* Delete an interpreter and its last thread. This requires that the
1562 given thread state is current, that the thread has no remaining
1563 frames, and that it is its interpreter's only remaining thread.
1564 It is a fatal error to violate these constraints.
1565
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001566 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001567 everything, regardless.)
1568
1569 Locking: as above.
1570
1571*/
1572
1573void
1574Py_EndInterpreter(PyThreadState *tstate)
1575{
1576 PyInterpreterState *interp = tstate->interp;
1577
Victor Stinner50b48572018-11-01 01:51:40 +01001578 if (tstate != _PyThreadState_GET())
Nick Coghland6009512014-11-20 21:39:37 +10001579 Py_FatalError("Py_EndInterpreter: thread is not current");
1580 if (tstate->frame != NULL)
1581 Py_FatalError("Py_EndInterpreter: thread still has a frame");
Eric Snow5be45a62019-03-08 22:47:07 -07001582 interp->finalizing = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001583
Eric Snow842a2f02019-03-15 15:47:51 -06001584 // Wrap up existing "threading"-module-created, non-daemon threads.
Nick Coghland6009512014-11-20 21:39:37 +10001585 wait_for_thread_shutdown();
1586
Marcel Plch776407f2017-12-20 11:17:58 +01001587 call_py_exitfuncs(interp);
1588
Nick Coghland6009512014-11-20 21:39:37 +10001589 if (tstate != interp->tstate_head || tstate->next != NULL)
1590 Py_FatalError("Py_EndInterpreter: not the last thread");
1591
1592 PyImport_Cleanup();
1593 PyInterpreterState_Clear(interp);
1594 PyThreadState_Swap(NULL);
1595 PyInterpreterState_Delete(interp);
1596}
1597
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001598/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001599
Victor Stinner331a6a52019-05-27 16:39:22 +02001600static PyStatus
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001601add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001602{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001603 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001604 m = PyImport_AddModule("__main__");
1605 if (m == NULL)
Victor Stinner331a6a52019-05-27 16:39:22 +02001606 return _PyStatus_ERR("can't create __main__ module");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001607
Nick Coghland6009512014-11-20 21:39:37 +10001608 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001609 ann_dict = PyDict_New();
1610 if ((ann_dict == NULL) ||
1611 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001612 return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001613 }
1614 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001615
Nick Coghland6009512014-11-20 21:39:37 +10001616 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1617 PyObject *bimod = PyImport_ImportModule("builtins");
1618 if (bimod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001619 return _PyStatus_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001620 }
1621 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001622 return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001623 }
1624 Py_DECREF(bimod);
1625 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626
Nick Coghland6009512014-11-20 21:39:37 +10001627 /* Main is a little special - imp.is_builtin("__main__") will return
1628 * False, but BuiltinImporter is still the most appropriate initial
1629 * setting for its __loader__ attribute. A more suitable value will
1630 * be set if __main__ gets further initialized later in the startup
1631 * process.
1632 */
1633 loader = PyDict_GetItemString(d, "__loader__");
1634 if (loader == NULL || loader == Py_None) {
1635 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1636 "BuiltinImporter");
1637 if (loader == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001638 return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001639 }
1640 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001641 return _PyStatus_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001642 }
1643 Py_DECREF(loader);
1644 }
Victor Stinner331a6a52019-05-27 16:39:22 +02001645 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001646}
1647
Nick Coghland6009512014-11-20 21:39:37 +10001648/* Import the site module (not into __main__ though) */
1649
Victor Stinner331a6a52019-05-27 16:39:22 +02001650static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -04001651init_import_size(void)
Nick Coghland6009512014-11-20 21:39:37 +10001652{
1653 PyObject *m;
1654 m = PyImport_ImportModule("site");
1655 if (m == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001656 return _PyStatus_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001657 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001658 Py_DECREF(m);
Victor Stinner331a6a52019-05-27 16:39:22 +02001659 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001660}
1661
Victor Stinner874dbe82015-09-04 17:29:57 +02001662/* Check if a file descriptor is valid or not.
1663 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1664static int
1665is_valid_fd(int fd)
1666{
Victor Stinner3092d6b2019-04-17 18:09:12 +02001667/* dup() is faster than fstat(): fstat() can require input/output operations,
1668 whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1669 startup. Problem: dup() doesn't check if the file descriptor is valid on
1670 some platforms.
1671
1672 bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1673 side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1674 EBADF. FreeBSD has similar issue (bpo-32849).
1675
1676 Only use dup() on platforms where dup() is enough to detect invalid FD in
1677 corner cases: on Linux and Windows (bpo-32849). */
1678#if defined(__linux__) || defined(MS_WINDOWS)
1679 if (fd < 0) {
1680 return 0;
1681 }
1682 int fd2;
1683
1684 _Py_BEGIN_SUPPRESS_IPH
1685 fd2 = dup(fd);
1686 if (fd2 >= 0) {
1687 close(fd2);
1688 }
1689 _Py_END_SUPPRESS_IPH
1690
1691 return (fd2 >= 0);
1692#else
Victor Stinner1c4670e2017-05-04 00:45:56 +02001693 struct stat st;
1694 return (fstat(fd, &st) == 0);
Victor Stinner1c4670e2017-05-04 00:45:56 +02001695#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001696}
1697
1698/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001699static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02001700create_stdio(const PyConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001701 int fd, int write_mode, const char* name,
Victor Stinner709d23d2019-05-02 14:56:30 -04001702 const wchar_t* encoding, const wchar_t* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001703{
1704 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1705 const char* mode;
1706 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001707 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001708 int buffering, isatty;
1709 _Py_IDENTIFIER(open);
1710 _Py_IDENTIFIER(isatty);
1711 _Py_IDENTIFIER(TextIOWrapper);
1712 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001713 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001714
Victor Stinner874dbe82015-09-04 17:29:57 +02001715 if (!is_valid_fd(fd))
1716 Py_RETURN_NONE;
1717
Nick Coghland6009512014-11-20 21:39:37 +10001718 /* stdin is always opened in buffered mode, first because it shouldn't
1719 make a difference in common use cases, second because TextIOWrapper
1720 depends on the presence of a read1() method which only exists on
1721 buffered streams.
1722 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001723 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001724 buffering = 0;
1725 else
1726 buffering = -1;
1727 if (write_mode)
1728 mode = "wb";
1729 else
1730 mode = "rb";
1731 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1732 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001733 Py_None, Py_None, /* encoding, errors */
1734 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001735 if (buf == NULL)
1736 goto error;
1737
1738 if (buffering) {
1739 _Py_IDENTIFIER(raw);
1740 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1741 if (raw == NULL)
1742 goto error;
1743 }
1744 else {
1745 raw = buf;
1746 Py_INCREF(raw);
1747 }
1748
Steve Dower39294992016-08-30 21:22:36 -07001749#ifdef MS_WINDOWS
1750 /* Windows console IO is always UTF-8 encoded */
1751 if (PyWindowsConsoleIO_Check(raw))
Victor Stinner709d23d2019-05-02 14:56:30 -04001752 encoding = L"utf-8";
Steve Dower39294992016-08-30 21:22:36 -07001753#endif
1754
Nick Coghland6009512014-11-20 21:39:37 +10001755 text = PyUnicode_FromString(name);
1756 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1757 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001758 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001759 if (res == NULL)
1760 goto error;
1761 isatty = PyObject_IsTrue(res);
1762 Py_DECREF(res);
1763 if (isatty == -1)
1764 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001765 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001766 write_through = Py_True;
1767 else
1768 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001769 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001770 line_buffering = Py_True;
1771 else
1772 line_buffering = Py_False;
1773
1774 Py_CLEAR(raw);
1775 Py_CLEAR(text);
1776
1777#ifdef MS_WINDOWS
1778 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1779 newlines to "\n".
1780 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1781 newline = NULL;
1782#else
1783 /* sys.stdin: split lines at "\n".
1784 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1785 newline = "\n";
1786#endif
1787
Victor Stinner709d23d2019-05-02 14:56:30 -04001788 PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1789 if (encoding_str == NULL) {
1790 Py_CLEAR(buf);
1791 goto error;
1792 }
1793
1794 PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1795 if (errors_str == NULL) {
1796 Py_CLEAR(buf);
1797 Py_CLEAR(encoding_str);
1798 goto error;
1799 }
1800
1801 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1802 buf, encoding_str, errors_str,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001803 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001804 Py_CLEAR(buf);
Victor Stinner709d23d2019-05-02 14:56:30 -04001805 Py_CLEAR(encoding_str);
1806 Py_CLEAR(errors_str);
Nick Coghland6009512014-11-20 21:39:37 +10001807 if (stream == NULL)
1808 goto error;
1809
1810 if (write_mode)
1811 mode = "w";
1812 else
1813 mode = "r";
1814 text = PyUnicode_FromString(mode);
1815 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1816 goto error;
1817 Py_CLEAR(text);
1818 return stream;
1819
1820error:
1821 Py_XDECREF(buf);
1822 Py_XDECREF(stream);
1823 Py_XDECREF(text);
1824 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001825
Victor Stinner874dbe82015-09-04 17:29:57 +02001826 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1827 /* Issue #24891: the file descriptor was closed after the first
1828 is_valid_fd() check was called. Ignore the OSError and set the
1829 stream to None. */
1830 PyErr_Clear();
1831 Py_RETURN_NONE;
1832 }
1833 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001834}
1835
1836/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinner331a6a52019-05-27 16:39:22 +02001837static PyStatus
Victor Stinner91106cd2017-12-13 12:29:09 +01001838init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001839{
1840 PyObject *iomod = NULL, *wrapper;
1841 PyObject *bimod = NULL;
1842 PyObject *m;
1843 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001844 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001845 PyObject * encoding_attr;
Victor Stinner331a6a52019-05-27 16:39:22 +02001846 PyStatus res = _PyStatus_OK();
1847 PyConfig *config = &interp->config;
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001848
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001849 /* Check that stdin is not a directory
1850 Using shell redirection, you can redirect stdin to a directory,
1851 crashing the Python interpreter. Catch this common mistake here
1852 and output a useful error message. Note that under MS Windows,
1853 the shell already prevents that. */
1854#ifndef MS_WINDOWS
1855 struct _Py_stat_struct sb;
1856 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1857 S_ISDIR(sb.st_mode)) {
Victor Stinner331a6a52019-05-27 16:39:22 +02001858 return _PyStatus_ERR("<stdin> is a directory, cannot continue");
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001859 }
1860#endif
1861
Nick Coghland6009512014-11-20 21:39:37 +10001862 /* Hack to avoid a nasty recursion issue when Python is invoked
1863 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1864 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1865 goto error;
1866 }
1867 Py_DECREF(m);
1868
1869 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1870 goto error;
1871 }
1872 Py_DECREF(m);
1873
1874 if (!(bimod = PyImport_ImportModule("builtins"))) {
1875 goto error;
1876 }
1877
1878 if (!(iomod = PyImport_ImportModule("io"))) {
1879 goto error;
1880 }
1881 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1882 goto error;
1883 }
1884
1885 /* Set builtins.open */
1886 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1887 Py_DECREF(wrapper);
1888 goto error;
1889 }
1890 Py_DECREF(wrapper);
1891
Nick Coghland6009512014-11-20 21:39:37 +10001892 /* Set sys.stdin */
1893 fd = fileno(stdin);
1894 /* Under some conditions stdin, stdout and stderr may not be connected
1895 * and fileno() may point to an invalid file descriptor. For example
1896 * GUI apps don't have valid standard streams by default.
1897 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001898 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001899 config->stdio_encoding,
1900 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001901 if (std == NULL)
1902 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001903 PySys_SetObject("__stdin__", std);
1904 _PySys_SetObjectId(&PyId_stdin, std);
1905 Py_DECREF(std);
1906
1907 /* Set sys.stdout */
1908 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001909 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001910 config->stdio_encoding,
1911 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001912 if (std == NULL)
1913 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001914 PySys_SetObject("__stdout__", std);
1915 _PySys_SetObjectId(&PyId_stdout, std);
1916 Py_DECREF(std);
1917
1918#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1919 /* Set sys.stderr, replaces the preliminary stderr */
1920 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001921 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001922 config->stdio_encoding,
Victor Stinner709d23d2019-05-02 14:56:30 -04001923 L"backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001924 if (std == NULL)
1925 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001926
1927 /* Same as hack above, pre-import stderr's codec to avoid recursion
1928 when import.c tries to write to stderr in verbose mode. */
1929 encoding_attr = PyObject_GetAttrString(std, "encoding");
1930 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001931 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001932 if (std_encoding != NULL) {
1933 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1934 Py_XDECREF(codec_info);
1935 }
1936 Py_DECREF(encoding_attr);
1937 }
1938 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1939
1940 if (PySys_SetObject("__stderr__", std) < 0) {
1941 Py_DECREF(std);
1942 goto error;
1943 }
1944 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1945 Py_DECREF(std);
1946 goto error;
1947 }
1948 Py_DECREF(std);
1949#endif
1950
Victor Stinnera7368ac2017-11-15 18:11:45 -08001951 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001952
Victor Stinnera7368ac2017-11-15 18:11:45 -08001953error:
Victor Stinner331a6a52019-05-27 16:39:22 +02001954 res = _PyStatus_ERR("can't initialize sys standard streams");
Victor Stinnera7368ac2017-11-15 18:11:45 -08001955
1956done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001957 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001958
Nick Coghland6009512014-11-20 21:39:37 +10001959 Py_XDECREF(bimod);
1960 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001961 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001962}
1963
1964
Victor Stinner10dc4842015-03-24 12:01:30 +01001965static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001966_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001967{
Victor Stinner10dc4842015-03-24 12:01:30 +01001968 fputc('\n', stderr);
1969 fflush(stderr);
1970
1971 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001972 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001973}
Victor Stinner791da1c2016-03-14 16:53:12 +01001974
1975/* Print the current exception (if an exception is set) with its traceback,
1976 or display the current Python stack.
1977
1978 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1979 called on catastrophic cases.
1980
1981 Return 1 if the traceback was displayed, 0 otherwise. */
1982
1983static int
1984_Py_FatalError_PrintExc(int fd)
1985{
1986 PyObject *ferr, *res;
1987 PyObject *exception, *v, *tb;
1988 int has_tb;
1989
Victor Stinner791da1c2016-03-14 16:53:12 +01001990 PyErr_Fetch(&exception, &v, &tb);
1991 if (exception == NULL) {
1992 /* No current exception */
1993 return 0;
1994 }
1995
1996 ferr = _PySys_GetObjectId(&PyId_stderr);
1997 if (ferr == NULL || ferr == Py_None) {
1998 /* sys.stderr is not set yet or set to None,
1999 no need to try to display the exception */
2000 return 0;
2001 }
2002
2003 PyErr_NormalizeException(&exception, &v, &tb);
2004 if (tb == NULL) {
2005 tb = Py_None;
2006 Py_INCREF(tb);
2007 }
2008 PyException_SetTraceback(v, tb);
2009 if (exception == NULL) {
2010 /* PyErr_NormalizeException() failed */
2011 return 0;
2012 }
2013
2014 has_tb = (tb != Py_None);
2015 PyErr_Display(exception, v, tb);
2016 Py_XDECREF(exception);
2017 Py_XDECREF(v);
2018 Py_XDECREF(tb);
2019
2020 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002021 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002022 if (res == NULL)
2023 PyErr_Clear();
2024 else
2025 Py_DECREF(res);
2026
2027 return has_tb;
2028}
2029
Nick Coghland6009512014-11-20 21:39:37 +10002030/* Print fatal error message and abort */
2031
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002032#ifdef MS_WINDOWS
2033static void
2034fatal_output_debug(const char *msg)
2035{
2036 /* buffer of 256 bytes allocated on the stack */
2037 WCHAR buffer[256 / sizeof(WCHAR)];
2038 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2039 size_t msglen;
2040
2041 OutputDebugStringW(L"Fatal Python error: ");
2042
2043 msglen = strlen(msg);
2044 while (msglen) {
2045 size_t i;
2046
2047 if (buflen > msglen) {
2048 buflen = msglen;
2049 }
2050
2051 /* Convert the message to wchar_t. This uses a simple one-to-one
2052 conversion, assuming that the this error message actually uses
2053 ASCII only. If this ceases to be true, we will have to convert. */
2054 for (i=0; i < buflen; ++i) {
2055 buffer[i] = msg[i];
2056 }
2057 buffer[i] = L'\0';
2058 OutputDebugStringW(buffer);
2059
2060 msg += buflen;
2061 msglen -= buflen;
2062 }
2063 OutputDebugStringW(L"\n");
2064}
2065#endif
2066
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002067static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002068fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002069{
2070 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002071 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002072
2073 if (reentrant) {
2074 /* Py_FatalError() caused a second fatal error.
2075 Example: flush_std_files() raises a recursion error. */
2076 goto exit;
2077 }
2078 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002079
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002080 fprintf(stderr, "Fatal Python error: ");
2081 if (prefix) {
2082 fputs(prefix, stderr);
2083 fputs(": ", stderr);
2084 }
2085 if (msg) {
2086 fputs(msg, stderr);
2087 }
2088 else {
2089 fprintf(stderr, "<message not set>");
2090 }
2091 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002092 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002093
Victor Stinner3a228ab2018-11-01 00:26:41 +01002094 /* Check if the current thread has a Python thread state
2095 and holds the GIL */
2096 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2097 if (tss_tstate != NULL) {
Victor Stinner50b48572018-11-01 01:51:40 +01002098 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3a228ab2018-11-01 00:26:41 +01002099 if (tss_tstate != tstate) {
2100 /* The Python thread does not hold the GIL */
2101 tss_tstate = NULL;
2102 }
2103 }
2104 else {
2105 /* Py_FatalError() has been called from a C thread
2106 which has no Python thread state. */
2107 }
2108 int has_tstate_and_gil = (tss_tstate != NULL);
2109
2110 if (has_tstate_and_gil) {
2111 /* If an exception is set, print the exception with its traceback */
2112 if (!_Py_FatalError_PrintExc(fd)) {
2113 /* No exception is set, or an exception is set without traceback */
2114 _Py_FatalError_DumpTracebacks(fd);
2115 }
2116 }
2117 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01002118 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002119 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002120
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002121 /* The main purpose of faulthandler is to display the traceback.
2122 This function already did its best to display a traceback.
2123 Disable faulthandler to prevent writing a second traceback
2124 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002125 _PyFaulthandler_Fini();
2126
Victor Stinner791da1c2016-03-14 16:53:12 +01002127 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01002128 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002129 /* Flush sys.stdout and sys.stderr */
2130 flush_std_files();
2131 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002132
Nick Coghland6009512014-11-20 21:39:37 +10002133#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002134 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002135#endif /* MS_WINDOWS */
2136
2137exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002138 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002139#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002140 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002141#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002142 abort();
2143 }
2144 else {
2145 exit(status);
2146 }
2147}
2148
Victor Stinner19760862017-12-20 01:41:59 +01002149void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002150Py_FatalError(const char *msg)
2151{
2152 fatal_error(NULL, msg, -1);
2153}
2154
Victor Stinner19760862017-12-20 01:41:59 +01002155void _Py_NO_RETURN
Victor Stinner331a6a52019-05-27 16:39:22 +02002156Py_ExitStatusException(PyStatus status)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002157{
Victor Stinner331a6a52019-05-27 16:39:22 +02002158 if (_PyStatus_IS_EXIT(status)) {
2159 exit(status.exitcode);
Victor Stinnerdbacfc22019-05-16 16:39:26 +02002160 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002161 else if (_PyStatus_IS_ERROR(status)) {
2162 fatal_error(status.func, status.err_msg, 1);
Victor Stinnerdfe88472019-03-01 12:14:41 +01002163 }
2164 else {
Victor Stinner331a6a52019-05-27 16:39:22 +02002165 Py_FatalError("Py_ExitStatusException() must not be called on success");
Victor Stinnerdfe88472019-03-01 12:14:41 +01002166 }
Nick Coghland6009512014-11-20 21:39:37 +10002167}
2168
2169/* Clean up and exit */
2170
Victor Stinnerd7292b52016-06-17 12:29:00 +02002171# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002172
Nick Coghland6009512014-11-20 21:39:37 +10002173/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002174void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002175{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002176 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002177
Antoine Pitroufc5db952017-12-13 02:29:07 +01002178 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002179 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2180
2181 is->pyexitfunc = func;
2182 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002183}
2184
2185static void
Marcel Plch776407f2017-12-20 11:17:58 +01002186call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002187{
Marcel Plch776407f2017-12-20 11:17:58 +01002188 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002189 return;
2190
Marcel Plch776407f2017-12-20 11:17:58 +01002191 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002192 PyErr_Clear();
2193}
2194
2195/* Wait until threading._shutdown completes, provided
2196 the threading module was imported in the first place.
2197 The shutdown routine will wait until all non-daemon
2198 "threading" threads have completed. */
2199static void
2200wait_for_thread_shutdown(void)
2201{
Nick Coghland6009512014-11-20 21:39:37 +10002202 _Py_IDENTIFIER(_shutdown);
2203 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002204 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002205 if (threading == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +01002206 if (PyErr_Occurred()) {
2207 PyErr_WriteUnraisable(NULL);
2208 }
2209 /* else: threading not imported */
Nick Coghland6009512014-11-20 21:39:37 +10002210 return;
2211 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002212 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002213 if (result == NULL) {
2214 PyErr_WriteUnraisable(threading);
2215 }
2216 else {
2217 Py_DECREF(result);
2218 }
2219 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002220}
2221
2222#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002223int Py_AtExit(void (*func)(void))
2224{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002225 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002226 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002227 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002228 return 0;
2229}
2230
2231static void
Victor Stinner8e91c242019-04-24 17:24:01 +02002232call_ll_exitfuncs(_PyRuntimeState *runtime)
Nick Coghland6009512014-11-20 21:39:37 +10002233{
Victor Stinner8e91c242019-04-24 17:24:01 +02002234 while (runtime->nexitfuncs > 0) {
Victor Stinner87d23a02019-04-26 05:49:26 +02002235 /* pop last function from the list */
2236 runtime->nexitfuncs--;
2237 void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2238 runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2239
2240 exitfunc();
Victor Stinner8e91c242019-04-24 17:24:01 +02002241 }
Nick Coghland6009512014-11-20 21:39:37 +10002242
2243 fflush(stdout);
2244 fflush(stderr);
2245}
2246
Victor Stinnercfc88312018-08-01 16:41:25 +02002247void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002248Py_Exit(int sts)
2249{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002250 if (Py_FinalizeEx() < 0) {
2251 sts = 120;
2252 }
Nick Coghland6009512014-11-20 21:39:37 +10002253
2254 exit(sts);
2255}
2256
Victor Stinner331a6a52019-05-27 16:39:22 +02002257static PyStatus
Victor Stinner43fc3bb2019-05-02 11:54:20 -04002258init_signals(void)
Nick Coghland6009512014-11-20 21:39:37 +10002259{
2260#ifdef SIGPIPE
2261 PyOS_setsig(SIGPIPE, SIG_IGN);
2262#endif
2263#ifdef SIGXFZ
2264 PyOS_setsig(SIGXFZ, SIG_IGN);
2265#endif
2266#ifdef SIGXFSZ
2267 PyOS_setsig(SIGXFSZ, SIG_IGN);
2268#endif
2269 PyOS_InitInterrupts(); /* May imply initsignal() */
2270 if (PyErr_Occurred()) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002271 return _PyStatus_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002272 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002273 return _PyStatus_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002274}
2275
2276
2277/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2278 *
2279 * All of the code in this function must only use async-signal-safe functions,
2280 * listed at `man 7 signal` or
2281 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2282 */
2283void
2284_Py_RestoreSignals(void)
2285{
2286#ifdef SIGPIPE
2287 PyOS_setsig(SIGPIPE, SIG_DFL);
2288#endif
2289#ifdef SIGXFZ
2290 PyOS_setsig(SIGXFZ, SIG_DFL);
2291#endif
2292#ifdef SIGXFSZ
2293 PyOS_setsig(SIGXFSZ, SIG_DFL);
2294#endif
2295}
2296
2297
2298/*
2299 * The file descriptor fd is considered ``interactive'' if either
2300 * a) isatty(fd) is TRUE, or
2301 * b) the -i flag was given, and the filename associated with
2302 * the descriptor is NULL or "<stdin>" or "???".
2303 */
2304int
2305Py_FdIsInteractive(FILE *fp, const char *filename)
2306{
2307 if (isatty((int)fileno(fp)))
2308 return 1;
2309 if (!Py_InteractiveFlag)
2310 return 0;
2311 return (filename == NULL) ||
2312 (strcmp(filename, "<stdin>") == 0) ||
2313 (strcmp(filename, "???") == 0);
2314}
2315
2316
Nick Coghland6009512014-11-20 21:39:37 +10002317/* Wrappers around sigaction() or signal(). */
2318
2319PyOS_sighandler_t
2320PyOS_getsig(int sig)
2321{
2322#ifdef HAVE_SIGACTION
2323 struct sigaction context;
2324 if (sigaction(sig, NULL, &context) == -1)
2325 return SIG_ERR;
2326 return context.sa_handler;
2327#else
2328 PyOS_sighandler_t handler;
2329/* Special signal handling for the secure CRT in Visual Studio 2005 */
2330#if defined(_MSC_VER) && _MSC_VER >= 1400
2331 switch (sig) {
2332 /* Only these signals are valid */
2333 case SIGINT:
2334 case SIGILL:
2335 case SIGFPE:
2336 case SIGSEGV:
2337 case SIGTERM:
2338 case SIGBREAK:
2339 case SIGABRT:
2340 break;
2341 /* Don't call signal() with other values or it will assert */
2342 default:
2343 return SIG_ERR;
2344 }
2345#endif /* _MSC_VER && _MSC_VER >= 1400 */
2346 handler = signal(sig, SIG_IGN);
2347 if (handler != SIG_ERR)
2348 signal(sig, handler);
2349 return handler;
2350#endif
2351}
2352
2353/*
2354 * All of the code in this function must only use async-signal-safe functions,
2355 * listed at `man 7 signal` or
2356 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2357 */
2358PyOS_sighandler_t
2359PyOS_setsig(int sig, PyOS_sighandler_t handler)
2360{
2361#ifdef HAVE_SIGACTION
2362 /* Some code in Modules/signalmodule.c depends on sigaction() being
2363 * used here if HAVE_SIGACTION is defined. Fix that if this code
2364 * changes to invalidate that assumption.
2365 */
2366 struct sigaction context, ocontext;
2367 context.sa_handler = handler;
2368 sigemptyset(&context.sa_mask);
2369 context.sa_flags = 0;
2370 if (sigaction(sig, &context, &ocontext) == -1)
2371 return SIG_ERR;
2372 return ocontext.sa_handler;
2373#else
2374 PyOS_sighandler_t oldhandler;
2375 oldhandler = signal(sig, handler);
2376#ifdef HAVE_SIGINTERRUPT
2377 siginterrupt(sig, 1);
2378#endif
2379 return oldhandler;
2380#endif
2381}
2382
2383#ifdef __cplusplus
2384}
2385#endif