blob: 36fcf61c33d2d355ccf5216b0d846291398d2165 [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 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
51extern wchar_t *Py_GetPath(void);
52
53extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080059static _PyInitError init_sys_streams(void);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Nick Coghland6009512014-11-20 21:39:37 +100061static void call_py_exitfuncs(void);
62static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Global configuration variable declarations are in pydebug.h */
112/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
113int Py_DebugFlag; /* Needed by parser.c */
114int Py_VerboseFlag; /* Needed by import.c */
115int Py_QuietFlag; /* Needed by sysmodule.c */
116int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
117int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
118int Py_OptimizeFlag = 0; /* Needed by compile.c */
119int Py_NoSiteFlag; /* Suppress 'import site' */
120int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
121int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
122int Py_FrozenFlag; /* Needed by getpath.c */
123int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800124int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000125int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
126int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
127int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
128int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700129#ifdef MS_WINDOWS
130int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700131int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700132#endif
Nick Coghland6009512014-11-20 21:39:37 +1000133
Nick Coghland6009512014-11-20 21:39:37 +1000134/* Hack to force loading of object files */
135int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
136 PyOS_mystrnicmp; /* Python/pystrcmp.o */
137
138/* PyModule_GetWarningsModule is no longer necessary as of 2.6
139since _warnings is builtin. This API should not be used. */
140PyObject *
141PyModule_GetWarningsModule(void)
142{
143 return PyImport_ImportModule("warnings");
144}
145
Eric Snowc7ec9982017-05-23 23:00:52 -0700146
Eric Snow1abcf672017-05-23 21:46:51 -0700147/* APIs to access the initialization flags
148 *
149 * Can be called prior to Py_Initialize.
150 */
Nick Coghland6009512014-11-20 21:39:37 +1000151
Eric Snow1abcf672017-05-23 21:46:51 -0700152int
153_Py_IsCoreInitialized(void)
154{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600155 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700156}
Nick Coghland6009512014-11-20 21:39:37 +1000157
158int
159Py_IsInitialized(void)
160{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600161 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000162}
163
164/* Helper to allow an embedding application to override the normal
165 * mechanism that attempts to figure out an appropriate IO encoding
166 */
167
168static char *_Py_StandardStreamEncoding = NULL;
169static char *_Py_StandardStreamErrors = NULL;
170
171int
172Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
173{
174 if (Py_IsInitialized()) {
175 /* This is too late to have any effect */
176 return -1;
177 }
178 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
179 * initialised yet.
180 *
181 * However, the raw memory allocators are initialised appropriately
182 * as C static variables, so _PyMem_RawStrdup is OK even though
183 * Py_Initialize hasn't been called yet.
184 */
185 if (encoding) {
186 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
187 if (!_Py_StandardStreamEncoding) {
188 return -2;
189 }
190 }
191 if (errors) {
192 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
193 if (!_Py_StandardStreamErrors) {
194 if (_Py_StandardStreamEncoding) {
195 PyMem_RawFree(_Py_StandardStreamEncoding);
196 }
197 return -3;
198 }
199 }
Steve Dower39294992016-08-30 21:22:36 -0700200#ifdef MS_WINDOWS
201 if (_Py_StandardStreamEncoding) {
202 /* Overriding the stream encoding implies legacy streams */
203 Py_LegacyWindowsStdioFlag = 1;
204 }
205#endif
Nick Coghland6009512014-11-20 21:39:37 +1000206 return 0;
207}
208
Nick Coghlan6ea41862017-06-11 13:16:15 +1000209
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000210/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
211 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000212 initializations fail, a fatal error is issued and the function does
213 not return. On return, the first thread and interpreter state have
214 been created.
215
216 Locking: you must hold the interpreter lock while calling this.
217 (If the lock has not yet been initialized, that's equivalent to
218 having the lock, but you cannot use multiple threads.)
219
220*/
221
Nick Coghland6009512014-11-20 21:39:37 +1000222static char*
223get_codec_name(const char *encoding)
224{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200225 const char *name_utf8;
226 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000227 PyObject *codec, *name = NULL;
228
229 codec = _PyCodec_Lookup(encoding);
230 if (!codec)
231 goto error;
232
233 name = _PyObject_GetAttrId(codec, &PyId_name);
234 Py_CLEAR(codec);
235 if (!name)
236 goto error;
237
Serhiy Storchaka06515832016-11-20 09:13:07 +0200238 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000239 if (name_utf8 == NULL)
240 goto error;
241 name_str = _PyMem_RawStrdup(name_utf8);
242 Py_DECREF(name);
243 if (name_str == NULL) {
244 PyErr_NoMemory();
245 return NULL;
246 }
247 return name_str;
248
249error:
250 Py_XDECREF(codec);
251 Py_XDECREF(name);
252 return NULL;
253}
254
255static char*
256get_locale_encoding(void)
257{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700258#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000259 char* codeset = nl_langinfo(CODESET);
260 if (!codeset || codeset[0] == '\0') {
261 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
262 return NULL;
263 }
264 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200265#elif defined(__ANDROID__)
266 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000267#else
268 PyErr_SetNone(PyExc_NotImplementedError);
269 return NULL;
270#endif
271}
272
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800273static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700274initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000275{
276 PyObject *importlib;
277 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000278 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800279 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000280
281 /* Import _importlib through its frozen version, _frozen_importlib. */
282 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800283 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000284 }
285 else if (Py_VerboseFlag) {
286 PySys_FormatStderr("import _frozen_importlib # frozen\n");
287 }
288 importlib = PyImport_AddModule("_frozen_importlib");
289 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800290 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000291 }
292 interp->importlib = importlib;
293 Py_INCREF(interp->importlib);
294
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300295 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
296 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800297 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300298 Py_INCREF(interp->import_func);
299
Victor Stinnercd6e6942015-09-18 09:11:57 +0200300 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000301 impmod = PyInit_imp();
302 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800303 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000304 }
305 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200306 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000307 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600308 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800309 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000310 }
311
Victor Stinnercd6e6942015-09-18 09:11:57 +0200312 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000313 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200314 if (value != NULL) {
315 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700316 value = PyObject_CallMethod(importlib,
317 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200318 }
Nick Coghland6009512014-11-20 21:39:37 +1000319 if (value == NULL) {
320 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800321 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000322 }
323 Py_DECREF(value);
324 Py_DECREF(impmod);
325
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800326 err = _PyImportZip_Init();
327 if (_Py_INIT_FAILED(err)) {
328 return err;
329 }
330
331 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000332}
333
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800334static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700335initexternalimport(PyInterpreterState *interp)
336{
337 PyObject *value;
338 value = PyObject_CallMethod(interp->importlib,
339 "_install_external_importers", "");
340 if (value == NULL) {
341 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800342 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700343 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200344 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800345 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700346}
Nick Coghland6009512014-11-20 21:39:37 +1000347
Nick Coghlan6ea41862017-06-11 13:16:15 +1000348/* Helper functions to better handle the legacy C locale
349 *
350 * The legacy C locale assumes ASCII as the default text encoding, which
351 * causes problems not only for the CPython runtime, but also other
352 * components like GNU readline.
353 *
354 * Accordingly, when the CLI detects it, it attempts to coerce it to a
355 * more capable UTF-8 based alternative as follows:
356 *
357 * if (_Py_LegacyLocaleDetected()) {
358 * _Py_CoerceLegacyLocale();
359 * }
360 *
361 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
362 *
363 * Locale coercion also impacts the default error handler for the standard
364 * streams: while the usual default is "strict", the default for the legacy
365 * C locale and for any of the coercion target locales is "surrogateescape".
366 */
367
368int
369_Py_LegacyLocaleDetected(void)
370{
371#ifndef MS_WINDOWS
372 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000373 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
374 * the POSIX locale as a simple alias for the C locale, so
375 * we may also want to check for that explicitly.
376 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000377 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
378 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
379#else
380 /* Windows uses code pages instead of locales, so no locale is legacy */
381 return 0;
382#endif
383}
384
Nick Coghlaneb817952017-06-18 12:29:42 +1000385static const char *_C_LOCALE_WARNING =
386 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
387 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
388 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
389 "locales is recommended.\n";
390
391static int
392_legacy_locale_warnings_enabled(void)
393{
394 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
395 return (coerce_c_locale != NULL &&
396 strncmp(coerce_c_locale, "warn", 5) == 0);
397}
398
399static void
400_emit_stderr_warning_for_legacy_locale(void)
401{
402 if (_legacy_locale_warnings_enabled()) {
403 if (_Py_LegacyLocaleDetected()) {
404 fprintf(stderr, "%s", _C_LOCALE_WARNING);
405 }
406 }
407}
408
Nick Coghlan6ea41862017-06-11 13:16:15 +1000409typedef struct _CandidateLocale {
410 const char *locale_name; /* The locale to try as a coercion target */
411} _LocaleCoercionTarget;
412
413static _LocaleCoercionTarget _TARGET_LOCALES[] = {
414 {"C.UTF-8"},
415 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000416 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000417 {NULL}
418};
419
420static char *
421get_default_standard_stream_error_handler(void)
422{
423 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
424 if (ctype_loc != NULL) {
425 /* "surrogateescape" is the default in the legacy C locale */
426 if (strcmp(ctype_loc, "C") == 0) {
427 return "surrogateescape";
428 }
429
430#ifdef PY_COERCE_C_LOCALE
431 /* "surrogateescape" is the default in locale coercion target locales */
432 const _LocaleCoercionTarget *target = NULL;
433 for (target = _TARGET_LOCALES; target->locale_name; target++) {
434 if (strcmp(ctype_loc, target->locale_name) == 0) {
435 return "surrogateescape";
436 }
437 }
438#endif
439 }
440
441 /* Otherwise return NULL to request the typical default error handler */
442 return NULL;
443}
444
445#ifdef PY_COERCE_C_LOCALE
446static const char *_C_LOCALE_COERCION_WARNING =
447 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
448 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
449
450static void
451_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
452{
453 const char *newloc = target->locale_name;
454
455 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100456 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000457
458 /* Set the relevant locale environment variable */
459 if (setenv("LC_CTYPE", newloc, 1)) {
460 fprintf(stderr,
461 "Error setting LC_CTYPE, skipping C locale coercion\n");
462 return;
463 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000464 if (_legacy_locale_warnings_enabled()) {
465 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
466 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000467
468 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100469 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000470}
471#endif
472
473void
474_Py_CoerceLegacyLocale(void)
475{
476#ifdef PY_COERCE_C_LOCALE
477 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
478 * the locale settings *before* we try to do anything with the command
479 * line arguments. For cross-platform debugging purposes, we also need
480 * to give end users a way to force even scripts that are otherwise
481 * isolated from their environment to use the legacy ASCII-centric C
482 * locale.
483 *
484 * Ignoring -E and -I is safe from a security perspective, as we only use
485 * the setting to turn *off* the implicit locale coercion, and anyone with
486 * access to the process environment already has the ability to set
487 * `LC_ALL=C` to override the C level locale settings anyway.
488 */
489 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
490 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
491 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
492 const char *locale_override = getenv("LC_ALL");
493 if (locale_override == NULL || *locale_override == '\0') {
494 /* LC_ALL is also not set (or is set to an empty string) */
495 const _LocaleCoercionTarget *target = NULL;
496 for (target = _TARGET_LOCALES; target->locale_name; target++) {
497 const char *new_locale = setlocale(LC_CTYPE,
498 target->locale_name);
499 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100500#if !defined(__APPLE__) && !defined(__ANDROID__) && \
501 defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghlan18974c32017-06-30 00:48:14 +1000502 /* Also ensure that nl_langinfo works in this locale */
503 char *codeset = nl_langinfo(CODESET);
504 if (!codeset || *codeset == '\0') {
505 /* CODESET is not set or empty, so skip coercion */
506 new_locale = NULL;
xdegaye1588be62017-11-12 12:45:59 +0100507 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlan18974c32017-06-30 00:48:14 +1000508 continue;
509 }
510#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000511 /* Successfully configured locale, so make it the default */
512 _coerce_default_locale_settings(target);
513 return;
514 }
515 }
516 }
517 }
518 /* No C locale warning here, as Py_Initialize will emit one later */
519#endif
520}
521
xdegaye1588be62017-11-12 12:45:59 +0100522/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
523 * isolate the idiosyncrasies of different libc implementations. It reads the
524 * appropriate environment variable and uses its value to select the locale for
525 * 'category'. */
526char *
527_Py_SetLocaleFromEnv(int category)
528{
529#ifdef __ANDROID__
530 const char *locale;
531 const char **pvar;
532#ifdef PY_COERCE_C_LOCALE
533 const char *coerce_c_locale;
534#endif
535 const char *utf8_locale = "C.UTF-8";
536 const char *env_var_set[] = {
537 "LC_ALL",
538 "LC_CTYPE",
539 "LANG",
540 NULL,
541 };
542
543 /* Android setlocale(category, "") doesn't check the environment variables
544 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
545 * check the environment variables listed in env_var_set. */
546 for (pvar=env_var_set; *pvar; pvar++) {
547 locale = getenv(*pvar);
548 if (locale != NULL && *locale != '\0') {
549 if (strcmp(locale, utf8_locale) == 0 ||
550 strcmp(locale, "en_US.UTF-8") == 0) {
551 return setlocale(category, utf8_locale);
552 }
553 return setlocale(category, "C");
554 }
555 }
556
557 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
558 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
559 * Quote from POSIX section "8.2 Internationalization Variables":
560 * "4. If the LANG environment variable is not set or is set to the empty
561 * string, the implementation-defined default locale shall be used." */
562
563#ifdef PY_COERCE_C_LOCALE
564 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
565 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
566 /* Some other ported code may check the environment variables (e.g. in
567 * extension modules), so we make sure that they match the locale
568 * configuration */
569 if (setenv("LC_CTYPE", utf8_locale, 1)) {
570 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
571 "environment variable to %s\n", utf8_locale);
572 }
573 }
574#endif
575 return setlocale(category, utf8_locale);
576#else /* __ANDROID__ */
577 return setlocale(category, "");
578#endif /* __ANDROID__ */
579}
580
Nick Coghlan6ea41862017-06-11 13:16:15 +1000581
Eric Snow1abcf672017-05-23 21:46:51 -0700582/* Global initializations. Can be undone by Py_Finalize(). Don't
583 call this twice without an intervening Py_Finalize() call.
584
585 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
586 must have a corresponding call to Py_Finalize.
587
588 Locking: you must hold the interpreter lock while calling these APIs.
589 (If the lock has not yet been initialized, that's equivalent to
590 having the lock, but you cannot use multiple threads.)
591
592*/
593
594/* Begin interpreter initialization
595 *
596 * On return, the first thread and interpreter state have been created,
597 * but the compiler, signal handling, multithreading and
598 * multiple interpreter support, and codec infrastructure are not yet
599 * available.
600 *
601 * The import system will support builtin and frozen modules only.
602 * The only supported io is writing to sys.stderr
603 *
604 * If any operation invoked by this function fails, a fatal error is
605 * issued and the function does not return.
606 *
607 * Any code invoked from this function should *not* assume it has access
608 * to the Python C API (unless the API is explicitly listed as being
609 * safe to call without calling Py_Initialize first)
610 */
611
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200612/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700613 * Py_ReadConfig and Py_EndInitialization
614 */
615
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800616_PyInitError
617_Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000618{
619 PyInterpreterState *interp;
620 PyThreadState *tstate;
621 PyObject *bimod, *sysmod, *pstderr;
Eric Snow1abcf672017-05-23 21:46:51 -0700622 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700623 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800624 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000625
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800626 err = _PyRuntime_Initialize();
627 if (_Py_INIT_FAILED(err)) {
628 return err;
629 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600630
Eric Snow1abcf672017-05-23 21:46:51 -0700631 if (config != NULL) {
632 core_config = *config;
633 }
634
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800635 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
636 return _Py_INIT_ERR("Unknown PYTHONMALLOC allocator");
637 }
638
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600639 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800640 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700641 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600642 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800643 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700644 }
645
646 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
647 * threads behave a little more gracefully at interpreter shutdown.
648 * We clobber it here so the new interpreter can start with a clean
649 * slate.
650 *
651 * However, this may still lead to misbehaviour if there are daemon
652 * threads still hanging around from a previous Py_Initialize/Finalize
653 * pair :(
654 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600655 _PyRuntime.finalizing = NULL;
656
Nick Coghlan6ea41862017-06-11 13:16:15 +1000657#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000658 /* Set up the LC_CTYPE locale, so we can obtain
659 the locale's charset without having to switch
660 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100661 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlaneb817952017-06-18 12:29:42 +1000662 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000663#endif
Nick Coghland6009512014-11-20 21:39:37 +1000664
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800665 err = _Py_HashRandomization_Init(&core_config);
666 if (_Py_INIT_FAILED(err)) {
667 return err;
668 }
669
Eric Snow1abcf672017-05-23 21:46:51 -0700670 if (!core_config.use_hash_seed || core_config.hash_seed) {
671 /* Random or non-zero hash seed */
672 Py_HashRandomizationFlag = 1;
673 }
Nick Coghland6009512014-11-20 21:39:37 +1000674
Victor Stinnera7368ac2017-11-15 18:11:45 -0800675 err = _PyInterpreterState_Enable(&_PyRuntime);
676 if (_Py_INIT_FAILED(err)) {
677 return err;
678 }
679
Nick Coghland6009512014-11-20 21:39:37 +1000680 interp = PyInterpreterState_New();
681 if (interp == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800682 return _Py_INIT_ERR("can't make main interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700683 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700684 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000685
686 tstate = PyThreadState_New(interp);
687 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800688 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000689 (void) PyThreadState_Swap(tstate);
690
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000691 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000692 destroying the GIL might fail when it is being referenced from
693 another running thread (see issue #9901).
694 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000695 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000696 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000697 /* Auto-thread-state API */
698 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000699
700 _Py_ReadyTypes();
701
702 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800703 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000704
705 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800706 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000707
708 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800709 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000710
711 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800712 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000713
Eric Snowd393c1b2017-09-14 12:18:12 -0600714 PyObject *modules = PyDict_New();
715 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600717 interp->modules = modules;
718
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800719 err = _PySys_BeginInit(&sysmod);
720 if (_Py_INIT_FAILED(err)) {
721 return err;
722 }
723
Eric Snowd393c1b2017-09-14 12:18:12 -0600724 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800725 if (interp->sysdict == NULL) {
726 return _Py_INIT_ERR("can't initialize sys dict");
727 }
728
Eric Snowd393c1b2017-09-14 12:18:12 -0600729 Py_INCREF(interp->sysdict);
730 PyDict_SetItemString(interp->sysdict, "modules", modules);
731 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000732
733 /* Init Unicode implementation; relies on the codec registry */
734 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800735 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700736
Nick Coghland6009512014-11-20 21:39:37 +1000737 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800738 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000739
740 bimod = _PyBuiltin_Init();
741 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800742 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600743 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000744 interp->builtins = PyModule_GetDict(bimod);
745 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800746 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000747 Py_INCREF(interp->builtins);
748
749 /* initialize builtin exceptions */
750 _PyExc_Init(bimod);
751
Nick Coghland6009512014-11-20 21:39:37 +1000752 /* Set up a preliminary stderr printer until we have enough
753 infrastructure for the io module in place. */
754 pstderr = PyFile_NewStdPrinter(fileno(stderr));
755 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800756 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000757 _PySys_SetObjectId(&PyId_stderr, pstderr);
758 PySys_SetObject("__stderr__", pstderr);
759 Py_DECREF(pstderr);
760
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800761 err = _PyImport_Init();
762 if (_Py_INIT_FAILED(err)) {
763 return err;
764 }
Nick Coghland6009512014-11-20 21:39:37 +1000765
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800766 err = _PyImportHooks_Init();
767 if (_Py_INIT_FAILED(err)) {
768 return err;
769 }
Nick Coghland6009512014-11-20 21:39:37 +1000770
771 /* Initialize _warnings. */
772 _PyWarnings_Init();
773
Eric Snow1abcf672017-05-23 21:46:51 -0700774 /* This call sets up builtin and frozen import support */
775 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800776 err = initimport(interp, sysmod);
777 if (_Py_INIT_FAILED(err)) {
778 return err;
779 }
Eric Snow1abcf672017-05-23 21:46:51 -0700780 }
781
782 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600783 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800784 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700785}
786
Eric Snowc7ec9982017-05-23 23:00:52 -0700787/* Read configuration settings from standard locations
788 *
789 * This function doesn't make any changes to the interpreter state - it
790 * merely populates any missing configuration settings. This allows an
791 * embedding application to completely override a config option by
792 * setting it before calling this function, or else modify the default
793 * setting before passing the fully populated config to Py_EndInitialization.
794 *
795 * More advanced selective initialization tricks are possible by calling
796 * this function multiple times with various preconfigured settings.
797 */
798
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799_PyInitError
800_Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
Eric Snowc7ec9982017-05-23 23:00:52 -0700801{
802 /* Signal handlers are installed by default */
803 if (config->install_signal_handlers < 0) {
804 config->install_signal_handlers = 1;
805 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800806 return _Py_INIT_OK();
Eric Snowc7ec9982017-05-23 23:00:52 -0700807}
808
809/* Update interpreter state based on supplied configuration settings
810 *
811 * After calling this function, most of the restrictions on the interpreter
812 * are lifted. The only remaining incomplete settings are those related
813 * to the main module (sys.argv[0], __main__ metadata)
814 *
815 * Calling this when the interpreter is not initializing, is already
816 * initialized or without a valid current thread state is a fatal error.
817 * Other errors should be reported as normal Python exceptions with a
818 * non-zero return code.
819 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800820_PyInitError
821_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700822{
823 PyInterpreterState *interp;
824 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800825 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700826
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600827 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800828 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700829 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600830 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800831 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 }
833
Eric Snow1abcf672017-05-23 21:46:51 -0700834 /* Get current thread state and interpreter pointer */
835 tstate = PyThreadState_GET();
836 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700838 interp = tstate->interp;
839 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800840 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700841
842 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700843 interp->config = *config;
844
Eric Snow1abcf672017-05-23 21:46:51 -0700845 if (interp->core_config._disable_importlib) {
846 /* Special mode for freeze_importlib: run with no import system
847 *
848 * This means anything which needs support from extension modules
849 * or pure Python code in the standard library won't work.
850 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600851 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800852 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700853 }
854 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000855
Victor Stinner13019fd2015-04-03 13:10:54 +0200856 if (_PyTime_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800857 return _Py_INIT_ERR("can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200858
Eric Snow1abcf672017-05-23 21:46:51 -0700859 /* Finish setting up the sys module and import system */
860 /* GetPath may initialize state that _PySys_EndInit locks
861 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700862 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700863 PySys_SetPath(Py_GetPath());
864 if (_PySys_EndInit(interp->sysdict) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800866
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800867 err = initexternalimport(interp);
868 if (_Py_INIT_FAILED(err)) {
869 return err;
870 }
Nick Coghland6009512014-11-20 21:39:37 +1000871
872 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800873 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800874 if (_Py_INIT_FAILED(err)) {
875 return err;
876 }
Nick Coghland6009512014-11-20 21:39:37 +1000877
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800878 err = initfsencoding(interp);
879 if (_Py_INIT_FAILED(err)) {
880 return err;
881 }
Nick Coghland6009512014-11-20 21:39:37 +1000882
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800883 if (config->install_signal_handlers) {
884 err = initsigs(); /* Signal handling stuff, including initintr() */
885 if (_Py_INIT_FAILED(err)) {
886 return err;
887 }
888 }
Nick Coghland6009512014-11-20 21:39:37 +1000889
Victor Stinnera7368ac2017-11-15 18:11:45 -0800890 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000892
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800893 err = add_main_module(interp);
894 if (_Py_INIT_FAILED(err)) {
895 return err;
896 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800897
898 err = init_sys_streams();
899 if (_Py_INIT_FAILED(err)) {
900 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 }
Nick Coghland6009512014-11-20 21:39:37 +1000902
903 /* Initialize warnings. */
904 if (PySys_HasWarnOptions()) {
905 PyObject *warnings_module = PyImport_ImportModule("warnings");
906 if (warnings_module == NULL) {
907 fprintf(stderr, "'import warnings' failed; traceback:\n");
908 PyErr_Print();
909 }
910 Py_XDECREF(warnings_module);
911 }
912
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600913 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700914
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800915 if (!Py_NoSiteFlag) {
916 err = initsite(); /* Module site */
917 if (_Py_INIT_FAILED(err)) {
918 return err;
919 }
920 }
Eric Snow1abcf672017-05-23 21:46:51 -0700921
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800922 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000923}
924
Eric Snowc7ec9982017-05-23 23:00:52 -0700925#undef _INIT_DEBUG_PRINT
926
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700928_Py_InitializeEx_Private(int install_sigs, int install_importlib)
929{
930 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700931 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800932 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700933
934 /* TODO: Moar config options! */
935 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
936 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700937 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800938
939 err = _Py_InitializeCore(&core_config);
940 if (_Py_INIT_FAILED(err)) {
941 return err;
942 }
943
Eric Snowc7ec9982017-05-23 23:00:52 -0700944 /* TODO: Print any exceptions raised by these operations */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800945 err = _Py_ReadMainInterpreterConfig(&config);
946 if (_Py_INIT_FAILED(err)) {
947 return err;
948 }
949
950 err = _Py_InitializeMainInterpreter(&config);
951 if (_Py_INIT_FAILED(err)) {
952 return err;
953 }
954
955 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700956}
957
958
959void
Nick Coghland6009512014-11-20 21:39:37 +1000960Py_InitializeEx(int install_sigs)
961{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800962 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
963 if (_Py_INIT_FAILED(err)) {
964 _Py_FatalInitError(err);
965 }
Nick Coghland6009512014-11-20 21:39:37 +1000966}
967
968void
969Py_Initialize(void)
970{
971 Py_InitializeEx(1);
972}
973
974
975#ifdef COUNT_ALLOCS
976extern void dump_counts(FILE*);
977#endif
978
979/* Flush stdout and stderr */
980
981static int
982file_is_closed(PyObject *fobj)
983{
984 int r;
985 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
986 if (tmp == NULL) {
987 PyErr_Clear();
988 return 0;
989 }
990 r = PyObject_IsTrue(tmp);
991 Py_DECREF(tmp);
992 if (r < 0)
993 PyErr_Clear();
994 return r > 0;
995}
996
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000997static int
Nick Coghland6009512014-11-20 21:39:37 +1000998flush_std_files(void)
999{
1000 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1001 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1002 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001003 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001004
1005 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001006 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001007 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001008 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009 status = -1;
1010 }
Nick Coghland6009512014-11-20 21:39:37 +10001011 else
1012 Py_DECREF(tmp);
1013 }
1014
1015 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001016 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001018 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 status = -1;
1020 }
Nick Coghland6009512014-11-20 21:39:37 +10001021 else
1022 Py_DECREF(tmp);
1023 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001024
1025 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001026}
1027
1028/* Undo the effect of Py_Initialize().
1029
1030 Beware: if multiple interpreter and/or thread states exist, these
1031 are not wiped out; only the current thread and interpreter state
1032 are deleted. But since everything else is deleted, those other
1033 interpreter and thread states should no longer be used.
1034
1035 (XXX We should do better, e.g. wipe out all interpreters and
1036 threads.)
1037
1038 Locking: as above.
1039
1040*/
1041
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001042int
1043Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001044{
1045 PyInterpreterState *interp;
1046 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001047 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001048
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001050 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001051
1052 wait_for_thread_shutdown();
1053
1054 /* The interpreter is still entirely intact at this point, and the
1055 * exit funcs may be relying on that. In particular, if some thread
1056 * or exit func is still waiting to do an import, the import machinery
1057 * expects Py_IsInitialized() to return true. So don't say the
1058 * interpreter is uninitialized until after the exit funcs have run.
1059 * Note that Threading.py uses an exit func to do a join on all the
1060 * threads created thru it, so this also protects pending imports in
1061 * the threads created via Threading.
1062 */
1063 call_py_exitfuncs();
1064
1065 /* Get current thread state and interpreter pointer */
1066 tstate = PyThreadState_GET();
1067 interp = tstate->interp;
1068
1069 /* Remaining threads (e.g. daemon threads) will automatically exit
1070 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 _PyRuntime.finalizing = tstate;
1072 _PyRuntime.initialized = 0;
1073 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001074
Victor Stinnere0deff32015-03-24 13:46:18 +01001075 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001076 if (flush_std_files() < 0) {
1077 status = -1;
1078 }
Nick Coghland6009512014-11-20 21:39:37 +10001079
1080 /* Disable signal handling */
1081 PyOS_FiniInterrupts();
1082
1083 /* Collect garbage. This may call finalizers; it's nice to call these
1084 * before all modules are destroyed.
1085 * XXX If a __del__ or weakref callback is triggered here, and tries to
1086 * XXX import a module, bad things can happen, because Python no
1087 * XXX longer believes it's initialized.
1088 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1089 * XXX is easy to provoke that way. I've also seen, e.g.,
1090 * XXX Exception exceptions.ImportError: 'No module named sha'
1091 * XXX in <function callback at 0x008F5718> ignored
1092 * XXX but I'm unclear on exactly how that one happens. In any case,
1093 * XXX I haven't seen a real-life report of either of these.
1094 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001095 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001096#ifdef COUNT_ALLOCS
1097 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1098 each collection might release some types from the type
1099 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001100 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001101 /* nothing */;
1102#endif
Eric Snowdae02762017-09-14 00:35:58 -07001103
Nick Coghland6009512014-11-20 21:39:37 +10001104 /* Destroy all modules */
1105 PyImport_Cleanup();
1106
Victor Stinnere0deff32015-03-24 13:46:18 +01001107 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001108 if (flush_std_files() < 0) {
1109 status = -1;
1110 }
Nick Coghland6009512014-11-20 21:39:37 +10001111
1112 /* Collect final garbage. This disposes of cycles created by
1113 * class definitions, for example.
1114 * XXX This is disabled because it caused too many problems. If
1115 * XXX a __del__ or weakref callback triggers here, Python code has
1116 * XXX a hard time running, because even the sys module has been
1117 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1118 * XXX One symptom is a sequence of information-free messages
1119 * XXX coming from threads (if a __del__ or callback is invoked,
1120 * XXX other threads can execute too, and any exception they encounter
1121 * XXX triggers a comedy of errors as subsystem after subsystem
1122 * XXX fails to find what it *expects* to find in sys to help report
1123 * XXX the exception and consequent unexpected failures). I've also
1124 * XXX seen segfaults then, after adding print statements to the
1125 * XXX Python code getting called.
1126 */
1127#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001128 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001129#endif
1130
1131 /* Disable tracemalloc after all Python objects have been destroyed,
1132 so it is possible to use tracemalloc in objects destructor. */
1133 _PyTraceMalloc_Fini();
1134
1135 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1136 _PyImport_Fini();
1137
1138 /* Cleanup typeobject.c's internal caches. */
1139 _PyType_Fini();
1140
1141 /* unload faulthandler module */
1142 _PyFaulthandler_Fini();
1143
1144 /* Debugging stuff */
1145#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001146 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001147#endif
1148 /* dump hash stats */
1149 _PyHash_Fini();
1150
Eric Snowdae02762017-09-14 00:35:58 -07001151#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -08001152 if (interp->core_config.show_ref_count) {
1153 _PyDebug_PrintTotalRefs();
1154 }
Eric Snowdae02762017-09-14 00:35:58 -07001155#endif
Nick Coghland6009512014-11-20 21:39:37 +10001156
1157#ifdef Py_TRACE_REFS
1158 /* Display all objects still alive -- this can invoke arbitrary
1159 * __repr__ overrides, so requires a mostly-intact interpreter.
1160 * Alas, a lot of stuff may still be alive now that will be cleaned
1161 * up later.
1162 */
1163 if (Py_GETENV("PYTHONDUMPREFS"))
1164 _Py_PrintReferences(stderr);
1165#endif /* Py_TRACE_REFS */
1166
1167 /* Clear interpreter state and all thread states. */
1168 PyInterpreterState_Clear(interp);
1169
1170 /* Now we decref the exception classes. After this point nothing
1171 can raise an exception. That's okay, because each Fini() method
1172 below has been checked to make sure no exceptions are ever
1173 raised.
1174 */
1175
1176 _PyExc_Fini();
1177
1178 /* Sundry finalizers */
1179 PyMethod_Fini();
1180 PyFrame_Fini();
1181 PyCFunction_Fini();
1182 PyTuple_Fini();
1183 PyList_Fini();
1184 PySet_Fini();
1185 PyBytes_Fini();
1186 PyByteArray_Fini();
1187 PyLong_Fini();
1188 PyFloat_Fini();
1189 PyDict_Fini();
1190 PySlice_Fini();
1191 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001192 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001193 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001194 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001195
1196 /* Cleanup Unicode implementation */
1197 _PyUnicode_Fini();
1198
1199 /* reset file system default encoding */
1200 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1201 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1202 Py_FileSystemDefaultEncoding = NULL;
1203 }
1204
1205 /* XXX Still allocated:
1206 - various static ad-hoc pointers to interned strings
1207 - int and float free list blocks
1208 - whatever various modules and libraries allocate
1209 */
1210
1211 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1212
1213 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001214 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001215
1216 /* Delete current thread. After this, many C API calls become crashy. */
1217 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001218
Nick Coghland6009512014-11-20 21:39:37 +10001219 PyInterpreterState_Delete(interp);
1220
1221#ifdef Py_TRACE_REFS
1222 /* Display addresses (& refcnts) of all objects still alive.
1223 * An address can be used to find the repr of the object, printed
1224 * above by _Py_PrintReferences.
1225 */
1226 if (Py_GETENV("PYTHONDUMPREFS"))
1227 _Py_PrintReferenceAddresses(stderr);
1228#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001229#ifdef WITH_PYMALLOC
1230 if (_PyMem_PymallocEnabled()) {
1231 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1232 if (opt != NULL && *opt != '\0')
1233 _PyObject_DebugMallocStats(stderr);
1234 }
Nick Coghland6009512014-11-20 21:39:37 +10001235#endif
1236
1237 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001238 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001239 return status;
1240}
1241
1242void
1243Py_Finalize(void)
1244{
1245 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001246}
1247
1248/* Create and initialize a new interpreter and thread, and return the
1249 new thread. This requires that Py_Initialize() has been called
1250 first.
1251
1252 Unsuccessful initialization yields a NULL pointer. Note that *no*
1253 exception information is available even in this case -- the
1254 exception information is held in the thread, and there is no
1255 thread.
1256
1257 Locking: as above.
1258
1259*/
1260
Victor Stinnera7368ac2017-11-15 18:11:45 -08001261static _PyInitError
1262new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001263{
1264 PyInterpreterState *interp;
1265 PyThreadState *tstate, *save_tstate;
1266 PyObject *bimod, *sysmod;
1267
Victor Stinnera7368ac2017-11-15 18:11:45 -08001268 if (!_PyRuntime.initialized) {
1269 return _Py_INIT_ERR("Py_Initialize must be called first");
1270 }
Nick Coghland6009512014-11-20 21:39:37 +10001271
Victor Stinner8a1be612016-03-14 22:07:55 +01001272 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1273 interpreters: disable PyGILState_Check(). */
1274 _PyGILState_check_enabled = 0;
1275
Nick Coghland6009512014-11-20 21:39:37 +10001276 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001277 if (interp == NULL) {
1278 *tstate_p = NULL;
1279 return _Py_INIT_OK();
1280 }
Nick Coghland6009512014-11-20 21:39:37 +10001281
1282 tstate = PyThreadState_New(interp);
1283 if (tstate == NULL) {
1284 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001285 *tstate_p = NULL;
1286 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001287 }
1288
1289 save_tstate = PyThreadState_Swap(tstate);
1290
Eric Snow1abcf672017-05-23 21:46:51 -07001291 /* Copy the current interpreter config into the new interpreter */
1292 if (save_tstate != NULL) {
1293 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001294 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001295 } else {
1296 /* No current thread state, copy from the main interpreter */
1297 PyInterpreterState *main_interp = PyInterpreterState_Main();
1298 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001299 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001300 }
1301
Nick Coghland6009512014-11-20 21:39:37 +10001302 /* XXX The following is lax in error checking */
1303
Eric Snowd393c1b2017-09-14 12:18:12 -06001304 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001305 if (modules == NULL) {
1306 return _Py_INIT_ERR("can't make modules dictionary");
1307 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001308 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001309
Eric Snowd393c1b2017-09-14 12:18:12 -06001310 sysmod = _PyImport_FindBuiltin("sys", modules);
1311 if (sysmod != NULL) {
1312 interp->sysdict = PyModule_GetDict(sysmod);
1313 if (interp->sysdict == NULL)
1314 goto handle_error;
1315 Py_INCREF(interp->sysdict);
1316 PyDict_SetItemString(interp->sysdict, "modules", modules);
1317 PySys_SetPath(Py_GetPath());
1318 _PySys_EndInit(interp->sysdict);
1319 }
1320
1321 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001322 if (bimod != NULL) {
1323 interp->builtins = PyModule_GetDict(bimod);
1324 if (interp->builtins == NULL)
1325 goto handle_error;
1326 Py_INCREF(interp->builtins);
1327 }
1328
1329 /* initialize builtin exceptions */
1330 _PyExc_Init(bimod);
1331
Nick Coghland6009512014-11-20 21:39:37 +10001332 if (bimod != NULL && sysmod != NULL) {
1333 PyObject *pstderr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001334 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001335
Nick Coghland6009512014-11-20 21:39:37 +10001336 /* Set up a preliminary stderr printer until we have enough
1337 infrastructure for the io module in place. */
1338 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001339 if (pstderr == NULL) {
1340 return _Py_INIT_ERR("can't set preliminary stderr");
1341 }
Nick Coghland6009512014-11-20 21:39:37 +10001342 _PySys_SetObjectId(&PyId_stderr, pstderr);
1343 PySys_SetObject("__stderr__", pstderr);
1344 Py_DECREF(pstderr);
1345
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001346 err = _PyImportHooks_Init();
1347 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001348 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001349 }
Nick Coghland6009512014-11-20 21:39:37 +10001350
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001351 err = initimport(interp, sysmod);
1352 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001353 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001354 }
Nick Coghland6009512014-11-20 21:39:37 +10001355
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001356 err = initexternalimport(interp);
1357 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001359 }
Nick Coghland6009512014-11-20 21:39:37 +10001360
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001361 err = initfsencoding(interp);
1362 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001363 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001364 }
1365
Victor Stinnera7368ac2017-11-15 18:11:45 -08001366 err = init_sys_streams();
1367 if (_Py_INIT_FAILED(err)) {
1368 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001369 }
1370
1371 err = add_main_module(interp);
1372 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001373 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001374 }
1375
1376 if (!Py_NoSiteFlag) {
1377 err = initsite();
1378 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001379 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001380 }
1381 }
Nick Coghland6009512014-11-20 21:39:37 +10001382 }
1383
Victor Stinnera7368ac2017-11-15 18:11:45 -08001384 if (PyErr_Occurred()) {
1385 goto handle_error;
1386 }
Nick Coghland6009512014-11-20 21:39:37 +10001387
Victor Stinnera7368ac2017-11-15 18:11:45 -08001388 *tstate_p = tstate;
1389 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001390
Nick Coghland6009512014-11-20 21:39:37 +10001391handle_error:
1392 /* Oops, it didn't work. Undo it all. */
1393
1394 PyErr_PrintEx(0);
1395 PyThreadState_Clear(tstate);
1396 PyThreadState_Swap(save_tstate);
1397 PyThreadState_Delete(tstate);
1398 PyInterpreterState_Delete(interp);
1399
Victor Stinnera7368ac2017-11-15 18:11:45 -08001400 *tstate_p = NULL;
1401 return _Py_INIT_OK();
1402}
1403
1404PyThreadState *
1405Py_NewInterpreter(void)
1406{
1407 PyThreadState *tstate;
1408 _PyInitError err = new_interpreter(&tstate);
1409 if (_Py_INIT_FAILED(err)) {
1410 _Py_FatalInitError(err);
1411 }
1412 return tstate;
1413
Nick Coghland6009512014-11-20 21:39:37 +10001414}
1415
1416/* Delete an interpreter and its last thread. This requires that the
1417 given thread state is current, that the thread has no remaining
1418 frames, and that it is its interpreter's only remaining thread.
1419 It is a fatal error to violate these constraints.
1420
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001421 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001422 everything, regardless.)
1423
1424 Locking: as above.
1425
1426*/
1427
1428void
1429Py_EndInterpreter(PyThreadState *tstate)
1430{
1431 PyInterpreterState *interp = tstate->interp;
1432
1433 if (tstate != PyThreadState_GET())
1434 Py_FatalError("Py_EndInterpreter: thread is not current");
1435 if (tstate->frame != NULL)
1436 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1437
1438 wait_for_thread_shutdown();
1439
1440 if (tstate != interp->tstate_head || tstate->next != NULL)
1441 Py_FatalError("Py_EndInterpreter: not the last thread");
1442
1443 PyImport_Cleanup();
1444 PyInterpreterState_Clear(interp);
1445 PyThreadState_Swap(NULL);
1446 PyInterpreterState_Delete(interp);
1447}
1448
1449#ifdef MS_WINDOWS
1450static wchar_t *progname = L"python";
1451#else
1452static wchar_t *progname = L"python3";
1453#endif
1454
1455void
1456Py_SetProgramName(wchar_t *pn)
1457{
1458 if (pn && *pn)
1459 progname = pn;
1460}
1461
1462wchar_t *
1463Py_GetProgramName(void)
1464{
1465 return progname;
1466}
1467
1468static wchar_t *default_home = NULL;
1469static wchar_t env_home[MAXPATHLEN+1];
1470
1471void
1472Py_SetPythonHome(wchar_t *home)
1473{
1474 default_home = home;
1475}
1476
1477wchar_t *
1478Py_GetPythonHome(void)
1479{
1480 wchar_t *home = default_home;
1481 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1482 char* chome = Py_GETENV("PYTHONHOME");
1483 if (chome) {
1484 size_t size = Py_ARRAY_LENGTH(env_home);
1485 size_t r = mbstowcs(env_home, chome, size);
1486 if (r != (size_t)-1 && r < size)
1487 home = env_home;
1488 }
1489
1490 }
1491 return home;
1492}
1493
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001494/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001495
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001496static _PyInitError
1497add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001498{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001499 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001500 m = PyImport_AddModule("__main__");
1501 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001502 return _Py_INIT_ERR("can't create __main__ module");
1503
Nick Coghland6009512014-11-20 21:39:37 +10001504 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001505 ann_dict = PyDict_New();
1506 if ((ann_dict == NULL) ||
1507 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001509 }
1510 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001511
Nick Coghland6009512014-11-20 21:39:37 +10001512 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1513 PyObject *bimod = PyImport_ImportModule("builtins");
1514 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001516 }
1517 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001519 }
1520 Py_DECREF(bimod);
1521 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001522
Nick Coghland6009512014-11-20 21:39:37 +10001523 /* Main is a little special - imp.is_builtin("__main__") will return
1524 * False, but BuiltinImporter is still the most appropriate initial
1525 * setting for its __loader__ attribute. A more suitable value will
1526 * be set if __main__ gets further initialized later in the startup
1527 * process.
1528 */
1529 loader = PyDict_GetItemString(d, "__loader__");
1530 if (loader == NULL || loader == Py_None) {
1531 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1532 "BuiltinImporter");
1533 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001535 }
1536 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001537 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001538 }
1539 Py_DECREF(loader);
1540 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001542}
1543
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001544static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001545initfsencoding(PyInterpreterState *interp)
1546{
1547 PyObject *codec;
1548
Steve Dowercc16be82016-09-08 10:35:16 -07001549#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001551 Py_FileSystemDefaultEncoding = "mbcs";
1552 Py_FileSystemDefaultEncodeErrors = "replace";
1553 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001554 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001555 Py_FileSystemDefaultEncoding = "utf-8";
1556 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1557 }
1558#else
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001559 if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001560 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561 if (Py_FileSystemDefaultEncoding == NULL) {
1562 return _Py_INIT_ERR("Unable to get the locale encoding");
1563 }
Nick Coghland6009512014-11-20 21:39:37 +10001564
1565 Py_HasFileSystemDefaultEncoding = 0;
1566 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001568 }
Steve Dowercc16be82016-09-08 10:35:16 -07001569#endif
Nick Coghland6009512014-11-20 21:39:37 +10001570
1571 /* the encoding is mbcs, utf-8 or ascii */
1572 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1573 if (!codec) {
1574 /* Such error can only occurs in critical situations: no more
1575 * memory, import a module of the standard library failed,
1576 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001577 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001578 }
1579 Py_DECREF(codec);
1580 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001581 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001582}
1583
1584/* Import the site module (not into __main__ though) */
1585
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001586static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001587initsite(void)
1588{
1589 PyObject *m;
1590 m = PyImport_ImportModule("site");
1591 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001592 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001593 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001594 Py_DECREF(m);
1595 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001596}
1597
Victor Stinner874dbe82015-09-04 17:29:57 +02001598/* Check if a file descriptor is valid or not.
1599 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1600static int
1601is_valid_fd(int fd)
1602{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001603#ifdef __APPLE__
1604 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1605 and the other side of the pipe is closed, dup(1) succeed, whereas
1606 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1607 such error. */
1608 struct stat st;
1609 return (fstat(fd, &st) == 0);
1610#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001611 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001612 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001613 return 0;
1614 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001615 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1616 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1617 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001618 fd2 = dup(fd);
1619 if (fd2 >= 0)
1620 close(fd2);
1621 _Py_END_SUPPRESS_IPH
1622 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001623#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001624}
1625
1626/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001627static PyObject*
1628create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001629 int fd, int write_mode, const char* name,
1630 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001631{
1632 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1633 const char* mode;
1634 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001635 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001636 int buffering, isatty;
1637 _Py_IDENTIFIER(open);
1638 _Py_IDENTIFIER(isatty);
1639 _Py_IDENTIFIER(TextIOWrapper);
1640 _Py_IDENTIFIER(mode);
1641
Victor Stinner874dbe82015-09-04 17:29:57 +02001642 if (!is_valid_fd(fd))
1643 Py_RETURN_NONE;
1644
Nick Coghland6009512014-11-20 21:39:37 +10001645 /* stdin is always opened in buffered mode, first because it shouldn't
1646 make a difference in common use cases, second because TextIOWrapper
1647 depends on the presence of a read1() method which only exists on
1648 buffered streams.
1649 */
1650 if (Py_UnbufferedStdioFlag && write_mode)
1651 buffering = 0;
1652 else
1653 buffering = -1;
1654 if (write_mode)
1655 mode = "wb";
1656 else
1657 mode = "rb";
1658 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1659 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001660 Py_None, Py_None, /* encoding, errors */
1661 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001662 if (buf == NULL)
1663 goto error;
1664
1665 if (buffering) {
1666 _Py_IDENTIFIER(raw);
1667 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1668 if (raw == NULL)
1669 goto error;
1670 }
1671 else {
1672 raw = buf;
1673 Py_INCREF(raw);
1674 }
1675
Steve Dower39294992016-08-30 21:22:36 -07001676#ifdef MS_WINDOWS
1677 /* Windows console IO is always UTF-8 encoded */
1678 if (PyWindowsConsoleIO_Check(raw))
1679 encoding = "utf-8";
1680#endif
1681
Nick Coghland6009512014-11-20 21:39:37 +10001682 text = PyUnicode_FromString(name);
1683 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1684 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001685 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001686 if (res == NULL)
1687 goto error;
1688 isatty = PyObject_IsTrue(res);
1689 Py_DECREF(res);
1690 if (isatty == -1)
1691 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001692 if (Py_UnbufferedStdioFlag)
1693 write_through = Py_True;
1694 else
1695 write_through = Py_False;
1696 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001697 line_buffering = Py_True;
1698 else
1699 line_buffering = Py_False;
1700
1701 Py_CLEAR(raw);
1702 Py_CLEAR(text);
1703
1704#ifdef MS_WINDOWS
1705 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1706 newlines to "\n".
1707 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1708 newline = NULL;
1709#else
1710 /* sys.stdin: split lines at "\n".
1711 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1712 newline = "\n";
1713#endif
1714
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001715 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001716 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001717 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001718 Py_CLEAR(buf);
1719 if (stream == NULL)
1720 goto error;
1721
1722 if (write_mode)
1723 mode = "w";
1724 else
1725 mode = "r";
1726 text = PyUnicode_FromString(mode);
1727 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1728 goto error;
1729 Py_CLEAR(text);
1730 return stream;
1731
1732error:
1733 Py_XDECREF(buf);
1734 Py_XDECREF(stream);
1735 Py_XDECREF(text);
1736 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001737
Victor Stinner874dbe82015-09-04 17:29:57 +02001738 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1739 /* Issue #24891: the file descriptor was closed after the first
1740 is_valid_fd() check was called. Ignore the OSError and set the
1741 stream to None. */
1742 PyErr_Clear();
1743 Py_RETURN_NONE;
1744 }
1745 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001746}
1747
1748/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001749static _PyInitError
1750init_sys_streams(void)
Nick Coghland6009512014-11-20 21:39:37 +10001751{
1752 PyObject *iomod = NULL, *wrapper;
1753 PyObject *bimod = NULL;
1754 PyObject *m;
1755 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001756 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001757 PyObject * encoding_attr;
1758 char *pythonioencoding = NULL, *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001759 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001760
1761 /* Hack to avoid a nasty recursion issue when Python is invoked
1762 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1763 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1764 goto error;
1765 }
1766 Py_DECREF(m);
1767
1768 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1769 goto error;
1770 }
1771 Py_DECREF(m);
1772
1773 if (!(bimod = PyImport_ImportModule("builtins"))) {
1774 goto error;
1775 }
1776
1777 if (!(iomod = PyImport_ImportModule("io"))) {
1778 goto error;
1779 }
1780 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1781 goto error;
1782 }
1783
1784 /* Set builtins.open */
1785 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1786 Py_DECREF(wrapper);
1787 goto error;
1788 }
1789 Py_DECREF(wrapper);
1790
1791 encoding = _Py_StandardStreamEncoding;
1792 errors = _Py_StandardStreamErrors;
1793 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001794 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1795 if (pythonioencoding) {
1796 char *err;
1797 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1798 if (pythonioencoding == NULL) {
1799 PyErr_NoMemory();
1800 goto error;
1801 }
1802 err = strchr(pythonioencoding, ':');
1803 if (err) {
1804 *err = '\0';
1805 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001806 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001807 errors = err;
1808 }
1809 }
1810 if (*pythonioencoding && !encoding) {
1811 encoding = pythonioencoding;
1812 }
1813 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001814 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001815 /* Choose the default error handler based on the current locale */
1816 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001817 }
Nick Coghland6009512014-11-20 21:39:37 +10001818 }
1819
1820 /* Set sys.stdin */
1821 fd = fileno(stdin);
1822 /* Under some conditions stdin, stdout and stderr may not be connected
1823 * and fileno() may point to an invalid file descriptor. For example
1824 * GUI apps don't have valid standard streams by default.
1825 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001826 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1827 if (std == NULL)
1828 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001829 PySys_SetObject("__stdin__", std);
1830 _PySys_SetObjectId(&PyId_stdin, std);
1831 Py_DECREF(std);
1832
1833 /* Set sys.stdout */
1834 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001835 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1836 if (std == NULL)
1837 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001838 PySys_SetObject("__stdout__", std);
1839 _PySys_SetObjectId(&PyId_stdout, std);
1840 Py_DECREF(std);
1841
1842#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1843 /* Set sys.stderr, replaces the preliminary stderr */
1844 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001845 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1846 if (std == NULL)
1847 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001848
1849 /* Same as hack above, pre-import stderr's codec to avoid recursion
1850 when import.c tries to write to stderr in verbose mode. */
1851 encoding_attr = PyObject_GetAttrString(std, "encoding");
1852 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001853 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001854 if (std_encoding != NULL) {
1855 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1856 Py_XDECREF(codec_info);
1857 }
1858 Py_DECREF(encoding_attr);
1859 }
1860 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1861
1862 if (PySys_SetObject("__stderr__", std) < 0) {
1863 Py_DECREF(std);
1864 goto error;
1865 }
1866 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1867 Py_DECREF(std);
1868 goto error;
1869 }
1870 Py_DECREF(std);
1871#endif
1872
Victor Stinnera7368ac2017-11-15 18:11:45 -08001873 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001874
Victor Stinnera7368ac2017-11-15 18:11:45 -08001875error:
1876 res = _Py_INIT_ERR("can't initialize sys standard streams");
1877
1878done:
Nick Coghland6009512014-11-20 21:39:37 +10001879 /* We won't need them anymore. */
1880 if (_Py_StandardStreamEncoding) {
1881 PyMem_RawFree(_Py_StandardStreamEncoding);
1882 _Py_StandardStreamEncoding = NULL;
1883 }
1884 if (_Py_StandardStreamErrors) {
1885 PyMem_RawFree(_Py_StandardStreamErrors);
1886 _Py_StandardStreamErrors = NULL;
1887 }
1888 PyMem_Free(pythonioencoding);
1889 Py_XDECREF(bimod);
1890 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001891 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001892}
1893
1894
Victor Stinner10dc4842015-03-24 12:01:30 +01001895static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001896_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001897{
Victor Stinner10dc4842015-03-24 12:01:30 +01001898 fputc('\n', stderr);
1899 fflush(stderr);
1900
1901 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001902 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001903}
Victor Stinner791da1c2016-03-14 16:53:12 +01001904
1905/* Print the current exception (if an exception is set) with its traceback,
1906 or display the current Python stack.
1907
1908 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1909 called on catastrophic cases.
1910
1911 Return 1 if the traceback was displayed, 0 otherwise. */
1912
1913static int
1914_Py_FatalError_PrintExc(int fd)
1915{
1916 PyObject *ferr, *res;
1917 PyObject *exception, *v, *tb;
1918 int has_tb;
1919
1920 if (PyThreadState_GET() == NULL) {
1921 /* The GIL is released: trying to acquire it is likely to deadlock,
1922 just give up. */
1923 return 0;
1924 }
1925
1926 PyErr_Fetch(&exception, &v, &tb);
1927 if (exception == NULL) {
1928 /* No current exception */
1929 return 0;
1930 }
1931
1932 ferr = _PySys_GetObjectId(&PyId_stderr);
1933 if (ferr == NULL || ferr == Py_None) {
1934 /* sys.stderr is not set yet or set to None,
1935 no need to try to display the exception */
1936 return 0;
1937 }
1938
1939 PyErr_NormalizeException(&exception, &v, &tb);
1940 if (tb == NULL) {
1941 tb = Py_None;
1942 Py_INCREF(tb);
1943 }
1944 PyException_SetTraceback(v, tb);
1945 if (exception == NULL) {
1946 /* PyErr_NormalizeException() failed */
1947 return 0;
1948 }
1949
1950 has_tb = (tb != Py_None);
1951 PyErr_Display(exception, v, tb);
1952 Py_XDECREF(exception);
1953 Py_XDECREF(v);
1954 Py_XDECREF(tb);
1955
1956 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001957 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001958 if (res == NULL)
1959 PyErr_Clear();
1960 else
1961 Py_DECREF(res);
1962
1963 return has_tb;
1964}
1965
Nick Coghland6009512014-11-20 21:39:37 +10001966/* Print fatal error message and abort */
1967
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001968#ifdef MS_WINDOWS
1969static void
1970fatal_output_debug(const char *msg)
1971{
1972 /* buffer of 256 bytes allocated on the stack */
1973 WCHAR buffer[256 / sizeof(WCHAR)];
1974 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1975 size_t msglen;
1976
1977 OutputDebugStringW(L"Fatal Python error: ");
1978
1979 msglen = strlen(msg);
1980 while (msglen) {
1981 size_t i;
1982
1983 if (buflen > msglen) {
1984 buflen = msglen;
1985 }
1986
1987 /* Convert the message to wchar_t. This uses a simple one-to-one
1988 conversion, assuming that the this error message actually uses
1989 ASCII only. If this ceases to be true, we will have to convert. */
1990 for (i=0; i < buflen; ++i) {
1991 buffer[i] = msg[i];
1992 }
1993 buffer[i] = L'\0';
1994 OutputDebugStringW(buffer);
1995
1996 msg += buflen;
1997 msglen -= buflen;
1998 }
1999 OutputDebugStringW(L"\n");
2000}
2001#endif
2002
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002003static void
2004fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002005{
2006 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002007 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002008
2009 if (reentrant) {
2010 /* Py_FatalError() caused a second fatal error.
2011 Example: flush_std_files() raises a recursion error. */
2012 goto exit;
2013 }
2014 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002015
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002016 fprintf(stderr, "Fatal Python error: ");
2017 if (prefix) {
2018 fputs(prefix, stderr);
2019 fputs(": ", stderr);
2020 }
2021 if (msg) {
2022 fputs(msg, stderr);
2023 }
2024 else {
2025 fprintf(stderr, "<message not set>");
2026 }
2027 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002028 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002029
Victor Stinnere0deff32015-03-24 13:46:18 +01002030 /* Print the exception (if an exception is set) with its traceback,
2031 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002032 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002033 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002034 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002035
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002036 /* The main purpose of faulthandler is to display the traceback.
2037 This function already did its best to display a traceback.
2038 Disable faulthandler to prevent writing a second traceback
2039 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002040 _PyFaulthandler_Fini();
2041
Victor Stinner791da1c2016-03-14 16:53:12 +01002042 /* Check if the current Python thread hold the GIL */
2043 if (PyThreadState_GET() != NULL) {
2044 /* Flush sys.stdout and sys.stderr */
2045 flush_std_files();
2046 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002047
Nick Coghland6009512014-11-20 21:39:37 +10002048#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002049 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002050#endif /* MS_WINDOWS */
2051
2052exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002053 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002054#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002055 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002056#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002057 abort();
2058 }
2059 else {
2060 exit(status);
2061 }
2062}
2063
2064void
2065Py_FatalError(const char *msg)
2066{
2067 fatal_error(NULL, msg, -1);
2068}
2069
2070void
2071_Py_FatalInitError(_PyInitError err)
2072{
2073 /* On "user" error: exit with status 1.
2074 For all other errors, call abort(). */
2075 int status = err.user_err ? 1 : -1;
2076 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002077}
2078
2079/* Clean up and exit */
2080
Victor Stinnerd7292b52016-06-17 12:29:00 +02002081# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002082
Nick Coghland6009512014-11-20 21:39:37 +10002083/* For the atexit module. */
2084void _Py_PyAtExit(void (*func)(void))
2085{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002086 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002087}
2088
2089static void
2090call_py_exitfuncs(void)
2091{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002092 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002093 return;
2094
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002095 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002096 PyErr_Clear();
2097}
2098
2099/* Wait until threading._shutdown completes, provided
2100 the threading module was imported in the first place.
2101 The shutdown routine will wait until all non-daemon
2102 "threading" threads have completed. */
2103static void
2104wait_for_thread_shutdown(void)
2105{
Nick Coghland6009512014-11-20 21:39:37 +10002106 _Py_IDENTIFIER(_shutdown);
2107 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002108 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002109 if (threading == NULL) {
2110 /* threading not imported */
2111 PyErr_Clear();
2112 return;
2113 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002114 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002115 if (result == NULL) {
2116 PyErr_WriteUnraisable(threading);
2117 }
2118 else {
2119 Py_DECREF(result);
2120 }
2121 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002122}
2123
2124#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002125int Py_AtExit(void (*func)(void))
2126{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002127 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002128 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002129 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002130 return 0;
2131}
2132
2133static void
2134call_ll_exitfuncs(void)
2135{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002136 while (_PyRuntime.nexitfuncs > 0)
2137 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002138
2139 fflush(stdout);
2140 fflush(stderr);
2141}
2142
2143void
2144Py_Exit(int sts)
2145{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002146 if (Py_FinalizeEx() < 0) {
2147 sts = 120;
2148 }
Nick Coghland6009512014-11-20 21:39:37 +10002149
2150 exit(sts);
2151}
2152
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002153static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002154initsigs(void)
2155{
2156#ifdef SIGPIPE
2157 PyOS_setsig(SIGPIPE, SIG_IGN);
2158#endif
2159#ifdef SIGXFZ
2160 PyOS_setsig(SIGXFZ, SIG_IGN);
2161#endif
2162#ifdef SIGXFSZ
2163 PyOS_setsig(SIGXFSZ, SIG_IGN);
2164#endif
2165 PyOS_InitInterrupts(); /* May imply initsignal() */
2166 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002167 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002168 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002169 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002170}
2171
2172
2173/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2174 *
2175 * All of the code in this function must only use async-signal-safe functions,
2176 * listed at `man 7 signal` or
2177 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2178 */
2179void
2180_Py_RestoreSignals(void)
2181{
2182#ifdef SIGPIPE
2183 PyOS_setsig(SIGPIPE, SIG_DFL);
2184#endif
2185#ifdef SIGXFZ
2186 PyOS_setsig(SIGXFZ, SIG_DFL);
2187#endif
2188#ifdef SIGXFSZ
2189 PyOS_setsig(SIGXFSZ, SIG_DFL);
2190#endif
2191}
2192
2193
2194/*
2195 * The file descriptor fd is considered ``interactive'' if either
2196 * a) isatty(fd) is TRUE, or
2197 * b) the -i flag was given, and the filename associated with
2198 * the descriptor is NULL or "<stdin>" or "???".
2199 */
2200int
2201Py_FdIsInteractive(FILE *fp, const char *filename)
2202{
2203 if (isatty((int)fileno(fp)))
2204 return 1;
2205 if (!Py_InteractiveFlag)
2206 return 0;
2207 return (filename == NULL) ||
2208 (strcmp(filename, "<stdin>") == 0) ||
2209 (strcmp(filename, "???") == 0);
2210}
2211
2212
Nick Coghland6009512014-11-20 21:39:37 +10002213/* Wrappers around sigaction() or signal(). */
2214
2215PyOS_sighandler_t
2216PyOS_getsig(int sig)
2217{
2218#ifdef HAVE_SIGACTION
2219 struct sigaction context;
2220 if (sigaction(sig, NULL, &context) == -1)
2221 return SIG_ERR;
2222 return context.sa_handler;
2223#else
2224 PyOS_sighandler_t handler;
2225/* Special signal handling for the secure CRT in Visual Studio 2005 */
2226#if defined(_MSC_VER) && _MSC_VER >= 1400
2227 switch (sig) {
2228 /* Only these signals are valid */
2229 case SIGINT:
2230 case SIGILL:
2231 case SIGFPE:
2232 case SIGSEGV:
2233 case SIGTERM:
2234 case SIGBREAK:
2235 case SIGABRT:
2236 break;
2237 /* Don't call signal() with other values or it will assert */
2238 default:
2239 return SIG_ERR;
2240 }
2241#endif /* _MSC_VER && _MSC_VER >= 1400 */
2242 handler = signal(sig, SIG_IGN);
2243 if (handler != SIG_ERR)
2244 signal(sig, handler);
2245 return handler;
2246#endif
2247}
2248
2249/*
2250 * All of the code in this function must only use async-signal-safe functions,
2251 * listed at `man 7 signal` or
2252 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2253 */
2254PyOS_sighandler_t
2255PyOS_setsig(int sig, PyOS_sighandler_t handler)
2256{
2257#ifdef HAVE_SIGACTION
2258 /* Some code in Modules/signalmodule.c depends on sigaction() being
2259 * used here if HAVE_SIGACTION is defined. Fix that if this code
2260 * changes to invalidate that assumption.
2261 */
2262 struct sigaction context, ocontext;
2263 context.sa_handler = handler;
2264 sigemptyset(&context.sa_mask);
2265 context.sa_flags = 0;
2266 if (sigaction(sig, &context, &ocontext) == -1)
2267 return SIG_ERR;
2268 return ocontext.sa_handler;
2269#else
2270 PyOS_sighandler_t oldhandler;
2271 oldhandler = signal(sig, handler);
2272#ifdef HAVE_SIGINTERRUPT
2273 siginterrupt(sig, 1);
2274#endif
2275 return oldhandler;
2276#endif
2277}
2278
2279#ifdef __cplusplus
2280}
2281#endif