blob: fab96fd5238180852fe2d662f978faa941baf976 [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"
6#undef Yield /* undefine macro conflicting with winbase.h */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Victor Stinner2be00d92018-10-31 20:19:24 +01009#include "internal/mem.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060010#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100011#include "grammar.h"
12#include "node.h"
13#include "token.h"
14#include "parsetok.h"
15#include "errcode.h"
16#include "code.h"
17#include "symtable.h"
18#include "ast.h"
19#include "marshal.h"
20#include "osdefs.h"
21#include <locale.h>
22
23#ifdef HAVE_SIGNAL_H
24#include <signal.h>
25#endif
26
27#ifdef MS_WINDOWS
28#include "malloc.h" /* for alloca */
29#endif
30
31#ifdef HAVE_LANGINFO_H
32#include <langinfo.h>
33#endif
34
35#ifdef MS_WINDOWS
36#undef BYTE
37#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070038
39extern PyTypeObject PyWindowsConsoleIO_Type;
40#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100041#endif
42
43_Py_IDENTIFIER(flush);
44_Py_IDENTIFIER(name);
45_Py_IDENTIFIER(stdin);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060048_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100049
50#ifdef __cplusplus
51extern "C" {
52#endif
53
Nick Coghland6009512014-11-20 21:39:37 +100054extern grammar _PyParser_Grammar; /* From graminit.c */
55
56/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080057static _PyInitError add_main_module(PyInterpreterState *interp);
58static _PyInitError initfsencoding(PyInterpreterState *interp);
59static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010060static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010062static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100063static void wait_for_thread_shutdown(void);
64static void call_ll_exitfuncs(void);
65extern int _PyUnicode_Init(void);
66extern int _PyStructSequence_Init(void);
67extern void _PyUnicode_Fini(void);
68extern int _PyLong_Init(void);
69extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080070extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100071extern void _PyFaulthandler_Fini(void);
72extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080073extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100074extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070075extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100076
Nick Coghland6009512014-11-20 21:39:37 +100077extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
78extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100079
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081
Victor Stinnerf7e5b562017-11-15 15:48:08 -080082_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083_PyRuntime_Initialize(void)
84{
85 /* XXX We only initialize once in the process, which aligns with
86 the static initialization of the former globals now found in
87 _PyRuntime. However, _PyRuntime *should* be initialized with
88 every Py_Initialize() call, but doing so breaks the runtime.
89 This is because the runtime state is not properly finalized
90 currently. */
91 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080092 if (initialized) {
93 return _Py_INIT_OK();
94 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080096
97 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060098}
99
100void
101_PyRuntime_Finalize(void)
102{
103 _PyRuntimeState_Fini(&_PyRuntime);
104}
105
106int
107_Py_IsFinalizing(void)
108{
109 return _PyRuntime.finalizing != NULL;
110}
111
Nick Coghland6009512014-11-20 21:39:37 +1000112/* Hack to force loading of object files */
113int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
114 PyOS_mystrnicmp; /* Python/pystrcmp.o */
115
116/* PyModule_GetWarningsModule is no longer necessary as of 2.6
117since _warnings is builtin. This API should not be used. */
118PyObject *
119PyModule_GetWarningsModule(void)
120{
121 return PyImport_ImportModule("warnings");
122}
123
Eric Snowc7ec9982017-05-23 23:00:52 -0700124
Eric Snow1abcf672017-05-23 21:46:51 -0700125/* APIs to access the initialization flags
126 *
127 * Can be called prior to Py_Initialize.
128 */
Nick Coghland6009512014-11-20 21:39:37 +1000129
Eric Snow1abcf672017-05-23 21:46:51 -0700130int
131_Py_IsCoreInitialized(void)
132{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600133 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700134}
Nick Coghland6009512014-11-20 21:39:37 +1000135
136int
137Py_IsInitialized(void)
138{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600139 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000140}
141
Nick Coghlan6ea41862017-06-11 13:16:15 +1000142
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000143/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
144 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000145 initializations fail, a fatal error is issued and the function does
146 not return. On return, the first thread and interpreter state have
147 been created.
148
149 Locking: you must hold the interpreter lock while calling this.
150 (If the lock has not yet been initialized, that's equivalent to
151 having the lock, but you cannot use multiple threads.)
152
153*/
154
Nick Coghland6009512014-11-20 21:39:37 +1000155static char*
156get_codec_name(const char *encoding)
157{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200158 const char *name_utf8;
159 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000160 PyObject *codec, *name = NULL;
161
162 codec = _PyCodec_Lookup(encoding);
163 if (!codec)
164 goto error;
165
166 name = _PyObject_GetAttrId(codec, &PyId_name);
167 Py_CLEAR(codec);
168 if (!name)
169 goto error;
170
Serhiy Storchaka06515832016-11-20 09:13:07 +0200171 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000172 if (name_utf8 == NULL)
173 goto error;
174 name_str = _PyMem_RawStrdup(name_utf8);
175 Py_DECREF(name);
176 if (name_str == NULL) {
177 PyErr_NoMemory();
178 return NULL;
179 }
180 return name_str;
181
182error:
183 Py_XDECREF(codec);
184 Py_XDECREF(name);
185 return NULL;
186}
187
Nick Coghland6009512014-11-20 21:39:37 +1000188
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800189static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700190initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000191{
192 PyObject *importlib;
193 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000194 PyObject *value;
195
196 /* Import _importlib through its frozen version, _frozen_importlib. */
197 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800198 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000199 }
200 else if (Py_VerboseFlag) {
201 PySys_FormatStderr("import _frozen_importlib # frozen\n");
202 }
203 importlib = PyImport_AddModule("_frozen_importlib");
204 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800205 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000206 }
207 interp->importlib = importlib;
208 Py_INCREF(interp->importlib);
209
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300210 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
211 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800212 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300213 Py_INCREF(interp->import_func);
214
Victor Stinnercd6e6942015-09-18 09:11:57 +0200215 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800216 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000217 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800218 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000219 }
220 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200221 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000222 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600223 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800224 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000225 }
226
Victor Stinnercd6e6942015-09-18 09:11:57 +0200227 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000228 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
229 if (value == NULL) {
230 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800231 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000232 }
233 Py_DECREF(value);
234 Py_DECREF(impmod);
235
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800236 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000237}
238
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800239static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700240initexternalimport(PyInterpreterState *interp)
241{
242 PyObject *value;
243 value = PyObject_CallMethod(interp->importlib,
244 "_install_external_importers", "");
245 if (value == NULL) {
246 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800247 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700248 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200249 Py_DECREF(value);
Serhiy Storchaka79d1c2e2018-09-18 22:22:29 +0300250 return _PyImportZip_Init();
Eric Snow1abcf672017-05-23 21:46:51 -0700251}
Nick Coghland6009512014-11-20 21:39:37 +1000252
Nick Coghlan6ea41862017-06-11 13:16:15 +1000253/* Helper functions to better handle the legacy C locale
254 *
255 * The legacy C locale assumes ASCII as the default text encoding, which
256 * causes problems not only for the CPython runtime, but also other
257 * components like GNU readline.
258 *
259 * Accordingly, when the CLI detects it, it attempts to coerce it to a
260 * more capable UTF-8 based alternative as follows:
261 *
262 * if (_Py_LegacyLocaleDetected()) {
263 * _Py_CoerceLegacyLocale();
264 * }
265 *
266 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
267 *
268 * Locale coercion also impacts the default error handler for the standard
269 * streams: while the usual default is "strict", the default for the legacy
270 * C locale and for any of the coercion target locales is "surrogateescape".
271 */
272
273int
274_Py_LegacyLocaleDetected(void)
275{
276#ifndef MS_WINDOWS
277 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000278 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
279 * the POSIX locale as a simple alias for the C locale, so
280 * we may also want to check for that explicitly.
281 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000282 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
283 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
284#else
285 /* Windows uses code pages instead of locales, so no locale is legacy */
286 return 0;
287#endif
288}
289
Nick Coghlaneb817952017-06-18 12:29:42 +1000290static const char *_C_LOCALE_WARNING =
291 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
292 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
293 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
294 "locales is recommended.\n";
295
Nick Coghlaneb817952017-06-18 12:29:42 +1000296static void
Victor Stinner94540602017-12-16 04:54:22 +0100297_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000298{
Victor Stinner06e76082018-09-19 14:56:36 -0700299 if (core_config->coerce_c_locale_warn && _Py_LegacyLocaleDetected()) {
Victor Stinnercf215042018-08-29 22:56:06 +0200300 PySys_FormatStderr("%s", _C_LOCALE_WARNING);
Nick Coghlaneb817952017-06-18 12:29:42 +1000301 }
302}
303
Nick Coghlan6ea41862017-06-11 13:16:15 +1000304typedef struct _CandidateLocale {
305 const char *locale_name; /* The locale to try as a coercion target */
306} _LocaleCoercionTarget;
307
308static _LocaleCoercionTarget _TARGET_LOCALES[] = {
309 {"C.UTF-8"},
310 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000311 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000312 {NULL}
313};
314
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200315
316int
317_Py_IsLocaleCoercionTarget(const char *ctype_loc)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000318{
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200319 const _LocaleCoercionTarget *target = NULL;
320 for (target = _TARGET_LOCALES; target->locale_name; target++) {
321 if (strcmp(ctype_loc, target->locale_name) == 0) {
322 return 1;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000323 }
Victor Stinner124b9eb2018-08-29 01:29:06 +0200324 }
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200325 return 0;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000326}
327
Victor Stinnerdfe0dc72018-08-29 11:47:29 +0200328
Nick Coghlan6ea41862017-06-11 13:16:15 +1000329#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100330static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000331 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
332 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
333
334static void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200335_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000336{
337 const char *newloc = target->locale_name;
338
339 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100340 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000341
342 /* Set the relevant locale environment variable */
343 if (setenv("LC_CTYPE", newloc, 1)) {
344 fprintf(stderr,
345 "Error setting LC_CTYPE, skipping C locale coercion\n");
346 return;
347 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200348 if (warn) {
Victor Stinner94540602017-12-16 04:54:22 +0100349 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000350 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351
352 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100353 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000354}
355#endif
356
357void
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200358_Py_CoerceLegacyLocale(int warn)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000359{
360#ifdef PY_COERCE_C_LOCALE
Victor Stinner8ea09112018-09-03 17:05:18 +0200361 char *oldloc = NULL;
362
363 oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
364 if (oldloc == NULL) {
365 return;
366 }
367
Victor Stinner94540602017-12-16 04:54:22 +0100368 const char *locale_override = getenv("LC_ALL");
369 if (locale_override == NULL || *locale_override == '\0') {
370 /* LC_ALL is also not set (or is set to an empty string) */
371 const _LocaleCoercionTarget *target = NULL;
372 for (target = _TARGET_LOCALES; target->locale_name; target++) {
373 const char *new_locale = setlocale(LC_CTYPE,
374 target->locale_name);
375 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100376#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100377defined(HAVE_LANGINFO_H) && defined(CODESET)
378 /* Also ensure that nl_langinfo works in this locale */
379 char *codeset = nl_langinfo(CODESET);
380 if (!codeset || *codeset == '\0') {
381 /* CODESET is not set or empty, so skip coercion */
382 new_locale = NULL;
383 _Py_SetLocaleFromEnv(LC_CTYPE);
384 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000385 }
Victor Stinner94540602017-12-16 04:54:22 +0100386#endif
387 /* Successfully configured locale, so make it the default */
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200388 _coerce_default_locale_settings(warn, target);
Victor Stinner8ea09112018-09-03 17:05:18 +0200389 goto done;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000390 }
391 }
392 }
393 /* No C locale warning here, as Py_Initialize will emit one later */
Victor Stinner8ea09112018-09-03 17:05:18 +0200394
395 setlocale(LC_CTYPE, oldloc);
396
397done:
398 PyMem_RawFree(oldloc);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000399#endif
400}
401
xdegaye1588be62017-11-12 12:45:59 +0100402/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
403 * isolate the idiosyncrasies of different libc implementations. It reads the
404 * appropriate environment variable and uses its value to select the locale for
405 * 'category'. */
406char *
407_Py_SetLocaleFromEnv(int category)
408{
409#ifdef __ANDROID__
410 const char *locale;
411 const char **pvar;
412#ifdef PY_COERCE_C_LOCALE
413 const char *coerce_c_locale;
414#endif
415 const char *utf8_locale = "C.UTF-8";
416 const char *env_var_set[] = {
417 "LC_ALL",
418 "LC_CTYPE",
419 "LANG",
420 NULL,
421 };
422
423 /* Android setlocale(category, "") doesn't check the environment variables
424 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
425 * check the environment variables listed in env_var_set. */
426 for (pvar=env_var_set; *pvar; pvar++) {
427 locale = getenv(*pvar);
428 if (locale != NULL && *locale != '\0') {
429 if (strcmp(locale, utf8_locale) == 0 ||
430 strcmp(locale, "en_US.UTF-8") == 0) {
431 return setlocale(category, utf8_locale);
432 }
433 return setlocale(category, "C");
434 }
435 }
436
437 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
438 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
439 * Quote from POSIX section "8.2 Internationalization Variables":
440 * "4. If the LANG environment variable is not set or is set to the empty
441 * string, the implementation-defined default locale shall be used." */
442
443#ifdef PY_COERCE_C_LOCALE
444 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
445 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
446 /* Some other ported code may check the environment variables (e.g. in
447 * extension modules), so we make sure that they match the locale
448 * configuration */
449 if (setenv("LC_CTYPE", utf8_locale, 1)) {
450 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
451 "environment variable to %s\n", utf8_locale);
452 }
453 }
454#endif
455 return setlocale(category, utf8_locale);
456#else /* __ANDROID__ */
457 return setlocale(category, "");
458#endif /* __ANDROID__ */
459}
460
Nick Coghlan6ea41862017-06-11 13:16:15 +1000461
Eric Snow1abcf672017-05-23 21:46:51 -0700462/* Global initializations. Can be undone by Py_Finalize(). Don't
463 call this twice without an intervening Py_Finalize() call.
464
Victor Stinner1dc6e392018-07-25 02:49:17 +0200465 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700466 must have a corresponding call to Py_Finalize.
467
468 Locking: you must hold the interpreter lock while calling these APIs.
469 (If the lock has not yet been initialized, that's equivalent to
470 having the lock, but you cannot use multiple threads.)
471
472*/
473
Victor Stinner1dc6e392018-07-25 02:49:17 +0200474static _PyInitError
475_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
476 const _PyCoreConfig *core_config)
477{
478 if (core_config->allocator != NULL) {
479 const char *allocator = _PyMem_GetAllocatorsName();
480 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
481 return _Py_INIT_USER_ERR("cannot modify memory allocator "
482 "after first Py_Initialize()");
483 }
484 }
485
486 _PyCoreConfig_SetGlobalConfig(core_config);
487
488 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
489 return _Py_INIT_ERR("failed to copy core config");
490 }
491 core_config = &interp->core_config;
492
493 if (core_config->_install_importlib) {
494 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
495 if (_Py_INIT_FAILED(err)) {
496 return err;
497 }
498 }
499 return _Py_INIT_OK();
500}
501
502
Eric Snow1abcf672017-05-23 21:46:51 -0700503/* Begin interpreter initialization
504 *
505 * On return, the first thread and interpreter state have been created,
506 * but the compiler, signal handling, multithreading and
507 * multiple interpreter support, and codec infrastructure are not yet
508 * available.
509 *
510 * The import system will support builtin and frozen modules only.
511 * The only supported io is writing to sys.stderr
512 *
513 * If any operation invoked by this function fails, a fatal error is
514 * issued and the function does not return.
515 *
516 * Any code invoked from this function should *not* assume it has access
517 * to the Python C API (unless the API is explicitly listed as being
518 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200519 *
520 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700521 */
522
Victor Stinner1dc6e392018-07-25 02:49:17 +0200523static _PyInitError
524_Py_InitializeCore_impl(PyInterpreterState **interp_p,
525 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000526{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200527 PyInterpreterState *interp;
528 _PyInitError err;
529
530 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
531 Py_Initialize() ignores the new configuration. */
532 if (_PyRuntime.core_initialized) {
533 PyThreadState *tstate = PyThreadState_GET();
534 if (!tstate) {
535 return _Py_INIT_ERR("failed to read thread state");
536 }
537
538 interp = tstate->interp;
539 if (interp == NULL) {
540 return _Py_INIT_ERR("can't make main interpreter");
541 }
542 *interp_p = interp;
543
544 return _Py_Initialize_ReconfigureCore(interp, core_config);
545 }
546
547 if (_PyRuntime.initialized) {
548 return _Py_INIT_ERR("main interpreter already initialized");
549 }
Victor Stinnerda273412017-12-15 01:46:02 +0100550
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200551 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000552
Victor Stinner1dc6e392018-07-25 02:49:17 +0200553 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800554 if (_Py_INIT_FAILED(err)) {
555 return err;
556 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600557
Victor Stinner31e99082017-12-20 23:41:38 +0100558 if (core_config->allocator != NULL) {
559 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
560 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
561 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800562 }
563
Eric Snow1abcf672017-05-23 21:46:51 -0700564 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
565 * threads behave a little more gracefully at interpreter shutdown.
566 * We clobber it here so the new interpreter can start with a clean
567 * slate.
568 *
569 * However, this may still lead to misbehaviour if there are daemon
570 * threads still hanging around from a previous Py_Initialize/Finalize
571 * pair :(
572 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600573 _PyRuntime.finalizing = NULL;
574
Victor Stinnerda273412017-12-15 01:46:02 +0100575 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800576 if (_Py_INIT_FAILED(err)) {
577 return err;
578 }
579
Victor Stinnera7368ac2017-11-15 18:11:45 -0800580 err = _PyInterpreterState_Enable(&_PyRuntime);
581 if (_Py_INIT_FAILED(err)) {
582 return err;
583 }
584
Victor Stinner1dc6e392018-07-25 02:49:17 +0200585 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100586 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800587 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100588 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200589 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100590
591 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
592 return _Py_INIT_ERR("failed to copy core config");
593 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200594 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000595
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200596 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000597 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800598 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000599 (void) PyThreadState_Swap(tstate);
600
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000601 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000602 destroying the GIL might fail when it is being referenced from
603 another running thread (see issue #9901).
604 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000605 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000606 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100607
Nick Coghland6009512014-11-20 21:39:37 +1000608 /* Auto-thread-state API */
609 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000610
Victor Stinner2914bb32018-01-29 11:57:45 +0100611 /* Create the GIL */
612 PyEval_InitThreads();
613
Nick Coghland6009512014-11-20 21:39:37 +1000614 _Py_ReadyTypes();
615
Nick Coghland6009512014-11-20 21:39:37 +1000616 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800617 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000618
619 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800620 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000621
622 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800623 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000624
Eric Snowd393c1b2017-09-14 12:18:12 -0600625 PyObject *modules = PyDict_New();
626 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800627 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600628 interp->modules = modules;
629
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200630 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800631 err = _PySys_BeginInit(&sysmod);
632 if (_Py_INIT_FAILED(err)) {
633 return err;
634 }
635
Eric Snowd393c1b2017-09-14 12:18:12 -0600636 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800637 if (interp->sysdict == NULL) {
638 return _Py_INIT_ERR("can't initialize sys dict");
639 }
640
Eric Snowd393c1b2017-09-14 12:18:12 -0600641 Py_INCREF(interp->sysdict);
642 PyDict_SetItemString(interp->sysdict, "modules", modules);
643 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000644
645 /* Init Unicode implementation; relies on the codec registry */
646 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800647 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700648
Nick Coghland6009512014-11-20 21:39:37 +1000649 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800650 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000651
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200652 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000653 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800654 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600655 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000656 interp->builtins = PyModule_GetDict(bimod);
657 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800658 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000659 Py_INCREF(interp->builtins);
660
661 /* initialize builtin exceptions */
662 _PyExc_Init(bimod);
663
Nick Coghland6009512014-11-20 21:39:37 +1000664 /* Set up a preliminary stderr printer until we have enough
665 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200666 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000667 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800668 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000669 _PySys_SetObjectId(&PyId_stderr, pstderr);
670 PySys_SetObject("__stderr__", pstderr);
671 Py_DECREF(pstderr);
672
Victor Stinner672b6ba2017-12-06 17:25:50 +0100673 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800674 if (_Py_INIT_FAILED(err)) {
675 return err;
676 }
Nick Coghland6009512014-11-20 21:39:37 +1000677
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800678 err = _PyImportHooks_Init();
679 if (_Py_INIT_FAILED(err)) {
680 return err;
681 }
Nick Coghland6009512014-11-20 21:39:37 +1000682
683 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100684 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100685 return _Py_INIT_ERR("can't initialize warnings");
686 }
Nick Coghland6009512014-11-20 21:39:37 +1000687
Yury Selivanovf23746a2018-01-22 19:11:18 -0500688 if (!_PyContext_Init())
689 return _Py_INIT_ERR("can't init context");
690
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200691 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200692 err = _PyCoreConfig_SetPathConfig(core_config);
693 if (_Py_INIT_FAILED(err)) {
694 return err;
695 }
696 }
697
Eric Snow1abcf672017-05-23 21:46:51 -0700698 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200699 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800700 err = initimport(interp, sysmod);
701 if (_Py_INIT_FAILED(err)) {
702 return err;
703 }
Eric Snow1abcf672017-05-23 21:46:51 -0700704 }
705
706 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600707 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800708 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700709}
710
Victor Stinner1dc6e392018-07-25 02:49:17 +0200711_PyInitError
712_Py_InitializeCore(PyInterpreterState **interp_p,
713 const _PyCoreConfig *src_config)
714{
715 assert(src_config != NULL);
716
Victor Stinner1dc6e392018-07-25 02:49:17 +0200717 PyMemAllocatorEx old_alloc;
718 _PyInitError err;
719
720 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
721 (and the input configuration is read only). */
722 _PyCoreConfig config = _PyCoreConfig_INIT;
723
Victor Stinner177d9212018-08-29 11:25:15 +0200724 /* Set LC_CTYPE to the user preferred locale */
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200725 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner2c8ddcf2018-08-29 00:16:53 +0200726
Victor Stinner1dc6e392018-07-25 02:49:17 +0200727 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
728 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
729 err = _PyCoreConfig_Read(&config);
730 }
731 else {
732 err = _Py_INIT_ERR("failed to copy core config");
733 }
734 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
735
736 if (_Py_INIT_FAILED(err)) {
737 goto done;
738 }
739
740 err = _Py_InitializeCore_impl(interp_p, &config);
741
742done:
743 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
744 _PyCoreConfig_Clear(&config);
745 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
746
747 return err;
748}
749
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200750/* Py_Initialize() has already been called: update the main interpreter
751 configuration. Example of bpo-34008: Py_Main() called after
752 Py_Initialize(). */
753static _PyInitError
754_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
755 const _PyMainInterpreterConfig *config)
756{
757 if (config->argv != NULL) {
758 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
759 if (res < 0) {
760 return _Py_INIT_ERR("fail to set sys.argv");
761 }
762 }
763 return _Py_INIT_OK();
764}
765
Eric Snowc7ec9982017-05-23 23:00:52 -0700766/* Update interpreter state based on supplied configuration settings
767 *
768 * After calling this function, most of the restrictions on the interpreter
769 * are lifted. The only remaining incomplete settings are those related
770 * to the main module (sys.argv[0], __main__ metadata)
771 *
772 * Calling this when the interpreter is not initializing, is already
773 * initialized or without a valid current thread state is a fatal error.
774 * Other errors should be reported as normal Python exceptions with a
775 * non-zero return code.
776 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800777_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200778_Py_InitializeMainInterpreter(PyInterpreterState *interp,
779 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700780{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600781 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800782 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700783 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700784
Victor Stinner1dc6e392018-07-25 02:49:17 +0200785 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100786 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
787 return _Py_INIT_ERR("failed to copy main interpreter config");
788 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200789 config = &interp->config;
790 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700791
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200792 if (_PyRuntime.initialized) {
793 return _Py_ReconfigureMainInterpreter(interp, config);
794 }
795
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200796 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700797 /* Special mode for freeze_importlib: run with no import system
798 *
799 * This means anything which needs support from extension modules
800 * or pure Python code in the standard library won't work.
801 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600802 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800803 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700804 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100805
Victor Stinner33c377e2017-12-05 15:12:41 +0100806 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800807 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100808 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200809
Victor Stinnerfbca9082018-08-30 00:50:45 +0200810 if (_PySys_EndInit(interp->sysdict, interp) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800811 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100812 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800813
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200814 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800815 if (_Py_INIT_FAILED(err)) {
816 return err;
817 }
Nick Coghland6009512014-11-20 21:39:37 +1000818
819 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200820 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800821 if (_Py_INIT_FAILED(err)) {
822 return err;
823 }
Nick Coghland6009512014-11-20 21:39:37 +1000824
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800825 err = initfsencoding(interp);
826 if (_Py_INIT_FAILED(err)) {
827 return err;
828 }
Nick Coghland6009512014-11-20 21:39:37 +1000829
Victor Stinner1f151112017-11-23 10:43:14 +0100830 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800831 err = initsigs(); /* Signal handling stuff, including initintr() */
832 if (_Py_INIT_FAILED(err)) {
833 return err;
834 }
835 }
Nick Coghland6009512014-11-20 21:39:37 +1000836
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200837 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800838 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200839 }
Nick Coghland6009512014-11-20 21:39:37 +1000840
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800841 err = add_main_module(interp);
842 if (_Py_INIT_FAILED(err)) {
843 return err;
844 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800845
Victor Stinner91106cd2017-12-13 12:29:09 +0100846 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800847 if (_Py_INIT_FAILED(err)) {
848 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800849 }
Nick Coghland6009512014-11-20 21:39:37 +1000850
851 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100852 if (interp->config.warnoptions != NULL &&
853 PyList_Size(interp->config.warnoptions) > 0)
854 {
Nick Coghland6009512014-11-20 21:39:37 +1000855 PyObject *warnings_module = PyImport_ImportModule("warnings");
856 if (warnings_module == NULL) {
857 fprintf(stderr, "'import warnings' failed; traceback:\n");
858 PyErr_Print();
859 }
860 Py_XDECREF(warnings_module);
861 }
862
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600863 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700864
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200865 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800866 err = initsite(); /* Module site */
867 if (_Py_INIT_FAILED(err)) {
868 return err;
869 }
870 }
Victor Stinnercf215042018-08-29 22:56:06 +0200871
872#ifndef MS_WINDOWS
873 _emit_stderr_warning_for_legacy_locale(core_config);
874#endif
875
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800876 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000877}
878
Eric Snowc7ec9982017-05-23 23:00:52 -0700879#undef _INIT_DEBUG_PRINT
880
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800881_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200882_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700883{
Benjamin Petersonacd282f2018-09-11 15:11:06 -0700884 PyInterpreterState *interp = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800885 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200886 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800887 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200888 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800889 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200890 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100891
Victor Stinner9cfc0022017-12-20 19:36:46 +0100892 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200893 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100894 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200895 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100897 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800898 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200899 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200901 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700902}
903
904
905void
Nick Coghland6009512014-11-20 21:39:37 +1000906Py_InitializeEx(int install_sigs)
907{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200908 if (_PyRuntime.initialized) {
909 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
910 return;
911 }
912
913 _PyInitError err;
914 _PyCoreConfig config = _PyCoreConfig_INIT;
915 config.install_signal_handlers = install_sigs;
916
917 err = _Py_InitializeFromConfig(&config);
918 _PyCoreConfig_Clear(&config);
919
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800920 if (_Py_INIT_FAILED(err)) {
921 _Py_FatalInitError(err);
922 }
Nick Coghland6009512014-11-20 21:39:37 +1000923}
924
925void
926Py_Initialize(void)
927{
928 Py_InitializeEx(1);
929}
930
931
932#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +0000933extern void _Py_dump_counts(FILE*);
Nick Coghland6009512014-11-20 21:39:37 +1000934#endif
935
936/* Flush stdout and stderr */
937
938static int
939file_is_closed(PyObject *fobj)
940{
941 int r;
942 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
943 if (tmp == NULL) {
944 PyErr_Clear();
945 return 0;
946 }
947 r = PyObject_IsTrue(tmp);
948 Py_DECREF(tmp);
949 if (r < 0)
950 PyErr_Clear();
951 return r > 0;
952}
953
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000954static int
Nick Coghland6009512014-11-20 21:39:37 +1000955flush_std_files(void)
956{
957 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
958 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
959 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000960 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000961
962 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700963 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000964 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000965 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000966 status = -1;
967 }
Nick Coghland6009512014-11-20 21:39:37 +1000968 else
969 Py_DECREF(tmp);
970 }
971
972 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700973 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000974 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000975 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000976 status = -1;
977 }
Nick Coghland6009512014-11-20 21:39:37 +1000978 else
979 Py_DECREF(tmp);
980 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000981
982 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000983}
984
985/* Undo the effect of Py_Initialize().
986
987 Beware: if multiple interpreter and/or thread states exist, these
988 are not wiped out; only the current thread and interpreter state
989 are deleted. But since everything else is deleted, those other
990 interpreter and thread states should no longer be used.
991
992 (XXX We should do better, e.g. wipe out all interpreters and
993 threads.)
994
995 Locking: as above.
996
997*/
998
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000999int
1000Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001001{
1002 PyInterpreterState *interp;
1003 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001004 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001005
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001006 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001007 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001008
1009 wait_for_thread_shutdown();
1010
Marcel Plch776407f2017-12-20 11:17:58 +01001011 /* Get current thread state and interpreter pointer */
1012 tstate = PyThreadState_GET();
1013 interp = tstate->interp;
1014
Nick Coghland6009512014-11-20 21:39:37 +10001015 /* The interpreter is still entirely intact at this point, and the
1016 * exit funcs may be relying on that. In particular, if some thread
1017 * or exit func is still waiting to do an import, the import machinery
1018 * expects Py_IsInitialized() to return true. So don't say the
1019 * interpreter is uninitialized until after the exit funcs have run.
1020 * Note that Threading.py uses an exit func to do a join on all the
1021 * threads created thru it, so this also protects pending imports in
1022 * the threads created via Threading.
1023 */
Nick Coghland6009512014-11-20 21:39:37 +10001024
Marcel Plch776407f2017-12-20 11:17:58 +01001025 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001026
Victor Stinnerda273412017-12-15 01:46:02 +01001027 /* Copy the core config, PyInterpreterState_Delete() free
1028 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001029#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001030 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001031#endif
1032#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001033 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001034#endif
1035#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001036 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001037#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001038
Nick Coghland6009512014-11-20 21:39:37 +10001039 /* Remaining threads (e.g. daemon threads) will automatically exit
1040 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001041 _PyRuntime.finalizing = tstate;
1042 _PyRuntime.initialized = 0;
1043 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001044
Victor Stinnere0deff32015-03-24 13:46:18 +01001045 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001046 if (flush_std_files() < 0) {
1047 status = -1;
1048 }
Nick Coghland6009512014-11-20 21:39:37 +10001049
1050 /* Disable signal handling */
1051 PyOS_FiniInterrupts();
1052
1053 /* Collect garbage. This may call finalizers; it's nice to call these
1054 * before all modules are destroyed.
1055 * XXX If a __del__ or weakref callback is triggered here, and tries to
1056 * XXX import a module, bad things can happen, because Python no
1057 * XXX longer believes it's initialized.
1058 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1059 * XXX is easy to provoke that way. I've also seen, e.g.,
1060 * XXX Exception exceptions.ImportError: 'No module named sha'
1061 * XXX in <function callback at 0x008F5718> ignored
1062 * XXX but I'm unclear on exactly how that one happens. In any case,
1063 * XXX I haven't seen a real-life report of either of these.
1064 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001065 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001066#ifdef COUNT_ALLOCS
1067 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1068 each collection might release some types from the type
1069 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001070 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001071 /* nothing */;
1072#endif
Eric Snowdae02762017-09-14 00:35:58 -07001073
Nick Coghland6009512014-11-20 21:39:37 +10001074 /* Destroy all modules */
1075 PyImport_Cleanup();
1076
Victor Stinnere0deff32015-03-24 13:46:18 +01001077 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001078 if (flush_std_files() < 0) {
1079 status = -1;
1080 }
Nick Coghland6009512014-11-20 21:39:37 +10001081
1082 /* Collect final garbage. This disposes of cycles created by
1083 * class definitions, for example.
1084 * XXX This is disabled because it caused too many problems. If
1085 * XXX a __del__ or weakref callback triggers here, Python code has
1086 * XXX a hard time running, because even the sys module has been
1087 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1088 * XXX One symptom is a sequence of information-free messages
1089 * XXX coming from threads (if a __del__ or callback is invoked,
1090 * XXX other threads can execute too, and any exception they encounter
1091 * XXX triggers a comedy of errors as subsystem after subsystem
1092 * XXX fails to find what it *expects* to find in sys to help report
1093 * XXX the exception and consequent unexpected failures). I've also
1094 * XXX seen segfaults then, after adding print statements to the
1095 * XXX Python code getting called.
1096 */
1097#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001098 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001099#endif
1100
1101 /* Disable tracemalloc after all Python objects have been destroyed,
1102 so it is possible to use tracemalloc in objects destructor. */
1103 _PyTraceMalloc_Fini();
1104
1105 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1106 _PyImport_Fini();
1107
1108 /* Cleanup typeobject.c's internal caches. */
1109 _PyType_Fini();
1110
1111 /* unload faulthandler module */
1112 _PyFaulthandler_Fini();
1113
1114 /* Debugging stuff */
1115#ifdef COUNT_ALLOCS
Pablo Galindo49c75a82018-10-28 15:02:17 +00001116 _Py_dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001117#endif
1118 /* dump hash stats */
1119 _PyHash_Fini();
1120
Eric Snowdae02762017-09-14 00:35:58 -07001121#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001122 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001123 _PyDebug_PrintTotalRefs();
1124 }
Eric Snowdae02762017-09-14 00:35:58 -07001125#endif
Nick Coghland6009512014-11-20 21:39:37 +10001126
1127#ifdef Py_TRACE_REFS
1128 /* Display all objects still alive -- this can invoke arbitrary
1129 * __repr__ overrides, so requires a mostly-intact interpreter.
1130 * Alas, a lot of stuff may still be alive now that will be cleaned
1131 * up later.
1132 */
Victor Stinnerda273412017-12-15 01:46:02 +01001133 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001134 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001135 }
Nick Coghland6009512014-11-20 21:39:37 +10001136#endif /* Py_TRACE_REFS */
1137
1138 /* Clear interpreter state and all thread states. */
1139 PyInterpreterState_Clear(interp);
1140
1141 /* Now we decref the exception classes. After this point nothing
1142 can raise an exception. That's okay, because each Fini() method
1143 below has been checked to make sure no exceptions are ever
1144 raised.
1145 */
1146
1147 _PyExc_Fini();
1148
1149 /* Sundry finalizers */
1150 PyMethod_Fini();
1151 PyFrame_Fini();
1152 PyCFunction_Fini();
1153 PyTuple_Fini();
1154 PyList_Fini();
1155 PySet_Fini();
1156 PyBytes_Fini();
1157 PyByteArray_Fini();
1158 PyLong_Fini();
1159 PyFloat_Fini();
1160 PyDict_Fini();
1161 PySlice_Fini();
1162 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001163 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001164 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001165 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001166 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001167
1168 /* Cleanup Unicode implementation */
1169 _PyUnicode_Fini();
1170
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001171 _Py_ClearFileSystemEncoding();
Nick Coghland6009512014-11-20 21:39:37 +10001172
1173 /* XXX Still allocated:
1174 - various static ad-hoc pointers to interned strings
1175 - int and float free list blocks
1176 - whatever various modules and libraries allocate
1177 */
1178
1179 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1180
1181 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001182 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001183
1184 /* Delete current thread. After this, many C API calls become crashy. */
1185 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001186
Nick Coghland6009512014-11-20 21:39:37 +10001187 PyInterpreterState_Delete(interp);
1188
1189#ifdef Py_TRACE_REFS
1190 /* Display addresses (& refcnts) of all objects still alive.
1191 * An address can be used to find the repr of the object, printed
1192 * above by _Py_PrintReferences.
1193 */
Victor Stinnerda273412017-12-15 01:46:02 +01001194 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001195 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001196 }
Nick Coghland6009512014-11-20 21:39:37 +10001197#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001198#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001199 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001200 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001201 }
Nick Coghland6009512014-11-20 21:39:37 +10001202#endif
1203
1204 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001205
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001206 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001207 return status;
1208}
1209
1210void
1211Py_Finalize(void)
1212{
1213 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001214}
1215
1216/* Create and initialize a new interpreter and thread, and return the
1217 new thread. This requires that Py_Initialize() has been called
1218 first.
1219
1220 Unsuccessful initialization yields a NULL pointer. Note that *no*
1221 exception information is available even in this case -- the
1222 exception information is held in the thread, and there is no
1223 thread.
1224
1225 Locking: as above.
1226
1227*/
1228
Victor Stinnera7368ac2017-11-15 18:11:45 -08001229static _PyInitError
1230new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001231{
1232 PyInterpreterState *interp;
1233 PyThreadState *tstate, *save_tstate;
1234 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001235 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001236
Victor Stinnera7368ac2017-11-15 18:11:45 -08001237 if (!_PyRuntime.initialized) {
1238 return _Py_INIT_ERR("Py_Initialize must be called first");
1239 }
Nick Coghland6009512014-11-20 21:39:37 +10001240
Victor Stinner8a1be612016-03-14 22:07:55 +01001241 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1242 interpreters: disable PyGILState_Check(). */
1243 _PyGILState_check_enabled = 0;
1244
Nick Coghland6009512014-11-20 21:39:37 +10001245 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001246 if (interp == NULL) {
1247 *tstate_p = NULL;
1248 return _Py_INIT_OK();
1249 }
Nick Coghland6009512014-11-20 21:39:37 +10001250
1251 tstate = PyThreadState_New(interp);
1252 if (tstate == NULL) {
1253 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001254 *tstate_p = NULL;
1255 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001256 }
1257
1258 save_tstate = PyThreadState_Swap(tstate);
1259
Eric Snow1abcf672017-05-23 21:46:51 -07001260 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001261 _PyCoreConfig *core_config;
1262 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001263 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001264 core_config = &save_tstate->interp->core_config;
1265 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001266 } else {
1267 /* No current thread state, copy from the main interpreter */
1268 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001269 core_config = &main_interp->core_config;
1270 config = &main_interp->config;
1271 }
1272
1273 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1274 return _Py_INIT_ERR("failed to copy core config");
1275 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001276 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001277 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1278 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001279 }
1280
Nick Coghland6009512014-11-20 21:39:37 +10001281 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001282 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001283 if (modules == NULL) {
1284 return _Py_INIT_ERR("can't make modules dictionary");
1285 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001286 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001287
Eric Snowd393c1b2017-09-14 12:18:12 -06001288 sysmod = _PyImport_FindBuiltin("sys", modules);
1289 if (sysmod != NULL) {
1290 interp->sysdict = PyModule_GetDict(sysmod);
1291 if (interp->sysdict == NULL)
1292 goto handle_error;
1293 Py_INCREF(interp->sysdict);
1294 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001295 _PySys_EndInit(interp->sysdict, interp);
Eric Snowd393c1b2017-09-14 12:18:12 -06001296 }
1297
1298 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001299 if (bimod != NULL) {
1300 interp->builtins = PyModule_GetDict(bimod);
1301 if (interp->builtins == NULL)
1302 goto handle_error;
1303 Py_INCREF(interp->builtins);
1304 }
1305
1306 /* initialize builtin exceptions */
1307 _PyExc_Init(bimod);
1308
Nick Coghland6009512014-11-20 21:39:37 +10001309 if (bimod != NULL && sysmod != NULL) {
1310 PyObject *pstderr;
1311
Nick Coghland6009512014-11-20 21:39:37 +10001312 /* Set up a preliminary stderr printer until we have enough
1313 infrastructure for the io module in place. */
1314 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001315 if (pstderr == NULL) {
1316 return _Py_INIT_ERR("can't set preliminary stderr");
1317 }
Nick Coghland6009512014-11-20 21:39:37 +10001318 _PySys_SetObjectId(&PyId_stderr, pstderr);
1319 PySys_SetObject("__stderr__", pstderr);
1320 Py_DECREF(pstderr);
1321
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001322 err = _PyImportHooks_Init();
1323 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001324 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001325 }
Nick Coghland6009512014-11-20 21:39:37 +10001326
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001327 err = initimport(interp, sysmod);
1328 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001329 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001330 }
Nick Coghland6009512014-11-20 21:39:37 +10001331
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001332 err = initexternalimport(interp);
1333 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001334 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001335 }
Nick Coghland6009512014-11-20 21:39:37 +10001336
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001337 err = initfsencoding(interp);
1338 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001339 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001340 }
1341
Victor Stinner91106cd2017-12-13 12:29:09 +01001342 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001343 if (_Py_INIT_FAILED(err)) {
1344 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001345 }
1346
1347 err = add_main_module(interp);
1348 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001349 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001350 }
1351
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001352 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001353 err = initsite();
1354 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001355 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001356 }
1357 }
Nick Coghland6009512014-11-20 21:39:37 +10001358 }
1359
Victor Stinnera7368ac2017-11-15 18:11:45 -08001360 if (PyErr_Occurred()) {
1361 goto handle_error;
1362 }
Nick Coghland6009512014-11-20 21:39:37 +10001363
Victor Stinnera7368ac2017-11-15 18:11:45 -08001364 *tstate_p = tstate;
1365 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001366
Nick Coghland6009512014-11-20 21:39:37 +10001367handle_error:
1368 /* Oops, it didn't work. Undo it all. */
1369
1370 PyErr_PrintEx(0);
1371 PyThreadState_Clear(tstate);
1372 PyThreadState_Swap(save_tstate);
1373 PyThreadState_Delete(tstate);
1374 PyInterpreterState_Delete(interp);
1375
Victor Stinnera7368ac2017-11-15 18:11:45 -08001376 *tstate_p = NULL;
1377 return _Py_INIT_OK();
1378}
1379
1380PyThreadState *
1381Py_NewInterpreter(void)
1382{
1383 PyThreadState *tstate;
1384 _PyInitError err = new_interpreter(&tstate);
1385 if (_Py_INIT_FAILED(err)) {
1386 _Py_FatalInitError(err);
1387 }
1388 return tstate;
1389
Nick Coghland6009512014-11-20 21:39:37 +10001390}
1391
1392/* Delete an interpreter and its last thread. This requires that the
1393 given thread state is current, that the thread has no remaining
1394 frames, and that it is its interpreter's only remaining thread.
1395 It is a fatal error to violate these constraints.
1396
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001397 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001398 everything, regardless.)
1399
1400 Locking: as above.
1401
1402*/
1403
1404void
1405Py_EndInterpreter(PyThreadState *tstate)
1406{
1407 PyInterpreterState *interp = tstate->interp;
1408
1409 if (tstate != PyThreadState_GET())
1410 Py_FatalError("Py_EndInterpreter: thread is not current");
1411 if (tstate->frame != NULL)
1412 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1413
1414 wait_for_thread_shutdown();
1415
Marcel Plch776407f2017-12-20 11:17:58 +01001416 call_py_exitfuncs(interp);
1417
Nick Coghland6009512014-11-20 21:39:37 +10001418 if (tstate != interp->tstate_head || tstate->next != NULL)
1419 Py_FatalError("Py_EndInterpreter: not the last thread");
1420
1421 PyImport_Cleanup();
1422 PyInterpreterState_Clear(interp);
1423 PyThreadState_Swap(NULL);
1424 PyInterpreterState_Delete(interp);
1425}
1426
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001427/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001428
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001429static _PyInitError
1430add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001431{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001432 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001433 m = PyImport_AddModule("__main__");
1434 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001435 return _Py_INIT_ERR("can't create __main__ module");
1436
Nick Coghland6009512014-11-20 21:39:37 +10001437 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001438 ann_dict = PyDict_New();
1439 if ((ann_dict == NULL) ||
1440 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001441 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001442 }
1443 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001444
Nick Coghland6009512014-11-20 21:39:37 +10001445 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1446 PyObject *bimod = PyImport_ImportModule("builtins");
1447 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001448 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001449 }
1450 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001451 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001452 }
1453 Py_DECREF(bimod);
1454 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001455
Nick Coghland6009512014-11-20 21:39:37 +10001456 /* Main is a little special - imp.is_builtin("__main__") will return
1457 * False, but BuiltinImporter is still the most appropriate initial
1458 * setting for its __loader__ attribute. A more suitable value will
1459 * be set if __main__ gets further initialized later in the startup
1460 * process.
1461 */
1462 loader = PyDict_GetItemString(d, "__loader__");
1463 if (loader == NULL || loader == Py_None) {
1464 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1465 "BuiltinImporter");
1466 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001467 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001468 }
1469 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001470 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001471 }
1472 Py_DECREF(loader);
1473 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001474 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001475}
1476
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001477static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001478initfsencoding(PyInterpreterState *interp)
1479{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001480 _PyCoreConfig *config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +10001481
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001482 char *encoding = get_codec_name(config->filesystem_encoding);
1483 if (encoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001484 /* Such error can only occurs in critical situations: no more
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001485 memory, import a module of the standard library failed, etc. */
1486 return _Py_INIT_ERR("failed to get the Python codec "
1487 "of the filesystem encoding");
Nick Coghland6009512014-11-20 21:39:37 +10001488 }
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001489
1490 /* Update the filesystem encoding to the normalized Python codec name.
1491 For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
1492 (Python codec name). */
1493 PyMem_RawFree(config->filesystem_encoding);
1494 config->filesystem_encoding = encoding;
1495
1496 /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
1497 global configuration variables. */
1498 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1499 config->filesystem_errors) < 0) {
1500 return _Py_INIT_NO_MEMORY();
1501 }
1502
1503 /* PyUnicode can now use the Python codec rather than C implementation
1504 for the filesystem encoding */
Nick Coghland6009512014-11-20 21:39:37 +10001505 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001506 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001507}
1508
1509/* Import the site module (not into __main__ though) */
1510
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001511static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001512initsite(void)
1513{
1514 PyObject *m;
1515 m = PyImport_ImportModule("site");
1516 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001518 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001519 Py_DECREF(m);
1520 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001521}
1522
Victor Stinner874dbe82015-09-04 17:29:57 +02001523/* Check if a file descriptor is valid or not.
1524 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1525static int
1526is_valid_fd(int fd)
1527{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001528#ifdef __APPLE__
1529 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1530 and the other side of the pipe is closed, dup(1) succeed, whereas
1531 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1532 such error. */
1533 struct stat st;
1534 return (fstat(fd, &st) == 0);
1535#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001536 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001537 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001538 return 0;
1539 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001540 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1541 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1542 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001543 fd2 = dup(fd);
1544 if (fd2 >= 0)
1545 close(fd2);
1546 _Py_END_SUPPRESS_IPH
1547 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001548#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001549}
1550
1551/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001552static PyObject*
Victor Stinnerfbca9082018-08-30 00:50:45 +02001553create_stdio(const _PyCoreConfig *config, PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001554 int fd, int write_mode, const char* name,
1555 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001556{
1557 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1558 const char* mode;
1559 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001560 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001561 int buffering, isatty;
1562 _Py_IDENTIFIER(open);
1563 _Py_IDENTIFIER(isatty);
1564 _Py_IDENTIFIER(TextIOWrapper);
1565 _Py_IDENTIFIER(mode);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001566 const int buffered_stdio = config->buffered_stdio;
Nick Coghland6009512014-11-20 21:39:37 +10001567
Victor Stinner874dbe82015-09-04 17:29:57 +02001568 if (!is_valid_fd(fd))
1569 Py_RETURN_NONE;
1570
Nick Coghland6009512014-11-20 21:39:37 +10001571 /* stdin is always opened in buffered mode, first because it shouldn't
1572 make a difference in common use cases, second because TextIOWrapper
1573 depends on the presence of a read1() method which only exists on
1574 buffered streams.
1575 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001576 if (!buffered_stdio && write_mode)
Nick Coghland6009512014-11-20 21:39:37 +10001577 buffering = 0;
1578 else
1579 buffering = -1;
1580 if (write_mode)
1581 mode = "wb";
1582 else
1583 mode = "rb";
1584 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1585 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001586 Py_None, Py_None, /* encoding, errors */
1587 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001588 if (buf == NULL)
1589 goto error;
1590
1591 if (buffering) {
1592 _Py_IDENTIFIER(raw);
1593 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1594 if (raw == NULL)
1595 goto error;
1596 }
1597 else {
1598 raw = buf;
1599 Py_INCREF(raw);
1600 }
1601
Steve Dower39294992016-08-30 21:22:36 -07001602#ifdef MS_WINDOWS
1603 /* Windows console IO is always UTF-8 encoded */
1604 if (PyWindowsConsoleIO_Check(raw))
1605 encoding = "utf-8";
1606#endif
1607
Nick Coghland6009512014-11-20 21:39:37 +10001608 text = PyUnicode_FromString(name);
1609 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1610 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001611 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001612 if (res == NULL)
1613 goto error;
1614 isatty = PyObject_IsTrue(res);
1615 Py_DECREF(res);
1616 if (isatty == -1)
1617 goto error;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001618 if (!buffered_stdio)
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001619 write_through = Py_True;
1620 else
1621 write_through = Py_False;
Victor Stinnerfbca9082018-08-30 00:50:45 +02001622 if (isatty && buffered_stdio)
Nick Coghland6009512014-11-20 21:39:37 +10001623 line_buffering = Py_True;
1624 else
1625 line_buffering = Py_False;
1626
1627 Py_CLEAR(raw);
1628 Py_CLEAR(text);
1629
1630#ifdef MS_WINDOWS
1631 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1632 newlines to "\n".
1633 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1634 newline = NULL;
1635#else
1636 /* sys.stdin: split lines at "\n".
1637 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1638 newline = "\n";
1639#endif
1640
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001641 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001642 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001643 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001644 Py_CLEAR(buf);
1645 if (stream == NULL)
1646 goto error;
1647
1648 if (write_mode)
1649 mode = "w";
1650 else
1651 mode = "r";
1652 text = PyUnicode_FromString(mode);
1653 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1654 goto error;
1655 Py_CLEAR(text);
1656 return stream;
1657
1658error:
1659 Py_XDECREF(buf);
1660 Py_XDECREF(stream);
1661 Py_XDECREF(text);
1662 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001663
Victor Stinner874dbe82015-09-04 17:29:57 +02001664 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1665 /* Issue #24891: the file descriptor was closed after the first
1666 is_valid_fd() check was called. Ignore the OSError and set the
1667 stream to None. */
1668 PyErr_Clear();
1669 Py_RETURN_NONE;
1670 }
1671 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001672}
1673
1674/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001675static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001676init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001677{
1678 PyObject *iomod = NULL, *wrapper;
1679 PyObject *bimod = NULL;
1680 PyObject *m;
1681 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001682 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001683 PyObject * encoding_attr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001684 _PyInitError res = _Py_INIT_OK();
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001685 _PyCoreConfig *config = &interp->core_config;
1686
1687 char *codec_name = get_codec_name(config->stdio_encoding);
1688 if (codec_name == NULL) {
1689 return _Py_INIT_ERR("failed to get the Python codec name "
1690 "of the stdio encoding");
1691 }
1692 PyMem_RawFree(config->stdio_encoding);
1693 config->stdio_encoding = codec_name;
Nick Coghland6009512014-11-20 21:39:37 +10001694
1695 /* Hack to avoid a nasty recursion issue when Python is invoked
1696 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1697 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1698 goto error;
1699 }
1700 Py_DECREF(m);
1701
1702 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1703 goto error;
1704 }
1705 Py_DECREF(m);
1706
1707 if (!(bimod = PyImport_ImportModule("builtins"))) {
1708 goto error;
1709 }
1710
1711 if (!(iomod = PyImport_ImportModule("io"))) {
1712 goto error;
1713 }
1714 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1715 goto error;
1716 }
1717
1718 /* Set builtins.open */
1719 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1720 Py_DECREF(wrapper);
1721 goto error;
1722 }
1723 Py_DECREF(wrapper);
1724
Nick Coghland6009512014-11-20 21:39:37 +10001725 /* Set sys.stdin */
1726 fd = fileno(stdin);
1727 /* Under some conditions stdin, stdout and stderr may not be connected
1728 * and fileno() may point to an invalid file descriptor. For example
1729 * GUI apps don't have valid standard streams by default.
1730 */
Victor Stinnerfbca9082018-08-30 00:50:45 +02001731 std = create_stdio(config, iomod, fd, 0, "<stdin>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001732 config->stdio_encoding,
1733 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001734 if (std == NULL)
1735 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001736 PySys_SetObject("__stdin__", std);
1737 _PySys_SetObjectId(&PyId_stdin, std);
1738 Py_DECREF(std);
1739
1740 /* Set sys.stdout */
1741 fd = fileno(stdout);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001742 std = create_stdio(config, iomod, fd, 1, "<stdout>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001743 config->stdio_encoding,
1744 config->stdio_errors);
Victor Stinner874dbe82015-09-04 17:29:57 +02001745 if (std == NULL)
1746 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001747 PySys_SetObject("__stdout__", std);
1748 _PySys_SetObjectId(&PyId_stdout, std);
1749 Py_DECREF(std);
1750
1751#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1752 /* Set sys.stderr, replaces the preliminary stderr */
1753 fd = fileno(stderr);
Victor Stinnerfbca9082018-08-30 00:50:45 +02001754 std = create_stdio(config, iomod, fd, 1, "<stderr>",
Victor Stinnerdfe0dc72018-08-29 11:47:29 +02001755 config->stdio_encoding,
1756 "backslashreplace");
Victor Stinner874dbe82015-09-04 17:29:57 +02001757 if (std == NULL)
1758 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001759
1760 /* Same as hack above, pre-import stderr's codec to avoid recursion
1761 when import.c tries to write to stderr in verbose mode. */
1762 encoding_attr = PyObject_GetAttrString(std, "encoding");
1763 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001764 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001765 if (std_encoding != NULL) {
1766 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1767 Py_XDECREF(codec_info);
1768 }
1769 Py_DECREF(encoding_attr);
1770 }
1771 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1772
1773 if (PySys_SetObject("__stderr__", std) < 0) {
1774 Py_DECREF(std);
1775 goto error;
1776 }
1777 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1778 Py_DECREF(std);
1779 goto error;
1780 }
1781 Py_DECREF(std);
1782#endif
1783
Victor Stinnera7368ac2017-11-15 18:11:45 -08001784 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001785
Victor Stinnera7368ac2017-11-15 18:11:45 -08001786error:
1787 res = _Py_INIT_ERR("can't initialize sys standard streams");
1788
1789done:
Victor Stinner124b9eb2018-08-29 01:29:06 +02001790 _Py_ClearStandardStreamEncoding();
Victor Stinner31e99082017-12-20 23:41:38 +01001791
Nick Coghland6009512014-11-20 21:39:37 +10001792 Py_XDECREF(bimod);
1793 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001794 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001795}
1796
1797
Victor Stinner10dc4842015-03-24 12:01:30 +01001798static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001799_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001800{
Victor Stinner10dc4842015-03-24 12:01:30 +01001801 fputc('\n', stderr);
1802 fflush(stderr);
1803
1804 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001805 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001806}
Victor Stinner791da1c2016-03-14 16:53:12 +01001807
1808/* Print the current exception (if an exception is set) with its traceback,
1809 or display the current Python stack.
1810
1811 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1812 called on catastrophic cases.
1813
1814 Return 1 if the traceback was displayed, 0 otherwise. */
1815
1816static int
1817_Py_FatalError_PrintExc(int fd)
1818{
1819 PyObject *ferr, *res;
1820 PyObject *exception, *v, *tb;
1821 int has_tb;
1822
Victor Stinner791da1c2016-03-14 16:53:12 +01001823 PyErr_Fetch(&exception, &v, &tb);
1824 if (exception == NULL) {
1825 /* No current exception */
1826 return 0;
1827 }
1828
1829 ferr = _PySys_GetObjectId(&PyId_stderr);
1830 if (ferr == NULL || ferr == Py_None) {
1831 /* sys.stderr is not set yet or set to None,
1832 no need to try to display the exception */
1833 return 0;
1834 }
1835
1836 PyErr_NormalizeException(&exception, &v, &tb);
1837 if (tb == NULL) {
1838 tb = Py_None;
1839 Py_INCREF(tb);
1840 }
1841 PyException_SetTraceback(v, tb);
1842 if (exception == NULL) {
1843 /* PyErr_NormalizeException() failed */
1844 return 0;
1845 }
1846
1847 has_tb = (tb != Py_None);
1848 PyErr_Display(exception, v, tb);
1849 Py_XDECREF(exception);
1850 Py_XDECREF(v);
1851 Py_XDECREF(tb);
1852
1853 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001854 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001855 if (res == NULL)
1856 PyErr_Clear();
1857 else
1858 Py_DECREF(res);
1859
1860 return has_tb;
1861}
1862
Nick Coghland6009512014-11-20 21:39:37 +10001863/* Print fatal error message and abort */
1864
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001865#ifdef MS_WINDOWS
1866static void
1867fatal_output_debug(const char *msg)
1868{
1869 /* buffer of 256 bytes allocated on the stack */
1870 WCHAR buffer[256 / sizeof(WCHAR)];
1871 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1872 size_t msglen;
1873
1874 OutputDebugStringW(L"Fatal Python error: ");
1875
1876 msglen = strlen(msg);
1877 while (msglen) {
1878 size_t i;
1879
1880 if (buflen > msglen) {
1881 buflen = msglen;
1882 }
1883
1884 /* Convert the message to wchar_t. This uses a simple one-to-one
1885 conversion, assuming that the this error message actually uses
1886 ASCII only. If this ceases to be true, we will have to convert. */
1887 for (i=0; i < buflen; ++i) {
1888 buffer[i] = msg[i];
1889 }
1890 buffer[i] = L'\0';
1891 OutputDebugStringW(buffer);
1892
1893 msg += buflen;
1894 msglen -= buflen;
1895 }
1896 OutputDebugStringW(L"\n");
1897}
1898#endif
1899
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001900static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001901fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001902{
1903 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001904 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001905
1906 if (reentrant) {
1907 /* Py_FatalError() caused a second fatal error.
1908 Example: flush_std_files() raises a recursion error. */
1909 goto exit;
1910 }
1911 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001912
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001913 fprintf(stderr, "Fatal Python error: ");
1914 if (prefix) {
1915 fputs(prefix, stderr);
1916 fputs(": ", stderr);
1917 }
1918 if (msg) {
1919 fputs(msg, stderr);
1920 }
1921 else {
1922 fprintf(stderr, "<message not set>");
1923 }
1924 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001925 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001926
Victor Stinner3a228ab2018-11-01 00:26:41 +01001927 /* Check if the current thread has a Python thread state
1928 and holds the GIL */
1929 PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
1930 if (tss_tstate != NULL) {
1931 PyThreadState *tstate = PyThreadState_GET();
1932 if (tss_tstate != tstate) {
1933 /* The Python thread does not hold the GIL */
1934 tss_tstate = NULL;
1935 }
1936 }
1937 else {
1938 /* Py_FatalError() has been called from a C thread
1939 which has no Python thread state. */
1940 }
1941 int has_tstate_and_gil = (tss_tstate != NULL);
1942
1943 if (has_tstate_and_gil) {
1944 /* If an exception is set, print the exception with its traceback */
1945 if (!_Py_FatalError_PrintExc(fd)) {
1946 /* No exception is set, or an exception is set without traceback */
1947 _Py_FatalError_DumpTracebacks(fd);
1948 }
1949 }
1950 else {
Victor Stinner791da1c2016-03-14 16:53:12 +01001951 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001952 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001953
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001954 /* The main purpose of faulthandler is to display the traceback.
1955 This function already did its best to display a traceback.
1956 Disable faulthandler to prevent writing a second traceback
1957 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001958 _PyFaulthandler_Fini();
1959
Victor Stinner791da1c2016-03-14 16:53:12 +01001960 /* Check if the current Python thread hold the GIL */
Victor Stinner3a228ab2018-11-01 00:26:41 +01001961 if (has_tstate_and_gil) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001962 /* Flush sys.stdout and sys.stderr */
1963 flush_std_files();
1964 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001965
Nick Coghland6009512014-11-20 21:39:37 +10001966#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001967 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001968#endif /* MS_WINDOWS */
1969
1970exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001972#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001974#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975 abort();
1976 }
1977 else {
1978 exit(status);
1979 }
1980}
1981
Victor Stinner19760862017-12-20 01:41:59 +01001982void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001983Py_FatalError(const char *msg)
1984{
1985 fatal_error(NULL, msg, -1);
1986}
1987
Victor Stinner19760862017-12-20 01:41:59 +01001988void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001989_Py_FatalInitError(_PyInitError err)
1990{
1991 /* On "user" error: exit with status 1.
1992 For all other errors, call abort(). */
1993 int status = err.user_err ? 1 : -1;
1994 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10001995}
1996
1997/* Clean up and exit */
1998
Victor Stinnerd7292b52016-06-17 12:29:00 +02001999# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002000
Nick Coghland6009512014-11-20 21:39:37 +10002001/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002002void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002003{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002004 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002005
Antoine Pitroufc5db952017-12-13 02:29:07 +01002006 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002007 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2008
2009 is->pyexitfunc = func;
2010 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002011}
2012
2013static void
Marcel Plch776407f2017-12-20 11:17:58 +01002014call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002015{
Marcel Plch776407f2017-12-20 11:17:58 +01002016 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002017 return;
2018
Marcel Plch776407f2017-12-20 11:17:58 +01002019 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002020 PyErr_Clear();
2021}
2022
2023/* Wait until threading._shutdown completes, provided
2024 the threading module was imported in the first place.
2025 The shutdown routine will wait until all non-daemon
2026 "threading" threads have completed. */
2027static void
2028wait_for_thread_shutdown(void)
2029{
Nick Coghland6009512014-11-20 21:39:37 +10002030 _Py_IDENTIFIER(_shutdown);
2031 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002032 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002033 if (threading == NULL) {
2034 /* threading not imported */
2035 PyErr_Clear();
2036 return;
2037 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002038 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002039 if (result == NULL) {
2040 PyErr_WriteUnraisable(threading);
2041 }
2042 else {
2043 Py_DECREF(result);
2044 }
2045 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002046}
2047
2048#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002049int Py_AtExit(void (*func)(void))
2050{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002051 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002052 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002053 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002054 return 0;
2055}
2056
2057static void
2058call_ll_exitfuncs(void)
2059{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002060 while (_PyRuntime.nexitfuncs > 0)
2061 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002062
2063 fflush(stdout);
2064 fflush(stderr);
2065}
2066
Victor Stinnercfc88312018-08-01 16:41:25 +02002067void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002068Py_Exit(int sts)
2069{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002070 if (Py_FinalizeEx() < 0) {
2071 sts = 120;
2072 }
Nick Coghland6009512014-11-20 21:39:37 +10002073
2074 exit(sts);
2075}
2076
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002077static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002078initsigs(void)
2079{
2080#ifdef SIGPIPE
2081 PyOS_setsig(SIGPIPE, SIG_IGN);
2082#endif
2083#ifdef SIGXFZ
2084 PyOS_setsig(SIGXFZ, SIG_IGN);
2085#endif
2086#ifdef SIGXFSZ
2087 PyOS_setsig(SIGXFSZ, SIG_IGN);
2088#endif
2089 PyOS_InitInterrupts(); /* May imply initsignal() */
2090 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002091 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002092 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002093 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002094}
2095
2096
2097/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2098 *
2099 * All of the code in this function must only use async-signal-safe functions,
2100 * listed at `man 7 signal` or
2101 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2102 */
2103void
2104_Py_RestoreSignals(void)
2105{
2106#ifdef SIGPIPE
2107 PyOS_setsig(SIGPIPE, SIG_DFL);
2108#endif
2109#ifdef SIGXFZ
2110 PyOS_setsig(SIGXFZ, SIG_DFL);
2111#endif
2112#ifdef SIGXFSZ
2113 PyOS_setsig(SIGXFSZ, SIG_DFL);
2114#endif
2115}
2116
2117
2118/*
2119 * The file descriptor fd is considered ``interactive'' if either
2120 * a) isatty(fd) is TRUE, or
2121 * b) the -i flag was given, and the filename associated with
2122 * the descriptor is NULL or "<stdin>" or "???".
2123 */
2124int
2125Py_FdIsInteractive(FILE *fp, const char *filename)
2126{
2127 if (isatty((int)fileno(fp)))
2128 return 1;
2129 if (!Py_InteractiveFlag)
2130 return 0;
2131 return (filename == NULL) ||
2132 (strcmp(filename, "<stdin>") == 0) ||
2133 (strcmp(filename, "???") == 0);
2134}
2135
2136
Nick Coghland6009512014-11-20 21:39:37 +10002137/* Wrappers around sigaction() or signal(). */
2138
2139PyOS_sighandler_t
2140PyOS_getsig(int sig)
2141{
2142#ifdef HAVE_SIGACTION
2143 struct sigaction context;
2144 if (sigaction(sig, NULL, &context) == -1)
2145 return SIG_ERR;
2146 return context.sa_handler;
2147#else
2148 PyOS_sighandler_t handler;
2149/* Special signal handling for the secure CRT in Visual Studio 2005 */
2150#if defined(_MSC_VER) && _MSC_VER >= 1400
2151 switch (sig) {
2152 /* Only these signals are valid */
2153 case SIGINT:
2154 case SIGILL:
2155 case SIGFPE:
2156 case SIGSEGV:
2157 case SIGTERM:
2158 case SIGBREAK:
2159 case SIGABRT:
2160 break;
2161 /* Don't call signal() with other values or it will assert */
2162 default:
2163 return SIG_ERR;
2164 }
2165#endif /* _MSC_VER && _MSC_VER >= 1400 */
2166 handler = signal(sig, SIG_IGN);
2167 if (handler != SIG_ERR)
2168 signal(sig, handler);
2169 return handler;
2170#endif
2171}
2172
2173/*
2174 * All of the code in this function must only use async-signal-safe functions,
2175 * listed at `man 7 signal` or
2176 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2177 */
2178PyOS_sighandler_t
2179PyOS_setsig(int sig, PyOS_sighandler_t handler)
2180{
2181#ifdef HAVE_SIGACTION
2182 /* Some code in Modules/signalmodule.c depends on sigaction() being
2183 * used here if HAVE_SIGACTION is defined. Fix that if this code
2184 * changes to invalidate that assumption.
2185 */
2186 struct sigaction context, ocontext;
2187 context.sa_handler = handler;
2188 sigemptyset(&context.sa_mask);
2189 context.sa_flags = 0;
2190 if (sigaction(sig, &context, &ocontext) == -1)
2191 return SIG_ERR;
2192 return ocontext.sa_handler;
2193#else
2194 PyOS_sighandler_t oldhandler;
2195 oldhandler = signal(sig, handler);
2196#ifdef HAVE_SIGINTERRUPT
2197 siginterrupt(sig, 1);
2198#endif
2199 return oldhandler;
2200#endif
2201}
2202
2203#ifdef __cplusplus
2204}
2205#endif