blob: eaa7b7f459953abf482783dd567fe1478acb9d17 [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 */
7#include "grammar.h"
8#include "node.h"
9#include "token.h"
10#include "parsetok.h"
11#include "errcode.h"
12#include "code.h"
13#include "symtable.h"
14#include "ast.h"
15#include "marshal.h"
16#include "osdefs.h"
17#include <locale.h>
18
19#ifdef HAVE_SIGNAL_H
20#include <signal.h>
21#endif
22
23#ifdef MS_WINDOWS
24#include "malloc.h" /* for alloca */
25#endif
26
27#ifdef HAVE_LANGINFO_H
28#include <langinfo.h>
29#endif
30
31#ifdef MS_WINDOWS
32#undef BYTE
33#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070034
35extern PyTypeObject PyWindowsConsoleIO_Type;
36#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
39_Py_IDENTIFIER(flush);
40_Py_IDENTIFIER(name);
41_Py_IDENTIFIER(stdin);
42_Py_IDENTIFIER(stdout);
43_Py_IDENTIFIER(stderr);
44
45#ifdef __cplusplus
46extern "C" {
47#endif
48
49extern wchar_t *Py_GetPath(void);
50
51extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
54static void initmain(PyInterpreterState *interp);
55static int initfsencoding(PyInterpreterState *interp);
56static void initsite(void);
57static int initstdio(void);
58static void initsigs(void);
59static void call_py_exitfuncs(void);
60static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
67extern int _PyFaulthandler_Init(void);
68extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
70extern int _PyTraceMalloc_Init(void);
71extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
74#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
79/* Global configuration variable declarations are in pydebug.h */
80/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
81int Py_DebugFlag; /* Needed by parser.c */
82int Py_VerboseFlag; /* Needed by import.c */
83int Py_QuietFlag; /* Needed by sysmodule.c */
84int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
85int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
86int Py_OptimizeFlag = 0; /* Needed by compile.c */
87int Py_NoSiteFlag; /* Suppress 'import site' */
88int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
89int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
90int Py_FrozenFlag; /* Needed by getpath.c */
91int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080092int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
94int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
95int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
96int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070097#ifdef MS_WINDOWS
98int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070099int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700100#endif
Nick Coghland6009512014-11-20 21:39:37 +1000101
102PyThreadState *_Py_Finalizing = NULL;
103
104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
121int _Py_CoreInitialized = 0;
122int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000123
Eric Snow1abcf672017-05-23 21:46:51 -0700124int
125_Py_IsCoreInitialized(void)
126{
127 return _Py_CoreInitialized;
128}
Nick Coghland6009512014-11-20 21:39:37 +1000129
130int
131Py_IsInitialized(void)
132{
Eric Snow1abcf672017-05-23 21:46:51 -0700133 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000134}
135
136/* Helper to allow an embedding application to override the normal
137 * mechanism that attempts to figure out an appropriate IO encoding
138 */
139
140static char *_Py_StandardStreamEncoding = NULL;
141static char *_Py_StandardStreamErrors = NULL;
142
143int
144Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
145{
146 if (Py_IsInitialized()) {
147 /* This is too late to have any effect */
148 return -1;
149 }
150 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
151 * initialised yet.
152 *
153 * However, the raw memory allocators are initialised appropriately
154 * as C static variables, so _PyMem_RawStrdup is OK even though
155 * Py_Initialize hasn't been called yet.
156 */
157 if (encoding) {
158 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
159 if (!_Py_StandardStreamEncoding) {
160 return -2;
161 }
162 }
163 if (errors) {
164 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
165 if (!_Py_StandardStreamErrors) {
166 if (_Py_StandardStreamEncoding) {
167 PyMem_RawFree(_Py_StandardStreamEncoding);
168 }
169 return -3;
170 }
171 }
Steve Dower39294992016-08-30 21:22:36 -0700172#ifdef MS_WINDOWS
173 if (_Py_StandardStreamEncoding) {
174 /* Overriding the stream encoding implies legacy streams */
175 Py_LegacyWindowsStdioFlag = 1;
176 }
177#endif
Nick Coghland6009512014-11-20 21:39:37 +1000178 return 0;
179}
180
Nick Coghlan6ea41862017-06-11 13:16:15 +1000181
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000182/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
183 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000184 initializations fail, a fatal error is issued and the function does
185 not return. On return, the first thread and interpreter state have
186 been created.
187
188 Locking: you must hold the interpreter lock while calling this.
189 (If the lock has not yet been initialized, that's equivalent to
190 having the lock, but you cannot use multiple threads.)
191
192*/
193
194static int
195add_flag(int flag, const char *envs)
196{
197 int env = atoi(envs);
198 if (flag < env)
199 flag = env;
200 if (flag < 1)
201 flag = 1;
202 return flag;
203}
204
205static char*
206get_codec_name(const char *encoding)
207{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200208 const char *name_utf8;
209 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000210 PyObject *codec, *name = NULL;
211
212 codec = _PyCodec_Lookup(encoding);
213 if (!codec)
214 goto error;
215
216 name = _PyObject_GetAttrId(codec, &PyId_name);
217 Py_CLEAR(codec);
218 if (!name)
219 goto error;
220
Serhiy Storchaka06515832016-11-20 09:13:07 +0200221 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000222 if (name_utf8 == NULL)
223 goto error;
224 name_str = _PyMem_RawStrdup(name_utf8);
225 Py_DECREF(name);
226 if (name_str == NULL) {
227 PyErr_NoMemory();
228 return NULL;
229 }
230 return name_str;
231
232error:
233 Py_XDECREF(codec);
234 Py_XDECREF(name);
235 return NULL;
236}
237
238static char*
239get_locale_encoding(void)
240{
241#ifdef MS_WINDOWS
242 char codepage[100];
243 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
244 return get_codec_name(codepage);
245#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
246 char* codeset = nl_langinfo(CODESET);
247 if (!codeset || codeset[0] == '\0') {
248 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
249 return NULL;
250 }
251 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200252#elif defined(__ANDROID__)
253 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000254#else
255 PyErr_SetNone(PyExc_NotImplementedError);
256 return NULL;
257#endif
258}
259
260static void
Eric Snow1abcf672017-05-23 21:46:51 -0700261initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000262{
263 PyObject *importlib;
264 PyObject *impmod;
265 PyObject *sys_modules;
266 PyObject *value;
267
268 /* Import _importlib through its frozen version, _frozen_importlib. */
269 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
270 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
271 }
272 else if (Py_VerboseFlag) {
273 PySys_FormatStderr("import _frozen_importlib # frozen\n");
274 }
275 importlib = PyImport_AddModule("_frozen_importlib");
276 if (importlib == NULL) {
277 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
278 "sys.modules");
279 }
280 interp->importlib = importlib;
281 Py_INCREF(interp->importlib);
282
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300283 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
284 if (interp->import_func == NULL)
285 Py_FatalError("Py_Initialize: __import__ not found");
286 Py_INCREF(interp->import_func);
287
Victor Stinnercd6e6942015-09-18 09:11:57 +0200288 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000289 impmod = PyInit_imp();
290 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200291 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000292 }
293 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200294 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000295 }
296 sys_modules = PyImport_GetModuleDict();
297 if (Py_VerboseFlag) {
298 PySys_FormatStderr("import sys # builtin\n");
299 }
300 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
301 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
302 }
303
Victor Stinnercd6e6942015-09-18 09:11:57 +0200304 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000305 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200306 if (value != NULL) {
307 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700308 value = PyObject_CallMethod(importlib,
309 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200310 }
Nick Coghland6009512014-11-20 21:39:37 +1000311 if (value == NULL) {
312 PyErr_Print();
313 Py_FatalError("Py_Initialize: importlib install failed");
314 }
315 Py_DECREF(value);
316 Py_DECREF(impmod);
317
318 _PyImportZip_Init();
319}
320
Eric Snow1abcf672017-05-23 21:46:51 -0700321static void
322initexternalimport(PyInterpreterState *interp)
323{
324 PyObject *value;
325 value = PyObject_CallMethod(interp->importlib,
326 "_install_external_importers", "");
327 if (value == NULL) {
328 PyErr_Print();
329 Py_FatalError("Py_EndInitialization: external importer setup failed");
330 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200331 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700332}
Nick Coghland6009512014-11-20 21:39:37 +1000333
Nick Coghlan6ea41862017-06-11 13:16:15 +1000334/* Helper functions to better handle the legacy C locale
335 *
336 * The legacy C locale assumes ASCII as the default text encoding, which
337 * causes problems not only for the CPython runtime, but also other
338 * components like GNU readline.
339 *
340 * Accordingly, when the CLI detects it, it attempts to coerce it to a
341 * more capable UTF-8 based alternative as follows:
342 *
343 * if (_Py_LegacyLocaleDetected()) {
344 * _Py_CoerceLegacyLocale();
345 * }
346 *
347 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
348 *
349 * Locale coercion also impacts the default error handler for the standard
350 * streams: while the usual default is "strict", the default for the legacy
351 * C locale and for any of the coercion target locales is "surrogateescape".
352 */
353
354int
355_Py_LegacyLocaleDetected(void)
356{
357#ifndef MS_WINDOWS
358 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000359 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
360 * the POSIX locale as a simple alias for the C locale, so
361 * we may also want to check for that explicitly.
362 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000363 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
364 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
365#else
366 /* Windows uses code pages instead of locales, so no locale is legacy */
367 return 0;
368#endif
369}
370
Nick Coghlaneb817952017-06-18 12:29:42 +1000371static const char *_C_LOCALE_WARNING =
372 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
373 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
374 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
375 "locales is recommended.\n";
376
377static int
378_legacy_locale_warnings_enabled(void)
379{
380 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
381 return (coerce_c_locale != NULL &&
382 strncmp(coerce_c_locale, "warn", 5) == 0);
383}
384
385static void
386_emit_stderr_warning_for_legacy_locale(void)
387{
388 if (_legacy_locale_warnings_enabled()) {
389 if (_Py_LegacyLocaleDetected()) {
390 fprintf(stderr, "%s", _C_LOCALE_WARNING);
391 }
392 }
393}
394
Nick Coghlan6ea41862017-06-11 13:16:15 +1000395typedef struct _CandidateLocale {
396 const char *locale_name; /* The locale to try as a coercion target */
397} _LocaleCoercionTarget;
398
399static _LocaleCoercionTarget _TARGET_LOCALES[] = {
400 {"C.UTF-8"},
401 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000402 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000403 {NULL}
404};
405
406static char *
407get_default_standard_stream_error_handler(void)
408{
409 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
410 if (ctype_loc != NULL) {
411 /* "surrogateescape" is the default in the legacy C locale */
412 if (strcmp(ctype_loc, "C") == 0) {
413 return "surrogateescape";
414 }
415
416#ifdef PY_COERCE_C_LOCALE
417 /* "surrogateescape" is the default in locale coercion target locales */
418 const _LocaleCoercionTarget *target = NULL;
419 for (target = _TARGET_LOCALES; target->locale_name; target++) {
420 if (strcmp(ctype_loc, target->locale_name) == 0) {
421 return "surrogateescape";
422 }
423 }
424#endif
425 }
426
427 /* Otherwise return NULL to request the typical default error handler */
428 return NULL;
429}
430
431#ifdef PY_COERCE_C_LOCALE
432static const char *_C_LOCALE_COERCION_WARNING =
433 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
434 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
435
436static void
437_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
438{
439 const char *newloc = target->locale_name;
440
441 /* Reset locale back to currently configured defaults */
442 setlocale(LC_ALL, "");
443
444 /* Set the relevant locale environment variable */
445 if (setenv("LC_CTYPE", newloc, 1)) {
446 fprintf(stderr,
447 "Error setting LC_CTYPE, skipping C locale coercion\n");
448 return;
449 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000450 if (_legacy_locale_warnings_enabled()) {
451 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
452 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453
454 /* Reconfigure with the overridden environment variables */
455 setlocale(LC_ALL, "");
456}
457#endif
458
459void
460_Py_CoerceLegacyLocale(void)
461{
462#ifdef PY_COERCE_C_LOCALE
463 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
464 * the locale settings *before* we try to do anything with the command
465 * line arguments. For cross-platform debugging purposes, we also need
466 * to give end users a way to force even scripts that are otherwise
467 * isolated from their environment to use the legacy ASCII-centric C
468 * locale.
469 *
470 * Ignoring -E and -I is safe from a security perspective, as we only use
471 * the setting to turn *off* the implicit locale coercion, and anyone with
472 * access to the process environment already has the ability to set
473 * `LC_ALL=C` to override the C level locale settings anyway.
474 */
475 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
476 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
477 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
478 const char *locale_override = getenv("LC_ALL");
479 if (locale_override == NULL || *locale_override == '\0') {
480 /* LC_ALL is also not set (or is set to an empty string) */
481 const _LocaleCoercionTarget *target = NULL;
482 for (target = _TARGET_LOCALES; target->locale_name; target++) {
483 const char *new_locale = setlocale(LC_CTYPE,
484 target->locale_name);
485 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000486#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
487 /* Also ensure that nl_langinfo works in this locale */
488 char *codeset = nl_langinfo(CODESET);
489 if (!codeset || *codeset == '\0') {
490 /* CODESET is not set or empty, so skip coercion */
491 new_locale = NULL;
492 setlocale(LC_CTYPE, "");
493 continue;
494 }
495#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000496 /* Successfully configured locale, so make it the default */
497 _coerce_default_locale_settings(target);
498 return;
499 }
500 }
501 }
502 }
503 /* No C locale warning here, as Py_Initialize will emit one later */
504#endif
505}
506
507
Eric Snow1abcf672017-05-23 21:46:51 -0700508/* Global initializations. Can be undone by Py_Finalize(). Don't
509 call this twice without an intervening Py_Finalize() call.
510
511 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
512 must have a corresponding call to Py_Finalize.
513
514 Locking: you must hold the interpreter lock while calling these APIs.
515 (If the lock has not yet been initialized, that's equivalent to
516 having the lock, but you cannot use multiple threads.)
517
518*/
519
520/* Begin interpreter initialization
521 *
522 * On return, the first thread and interpreter state have been created,
523 * but the compiler, signal handling, multithreading and
524 * multiple interpreter support, and codec infrastructure are not yet
525 * available.
526 *
527 * The import system will support builtin and frozen modules only.
528 * The only supported io is writing to sys.stderr
529 *
530 * If any operation invoked by this function fails, a fatal error is
531 * issued and the function does not return.
532 *
533 * Any code invoked from this function should *not* assume it has access
534 * to the Python C API (unless the API is explicitly listed as being
535 * safe to call without calling Py_Initialize first)
536 */
537
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200538/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700539 * Py_ReadConfig and Py_EndInitialization
540 */
541
542void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000543{
544 PyInterpreterState *interp;
545 PyThreadState *tstate;
546 PyObject *bimod, *sysmod, *pstderr;
547 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700548 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700549 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000550
Eric Snow1abcf672017-05-23 21:46:51 -0700551 if (config != NULL) {
552 core_config = *config;
553 }
554
555 if (_Py_Initialized) {
556 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
557 }
558 if (_Py_CoreInitialized) {
559 Py_FatalError("Py_InitializeCore: runtime core already initialized");
560 }
561
562 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
563 * threads behave a little more gracefully at interpreter shutdown.
564 * We clobber it here so the new interpreter can start with a clean
565 * slate.
566 *
567 * However, this may still lead to misbehaviour if there are daemon
568 * threads still hanging around from a previous Py_Initialize/Finalize
569 * pair :(
570 */
Nick Coghland6009512014-11-20 21:39:37 +1000571 _Py_Finalizing = NULL;
572
Nick Coghlan6ea41862017-06-11 13:16:15 +1000573#ifdef __ANDROID__
574 /* Passing "" to setlocale() on Android requests the C locale rather
575 * than checking environment variables, so request C.UTF-8 explicitly
576 */
577 setlocale(LC_CTYPE, "C.UTF-8");
578#else
579#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000580 /* Set up the LC_CTYPE locale, so we can obtain
581 the locale's charset without having to switch
582 locales. */
583 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000584 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000585#endif
Nick Coghland6009512014-11-20 21:39:37 +1000586#endif
587
588 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
589 Py_DebugFlag = add_flag(Py_DebugFlag, p);
590 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
591 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
592 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
593 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
594 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
595 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700596 /* The variable is only tested for existence here;
597 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000598 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
599 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700600#ifdef MS_WINDOWS
601 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
602 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700603 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
604 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700605#endif
Nick Coghland6009512014-11-20 21:39:37 +1000606
Eric Snow1abcf672017-05-23 21:46:51 -0700607 _Py_HashRandomization_Init(&core_config);
608 if (!core_config.use_hash_seed || core_config.hash_seed) {
609 /* Random or non-zero hash seed */
610 Py_HashRandomizationFlag = 1;
611 }
Nick Coghland6009512014-11-20 21:39:37 +1000612
Eric Snowe3774162017-05-22 19:46:40 -0700613 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000614 interp = PyInterpreterState_New();
615 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700616 Py_FatalError("Py_InitializeCore: can't make main interpreter");
617 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700618 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000619
620 tstate = PyThreadState_New(interp);
621 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700622 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000623 (void) PyThreadState_Swap(tstate);
624
625#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000626 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000627 destroying the GIL might fail when it is being referenced from
628 another running thread (see issue #9901).
629 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000630 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000631 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000632 /* Auto-thread-state API */
633 _PyGILState_Init(interp, tstate);
634#endif /* WITH_THREAD */
635
636 _Py_ReadyTypes();
637
638 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700639 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000640
641 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700642 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000643
644 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700645 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000646
647 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700648 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000649
650 interp->modules = PyDict_New();
651 if (interp->modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700652 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000653
654 /* Init Unicode implementation; relies on the codec registry */
655 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700656 Py_FatalError("Py_InitializeCore: can't initialize unicode");
657
Nick Coghland6009512014-11-20 21:39:37 +1000658 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700659 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000660
661 bimod = _PyBuiltin_Init();
662 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700663 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Nick Coghland6009512014-11-20 21:39:37 +1000664 _PyImport_FixupBuiltin(bimod, "builtins");
665 interp->builtins = PyModule_GetDict(bimod);
666 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700667 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000668 Py_INCREF(interp->builtins);
669
670 /* initialize builtin exceptions */
671 _PyExc_Init(bimod);
672
Eric Snow6b4be192017-05-22 21:36:03 -0700673 sysmod = _PySys_BeginInit();
Nick Coghland6009512014-11-20 21:39:37 +1000674 if (sysmod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700675 Py_FatalError("Py_InitializeCore: can't initialize sys");
Nick Coghland6009512014-11-20 21:39:37 +1000676 interp->sysdict = PyModule_GetDict(sysmod);
677 if (interp->sysdict == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700678 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
Nick Coghland6009512014-11-20 21:39:37 +1000679 Py_INCREF(interp->sysdict);
680 _PyImport_FixupBuiltin(sysmod, "sys");
Nick Coghland6009512014-11-20 21:39:37 +1000681 PyDict_SetItemString(interp->sysdict, "modules",
682 interp->modules);
683
684 /* Set up a preliminary stderr printer until we have enough
685 infrastructure for the io module in place. */
686 pstderr = PyFile_NewStdPrinter(fileno(stderr));
687 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700688 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000689 _PySys_SetObjectId(&PyId_stderr, pstderr);
690 PySys_SetObject("__stderr__", pstderr);
691 Py_DECREF(pstderr);
692
693 _PyImport_Init();
694
695 _PyImportHooks_Init();
696
697 /* Initialize _warnings. */
698 _PyWarnings_Init();
699
Eric Snow1abcf672017-05-23 21:46:51 -0700700 /* This call sets up builtin and frozen import support */
701 if (!interp->core_config._disable_importlib) {
702 initimport(interp, sysmod);
703 }
704
705 /* Only when we get here is the runtime core fully initialized */
706 _Py_CoreInitialized = 1;
707}
708
Eric Snowc7ec9982017-05-23 23:00:52 -0700709/* Read configuration settings from standard locations
710 *
711 * This function doesn't make any changes to the interpreter state - it
712 * merely populates any missing configuration settings. This allows an
713 * embedding application to completely override a config option by
714 * setting it before calling this function, or else modify the default
715 * setting before passing the fully populated config to Py_EndInitialization.
716 *
717 * More advanced selective initialization tricks are possible by calling
718 * this function multiple times with various preconfigured settings.
719 */
720
721int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
722{
723 /* Signal handlers are installed by default */
724 if (config->install_signal_handlers < 0) {
725 config->install_signal_handlers = 1;
726 }
727
728 return 0;
729}
730
731/* Update interpreter state based on supplied configuration settings
732 *
733 * After calling this function, most of the restrictions on the interpreter
734 * are lifted. The only remaining incomplete settings are those related
735 * to the main module (sys.argv[0], __main__ metadata)
736 *
737 * Calling this when the interpreter is not initializing, is already
738 * initialized or without a valid current thread state is a fatal error.
739 * Other errors should be reported as normal Python exceptions with a
740 * non-zero return code.
741 */
742int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700743{
744 PyInterpreterState *interp;
745 PyThreadState *tstate;
746
Eric Snowc7ec9982017-05-23 23:00:52 -0700747 if (!_Py_CoreInitialized) {
748 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
749 }
750 if (_Py_Initialized) {
751 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
752 }
753
Eric Snow1abcf672017-05-23 21:46:51 -0700754 /* Get current thread state and interpreter pointer */
755 tstate = PyThreadState_GET();
756 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700757 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700758 interp = tstate->interp;
759 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700760 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700761
762 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700763 interp->config = *config;
764
Eric Snow1abcf672017-05-23 21:46:51 -0700765 if (interp->core_config._disable_importlib) {
766 /* Special mode for freeze_importlib: run with no import system
767 *
768 * This means anything which needs support from extension modules
769 * or pure Python code in the standard library won't work.
770 */
771 _Py_Initialized = 1;
772 return 0;
773 }
774 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000775
Victor Stinner13019fd2015-04-03 13:10:54 +0200776 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700777 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200778
Eric Snow1abcf672017-05-23 21:46:51 -0700779 /* Finish setting up the sys module and import system */
780 /* GetPath may initialize state that _PySys_EndInit locks
781 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700782 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700783 PySys_SetPath(Py_GetPath());
784 if (_PySys_EndInit(interp->sysdict) < 0)
785 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700786 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000787
788 /* initialize the faulthandler module */
789 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700790 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000791
Nick Coghland6009512014-11-20 21:39:37 +1000792 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700793 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000794
Eric Snowc7ec9982017-05-23 23:00:52 -0700795 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000796 initsigs(); /* Signal handling stuff, including initintr() */
797
798 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700799 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000800
801 initmain(interp); /* Module __main__ */
802 if (initstdio() < 0)
803 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700804 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000805
806 /* Initialize warnings. */
807 if (PySys_HasWarnOptions()) {
808 PyObject *warnings_module = PyImport_ImportModule("warnings");
809 if (warnings_module == NULL) {
810 fprintf(stderr, "'import warnings' failed; traceback:\n");
811 PyErr_Print();
812 }
813 Py_XDECREF(warnings_module);
814 }
815
Eric Snow1abcf672017-05-23 21:46:51 -0700816 _Py_Initialized = 1;
817
Nick Coghland6009512014-11-20 21:39:37 +1000818 if (!Py_NoSiteFlag)
819 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700820
Eric Snowc7ec9982017-05-23 23:00:52 -0700821 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000822}
823
Eric Snowc7ec9982017-05-23 23:00:52 -0700824#undef _INIT_DEBUG_PRINT
825
Nick Coghland6009512014-11-20 21:39:37 +1000826void
Eric Snow1abcf672017-05-23 21:46:51 -0700827_Py_InitializeEx_Private(int install_sigs, int install_importlib)
828{
829 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700830 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700831
832 /* TODO: Moar config options! */
833 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
834 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700835 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700836 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700837 /* TODO: Print any exceptions raised by these operations */
838 if (_Py_ReadMainInterpreterConfig(&config))
839 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
840 if (_Py_InitializeMainInterpreter(&config))
841 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700842}
843
844
845void
Nick Coghland6009512014-11-20 21:39:37 +1000846Py_InitializeEx(int install_sigs)
847{
848 _Py_InitializeEx_Private(install_sigs, 1);
849}
850
851void
852Py_Initialize(void)
853{
854 Py_InitializeEx(1);
855}
856
857
858#ifdef COUNT_ALLOCS
859extern void dump_counts(FILE*);
860#endif
861
862/* Flush stdout and stderr */
863
864static int
865file_is_closed(PyObject *fobj)
866{
867 int r;
868 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
869 if (tmp == NULL) {
870 PyErr_Clear();
871 return 0;
872 }
873 r = PyObject_IsTrue(tmp);
874 Py_DECREF(tmp);
875 if (r < 0)
876 PyErr_Clear();
877 return r > 0;
878}
879
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000880static int
Nick Coghland6009512014-11-20 21:39:37 +1000881flush_std_files(void)
882{
883 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
884 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
885 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000886 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000887
888 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700889 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000890 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000891 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000892 status = -1;
893 }
Nick Coghland6009512014-11-20 21:39:37 +1000894 else
895 Py_DECREF(tmp);
896 }
897
898 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700899 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000900 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000901 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000902 status = -1;
903 }
Nick Coghland6009512014-11-20 21:39:37 +1000904 else
905 Py_DECREF(tmp);
906 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000907
908 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000909}
910
911/* Undo the effect of Py_Initialize().
912
913 Beware: if multiple interpreter and/or thread states exist, these
914 are not wiped out; only the current thread and interpreter state
915 are deleted. But since everything else is deleted, those other
916 interpreter and thread states should no longer be used.
917
918 (XXX We should do better, e.g. wipe out all interpreters and
919 threads.)
920
921 Locking: as above.
922
923*/
924
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000925int
926Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000927{
928 PyInterpreterState *interp;
929 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000930 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000931
Eric Snow1abcf672017-05-23 21:46:51 -0700932 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000933 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000934
935 wait_for_thread_shutdown();
936
937 /* The interpreter is still entirely intact at this point, and the
938 * exit funcs may be relying on that. In particular, if some thread
939 * or exit func is still waiting to do an import, the import machinery
940 * expects Py_IsInitialized() to return true. So don't say the
941 * interpreter is uninitialized until after the exit funcs have run.
942 * Note that Threading.py uses an exit func to do a join on all the
943 * threads created thru it, so this also protects pending imports in
944 * the threads created via Threading.
945 */
946 call_py_exitfuncs();
947
948 /* Get current thread state and interpreter pointer */
949 tstate = PyThreadState_GET();
950 interp = tstate->interp;
951
952 /* Remaining threads (e.g. daemon threads) will automatically exit
953 after taking the GIL (in PyEval_RestoreThread()). */
954 _Py_Finalizing = tstate;
Eric Snow1abcf672017-05-23 21:46:51 -0700955 _Py_Initialized = 0;
956 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000957
Victor Stinnere0deff32015-03-24 13:46:18 +0100958 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000959 if (flush_std_files() < 0) {
960 status = -1;
961 }
Nick Coghland6009512014-11-20 21:39:37 +1000962
963 /* Disable signal handling */
964 PyOS_FiniInterrupts();
965
966 /* Collect garbage. This may call finalizers; it's nice to call these
967 * before all modules are destroyed.
968 * XXX If a __del__ or weakref callback is triggered here, and tries to
969 * XXX import a module, bad things can happen, because Python no
970 * XXX longer believes it's initialized.
971 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
972 * XXX is easy to provoke that way. I've also seen, e.g.,
973 * XXX Exception exceptions.ImportError: 'No module named sha'
974 * XXX in <function callback at 0x008F5718> ignored
975 * XXX but I'm unclear on exactly how that one happens. In any case,
976 * XXX I haven't seen a real-life report of either of these.
977 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700978 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000979#ifdef COUNT_ALLOCS
980 /* With COUNT_ALLOCS, it helps to run GC multiple times:
981 each collection might release some types from the type
982 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700983 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000984 /* nothing */;
985#endif
986 /* Destroy all modules */
987 PyImport_Cleanup();
988
Victor Stinnere0deff32015-03-24 13:46:18 +0100989 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000990 if (flush_std_files() < 0) {
991 status = -1;
992 }
Nick Coghland6009512014-11-20 21:39:37 +1000993
994 /* Collect final garbage. This disposes of cycles created by
995 * class definitions, for example.
996 * XXX This is disabled because it caused too many problems. If
997 * XXX a __del__ or weakref callback triggers here, Python code has
998 * XXX a hard time running, because even the sys module has been
999 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1000 * XXX One symptom is a sequence of information-free messages
1001 * XXX coming from threads (if a __del__ or callback is invoked,
1002 * XXX other threads can execute too, and any exception they encounter
1003 * XXX triggers a comedy of errors as subsystem after subsystem
1004 * XXX fails to find what it *expects* to find in sys to help report
1005 * XXX the exception and consequent unexpected failures). I've also
1006 * XXX seen segfaults then, after adding print statements to the
1007 * XXX Python code getting called.
1008 */
1009#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001010 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001011#endif
1012
1013 /* Disable tracemalloc after all Python objects have been destroyed,
1014 so it is possible to use tracemalloc in objects destructor. */
1015 _PyTraceMalloc_Fini();
1016
1017 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1018 _PyImport_Fini();
1019
1020 /* Cleanup typeobject.c's internal caches. */
1021 _PyType_Fini();
1022
1023 /* unload faulthandler module */
1024 _PyFaulthandler_Fini();
1025
1026 /* Debugging stuff */
1027#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001028 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001029#endif
1030 /* dump hash stats */
1031 _PyHash_Fini();
1032
1033 _PY_DEBUG_PRINT_TOTAL_REFS();
1034
1035#ifdef Py_TRACE_REFS
1036 /* Display all objects still alive -- this can invoke arbitrary
1037 * __repr__ overrides, so requires a mostly-intact interpreter.
1038 * Alas, a lot of stuff may still be alive now that will be cleaned
1039 * up later.
1040 */
1041 if (Py_GETENV("PYTHONDUMPREFS"))
1042 _Py_PrintReferences(stderr);
1043#endif /* Py_TRACE_REFS */
1044
1045 /* Clear interpreter state and all thread states. */
1046 PyInterpreterState_Clear(interp);
1047
1048 /* Now we decref the exception classes. After this point nothing
1049 can raise an exception. That's okay, because each Fini() method
1050 below has been checked to make sure no exceptions are ever
1051 raised.
1052 */
1053
1054 _PyExc_Fini();
1055
1056 /* Sundry finalizers */
1057 PyMethod_Fini();
1058 PyFrame_Fini();
1059 PyCFunction_Fini();
1060 PyTuple_Fini();
1061 PyList_Fini();
1062 PySet_Fini();
1063 PyBytes_Fini();
1064 PyByteArray_Fini();
1065 PyLong_Fini();
1066 PyFloat_Fini();
1067 PyDict_Fini();
1068 PySlice_Fini();
1069 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001070 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001071 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001072 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001073
1074 /* Cleanup Unicode implementation */
1075 _PyUnicode_Fini();
1076
1077 /* reset file system default encoding */
1078 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1079 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1080 Py_FileSystemDefaultEncoding = NULL;
1081 }
1082
1083 /* XXX Still allocated:
1084 - various static ad-hoc pointers to interned strings
1085 - int and float free list blocks
1086 - whatever various modules and libraries allocate
1087 */
1088
1089 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1090
1091 /* Cleanup auto-thread-state */
1092#ifdef WITH_THREAD
1093 _PyGILState_Fini();
1094#endif /* WITH_THREAD */
1095
1096 /* Delete current thread. After this, many C API calls become crashy. */
1097 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001098
Nick Coghland6009512014-11-20 21:39:37 +10001099 PyInterpreterState_Delete(interp);
1100
1101#ifdef Py_TRACE_REFS
1102 /* Display addresses (& refcnts) of all objects still alive.
1103 * An address can be used to find the repr of the object, printed
1104 * above by _Py_PrintReferences.
1105 */
1106 if (Py_GETENV("PYTHONDUMPREFS"))
1107 _Py_PrintReferenceAddresses(stderr);
1108#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001109#ifdef WITH_PYMALLOC
1110 if (_PyMem_PymallocEnabled()) {
1111 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1112 if (opt != NULL && *opt != '\0')
1113 _PyObject_DebugMallocStats(stderr);
1114 }
Nick Coghland6009512014-11-20 21:39:37 +10001115#endif
1116
1117 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001118 return status;
1119}
1120
1121void
1122Py_Finalize(void)
1123{
1124 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001125}
1126
1127/* Create and initialize a new interpreter and thread, and return the
1128 new thread. This requires that Py_Initialize() has been called
1129 first.
1130
1131 Unsuccessful initialization yields a NULL pointer. Note that *no*
1132 exception information is available even in this case -- the
1133 exception information is held in the thread, and there is no
1134 thread.
1135
1136 Locking: as above.
1137
1138*/
1139
1140PyThreadState *
1141Py_NewInterpreter(void)
1142{
1143 PyInterpreterState *interp;
1144 PyThreadState *tstate, *save_tstate;
1145 PyObject *bimod, *sysmod;
1146
Eric Snow1abcf672017-05-23 21:46:51 -07001147 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001148 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1149
Victor Stinnerd7292b52016-06-17 12:29:00 +02001150#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +01001151 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1152 interpreters: disable PyGILState_Check(). */
1153 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +03001154#endif
Victor Stinner8a1be612016-03-14 22:07:55 +01001155
Nick Coghland6009512014-11-20 21:39:37 +10001156 interp = PyInterpreterState_New();
1157 if (interp == NULL)
1158 return NULL;
1159
1160 tstate = PyThreadState_New(interp);
1161 if (tstate == NULL) {
1162 PyInterpreterState_Delete(interp);
1163 return NULL;
1164 }
1165
1166 save_tstate = PyThreadState_Swap(tstate);
1167
Eric Snow1abcf672017-05-23 21:46:51 -07001168 /* Copy the current interpreter config into the new interpreter */
1169 if (save_tstate != NULL) {
1170 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001171 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001172 } else {
1173 /* No current thread state, copy from the main interpreter */
1174 PyInterpreterState *main_interp = PyInterpreterState_Main();
1175 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001176 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001177 }
1178
Nick Coghland6009512014-11-20 21:39:37 +10001179 /* XXX The following is lax in error checking */
1180
1181 interp->modules = PyDict_New();
1182
1183 bimod = _PyImport_FindBuiltin("builtins");
1184 if (bimod != NULL) {
1185 interp->builtins = PyModule_GetDict(bimod);
1186 if (interp->builtins == NULL)
1187 goto handle_error;
1188 Py_INCREF(interp->builtins);
1189 }
1190
1191 /* initialize builtin exceptions */
1192 _PyExc_Init(bimod);
1193
1194 sysmod = _PyImport_FindBuiltin("sys");
1195 if (bimod != NULL && sysmod != NULL) {
1196 PyObject *pstderr;
1197
1198 interp->sysdict = PyModule_GetDict(sysmod);
1199 if (interp->sysdict == NULL)
1200 goto handle_error;
1201 Py_INCREF(interp->sysdict);
Eric Snow1abcf672017-05-23 21:46:51 -07001202 _PySys_EndInit(interp->sysdict);
Nick Coghland6009512014-11-20 21:39:37 +10001203 PySys_SetPath(Py_GetPath());
1204 PyDict_SetItemString(interp->sysdict, "modules",
1205 interp->modules);
1206 /* Set up a preliminary stderr printer until we have enough
1207 infrastructure for the io module in place. */
1208 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1209 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001210 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001211 _PySys_SetObjectId(&PyId_stderr, pstderr);
1212 PySys_SetObject("__stderr__", pstderr);
1213 Py_DECREF(pstderr);
1214
1215 _PyImportHooks_Init();
1216
Eric Snow1abcf672017-05-23 21:46:51 -07001217 initimport(interp, sysmod);
1218 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001219
1220 if (initfsencoding(interp) < 0)
1221 goto handle_error;
1222
1223 if (initstdio() < 0)
1224 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001225 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001226 initmain(interp);
1227 if (!Py_NoSiteFlag)
1228 initsite();
1229 }
1230
1231 if (!PyErr_Occurred())
1232 return tstate;
1233
1234handle_error:
1235 /* Oops, it didn't work. Undo it all. */
1236
1237 PyErr_PrintEx(0);
1238 PyThreadState_Clear(tstate);
1239 PyThreadState_Swap(save_tstate);
1240 PyThreadState_Delete(tstate);
1241 PyInterpreterState_Delete(interp);
1242
1243 return NULL;
1244}
1245
1246/* Delete an interpreter and its last thread. This requires that the
1247 given thread state is current, that the thread has no remaining
1248 frames, and that it is its interpreter's only remaining thread.
1249 It is a fatal error to violate these constraints.
1250
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001251 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001252 everything, regardless.)
1253
1254 Locking: as above.
1255
1256*/
1257
1258void
1259Py_EndInterpreter(PyThreadState *tstate)
1260{
1261 PyInterpreterState *interp = tstate->interp;
1262
1263 if (tstate != PyThreadState_GET())
1264 Py_FatalError("Py_EndInterpreter: thread is not current");
1265 if (tstate->frame != NULL)
1266 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1267
1268 wait_for_thread_shutdown();
1269
1270 if (tstate != interp->tstate_head || tstate->next != NULL)
1271 Py_FatalError("Py_EndInterpreter: not the last thread");
1272
1273 PyImport_Cleanup();
1274 PyInterpreterState_Clear(interp);
1275 PyThreadState_Swap(NULL);
1276 PyInterpreterState_Delete(interp);
1277}
1278
1279#ifdef MS_WINDOWS
1280static wchar_t *progname = L"python";
1281#else
1282static wchar_t *progname = L"python3";
1283#endif
1284
1285void
1286Py_SetProgramName(wchar_t *pn)
1287{
1288 if (pn && *pn)
1289 progname = pn;
1290}
1291
1292wchar_t *
1293Py_GetProgramName(void)
1294{
1295 return progname;
1296}
1297
1298static wchar_t *default_home = NULL;
1299static wchar_t env_home[MAXPATHLEN+1];
1300
1301void
1302Py_SetPythonHome(wchar_t *home)
1303{
1304 default_home = home;
1305}
1306
1307wchar_t *
1308Py_GetPythonHome(void)
1309{
1310 wchar_t *home = default_home;
1311 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1312 char* chome = Py_GETENV("PYTHONHOME");
1313 if (chome) {
1314 size_t size = Py_ARRAY_LENGTH(env_home);
1315 size_t r = mbstowcs(env_home, chome, size);
1316 if (r != (size_t)-1 && r < size)
1317 home = env_home;
1318 }
1319
1320 }
1321 return home;
1322}
1323
1324/* Create __main__ module */
1325
1326static void
1327initmain(PyInterpreterState *interp)
1328{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001329 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001330 m = PyImport_AddModule("__main__");
1331 if (m == NULL)
1332 Py_FatalError("can't create __main__ module");
1333 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001334 ann_dict = PyDict_New();
1335 if ((ann_dict == NULL) ||
1336 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1337 Py_FatalError("Failed to initialize __main__.__annotations__");
1338 }
1339 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001340 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1341 PyObject *bimod = PyImport_ImportModule("builtins");
1342 if (bimod == NULL) {
1343 Py_FatalError("Failed to retrieve builtins module");
1344 }
1345 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1346 Py_FatalError("Failed to initialize __main__.__builtins__");
1347 }
1348 Py_DECREF(bimod);
1349 }
1350 /* Main is a little special - imp.is_builtin("__main__") will return
1351 * False, but BuiltinImporter is still the most appropriate initial
1352 * setting for its __loader__ attribute. A more suitable value will
1353 * be set if __main__ gets further initialized later in the startup
1354 * process.
1355 */
1356 loader = PyDict_GetItemString(d, "__loader__");
1357 if (loader == NULL || loader == Py_None) {
1358 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1359 "BuiltinImporter");
1360 if (loader == NULL) {
1361 Py_FatalError("Failed to retrieve BuiltinImporter");
1362 }
1363 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1364 Py_FatalError("Failed to initialize __main__.__loader__");
1365 }
1366 Py_DECREF(loader);
1367 }
1368}
1369
1370static int
1371initfsencoding(PyInterpreterState *interp)
1372{
1373 PyObject *codec;
1374
Steve Dowercc16be82016-09-08 10:35:16 -07001375#ifdef MS_WINDOWS
1376 if (Py_LegacyWindowsFSEncodingFlag)
1377 {
1378 Py_FileSystemDefaultEncoding = "mbcs";
1379 Py_FileSystemDefaultEncodeErrors = "replace";
1380 }
1381 else
1382 {
1383 Py_FileSystemDefaultEncoding = "utf-8";
1384 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1385 }
1386#else
Nick Coghland6009512014-11-20 21:39:37 +10001387 if (Py_FileSystemDefaultEncoding == NULL)
1388 {
1389 Py_FileSystemDefaultEncoding = get_locale_encoding();
1390 if (Py_FileSystemDefaultEncoding == NULL)
1391 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1392
1393 Py_HasFileSystemDefaultEncoding = 0;
1394 interp->fscodec_initialized = 1;
1395 return 0;
1396 }
Steve Dowercc16be82016-09-08 10:35:16 -07001397#endif
Nick Coghland6009512014-11-20 21:39:37 +10001398
1399 /* the encoding is mbcs, utf-8 or ascii */
1400 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1401 if (!codec) {
1402 /* Such error can only occurs in critical situations: no more
1403 * memory, import a module of the standard library failed,
1404 * etc. */
1405 return -1;
1406 }
1407 Py_DECREF(codec);
1408 interp->fscodec_initialized = 1;
1409 return 0;
1410}
1411
1412/* Import the site module (not into __main__ though) */
1413
1414static void
1415initsite(void)
1416{
1417 PyObject *m;
1418 m = PyImport_ImportModule("site");
1419 if (m == NULL) {
1420 fprintf(stderr, "Failed to import the site module\n");
1421 PyErr_Print();
1422 Py_Finalize();
1423 exit(1);
1424 }
1425 else {
1426 Py_DECREF(m);
1427 }
1428}
1429
Victor Stinner874dbe82015-09-04 17:29:57 +02001430/* Check if a file descriptor is valid or not.
1431 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1432static int
1433is_valid_fd(int fd)
1434{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001435#ifdef __APPLE__
1436 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1437 and the other side of the pipe is closed, dup(1) succeed, whereas
1438 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1439 such error. */
1440 struct stat st;
1441 return (fstat(fd, &st) == 0);
1442#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001443 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001444 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001445 return 0;
1446 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001447 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1448 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1449 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001450 fd2 = dup(fd);
1451 if (fd2 >= 0)
1452 close(fd2);
1453 _Py_END_SUPPRESS_IPH
1454 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001455#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001456}
1457
1458/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001459static PyObject*
1460create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001461 int fd, int write_mode, const char* name,
1462 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001463{
1464 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1465 const char* mode;
1466 const char* newline;
1467 PyObject *line_buffering;
1468 int buffering, isatty;
1469 _Py_IDENTIFIER(open);
1470 _Py_IDENTIFIER(isatty);
1471 _Py_IDENTIFIER(TextIOWrapper);
1472 _Py_IDENTIFIER(mode);
1473
Victor Stinner874dbe82015-09-04 17:29:57 +02001474 if (!is_valid_fd(fd))
1475 Py_RETURN_NONE;
1476
Nick Coghland6009512014-11-20 21:39:37 +10001477 /* stdin is always opened in buffered mode, first because it shouldn't
1478 make a difference in common use cases, second because TextIOWrapper
1479 depends on the presence of a read1() method which only exists on
1480 buffered streams.
1481 */
1482 if (Py_UnbufferedStdioFlag && write_mode)
1483 buffering = 0;
1484 else
1485 buffering = -1;
1486 if (write_mode)
1487 mode = "wb";
1488 else
1489 mode = "rb";
1490 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1491 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001492 Py_None, Py_None, /* encoding, errors */
1493 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001494 if (buf == NULL)
1495 goto error;
1496
1497 if (buffering) {
1498 _Py_IDENTIFIER(raw);
1499 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1500 if (raw == NULL)
1501 goto error;
1502 }
1503 else {
1504 raw = buf;
1505 Py_INCREF(raw);
1506 }
1507
Steve Dower39294992016-08-30 21:22:36 -07001508#ifdef MS_WINDOWS
1509 /* Windows console IO is always UTF-8 encoded */
1510 if (PyWindowsConsoleIO_Check(raw))
1511 encoding = "utf-8";
1512#endif
1513
Nick Coghland6009512014-11-20 21:39:37 +10001514 text = PyUnicode_FromString(name);
1515 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1516 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001517 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001518 if (res == NULL)
1519 goto error;
1520 isatty = PyObject_IsTrue(res);
1521 Py_DECREF(res);
1522 if (isatty == -1)
1523 goto error;
1524 if (isatty || Py_UnbufferedStdioFlag)
1525 line_buffering = Py_True;
1526 else
1527 line_buffering = Py_False;
1528
1529 Py_CLEAR(raw);
1530 Py_CLEAR(text);
1531
1532#ifdef MS_WINDOWS
1533 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1534 newlines to "\n".
1535 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1536 newline = NULL;
1537#else
1538 /* sys.stdin: split lines at "\n".
1539 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1540 newline = "\n";
1541#endif
1542
1543 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1544 buf, encoding, errors,
1545 newline, line_buffering);
1546 Py_CLEAR(buf);
1547 if (stream == NULL)
1548 goto error;
1549
1550 if (write_mode)
1551 mode = "w";
1552 else
1553 mode = "r";
1554 text = PyUnicode_FromString(mode);
1555 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1556 goto error;
1557 Py_CLEAR(text);
1558 return stream;
1559
1560error:
1561 Py_XDECREF(buf);
1562 Py_XDECREF(stream);
1563 Py_XDECREF(text);
1564 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001565
Victor Stinner874dbe82015-09-04 17:29:57 +02001566 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1567 /* Issue #24891: the file descriptor was closed after the first
1568 is_valid_fd() check was called. Ignore the OSError and set the
1569 stream to None. */
1570 PyErr_Clear();
1571 Py_RETURN_NONE;
1572 }
1573 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001574}
1575
1576/* Initialize sys.stdin, stdout, stderr and builtins.open */
1577static int
1578initstdio(void)
1579{
1580 PyObject *iomod = NULL, *wrapper;
1581 PyObject *bimod = NULL;
1582 PyObject *m;
1583 PyObject *std = NULL;
1584 int status = 0, fd;
1585 PyObject * encoding_attr;
1586 char *pythonioencoding = NULL, *encoding, *errors;
1587
1588 /* Hack to avoid a nasty recursion issue when Python is invoked
1589 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1590 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1591 goto error;
1592 }
1593 Py_DECREF(m);
1594
1595 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1596 goto error;
1597 }
1598 Py_DECREF(m);
1599
1600 if (!(bimod = PyImport_ImportModule("builtins"))) {
1601 goto error;
1602 }
1603
1604 if (!(iomod = PyImport_ImportModule("io"))) {
1605 goto error;
1606 }
1607 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1608 goto error;
1609 }
1610
1611 /* Set builtins.open */
1612 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1613 Py_DECREF(wrapper);
1614 goto error;
1615 }
1616 Py_DECREF(wrapper);
1617
1618 encoding = _Py_StandardStreamEncoding;
1619 errors = _Py_StandardStreamErrors;
1620 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001621 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1622 if (pythonioencoding) {
1623 char *err;
1624 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1625 if (pythonioencoding == NULL) {
1626 PyErr_NoMemory();
1627 goto error;
1628 }
1629 err = strchr(pythonioencoding, ':');
1630 if (err) {
1631 *err = '\0';
1632 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001633 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001634 errors = err;
1635 }
1636 }
1637 if (*pythonioencoding && !encoding) {
1638 encoding = pythonioencoding;
1639 }
1640 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001641 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001642 /* Choose the default error handler based on the current locale */
1643 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001644 }
Nick Coghland6009512014-11-20 21:39:37 +10001645 }
1646
1647 /* Set sys.stdin */
1648 fd = fileno(stdin);
1649 /* Under some conditions stdin, stdout and stderr may not be connected
1650 * and fileno() may point to an invalid file descriptor. For example
1651 * GUI apps don't have valid standard streams by default.
1652 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001653 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1654 if (std == NULL)
1655 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001656 PySys_SetObject("__stdin__", std);
1657 _PySys_SetObjectId(&PyId_stdin, std);
1658 Py_DECREF(std);
1659
1660 /* Set sys.stdout */
1661 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001662 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1663 if (std == NULL)
1664 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001665 PySys_SetObject("__stdout__", std);
1666 _PySys_SetObjectId(&PyId_stdout, std);
1667 Py_DECREF(std);
1668
1669#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1670 /* Set sys.stderr, replaces the preliminary stderr */
1671 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001672 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1673 if (std == NULL)
1674 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001675
1676 /* Same as hack above, pre-import stderr's codec to avoid recursion
1677 when import.c tries to write to stderr in verbose mode. */
1678 encoding_attr = PyObject_GetAttrString(std, "encoding");
1679 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001680 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001681 if (std_encoding != NULL) {
1682 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1683 Py_XDECREF(codec_info);
1684 }
1685 Py_DECREF(encoding_attr);
1686 }
1687 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1688
1689 if (PySys_SetObject("__stderr__", std) < 0) {
1690 Py_DECREF(std);
1691 goto error;
1692 }
1693 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1694 Py_DECREF(std);
1695 goto error;
1696 }
1697 Py_DECREF(std);
1698#endif
1699
1700 if (0) {
1701 error:
1702 status = -1;
1703 }
1704
1705 /* We won't need them anymore. */
1706 if (_Py_StandardStreamEncoding) {
1707 PyMem_RawFree(_Py_StandardStreamEncoding);
1708 _Py_StandardStreamEncoding = NULL;
1709 }
1710 if (_Py_StandardStreamErrors) {
1711 PyMem_RawFree(_Py_StandardStreamErrors);
1712 _Py_StandardStreamErrors = NULL;
1713 }
1714 PyMem_Free(pythonioencoding);
1715 Py_XDECREF(bimod);
1716 Py_XDECREF(iomod);
1717 return status;
1718}
1719
1720
Victor Stinner10dc4842015-03-24 12:01:30 +01001721static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001722_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001723{
Victor Stinner10dc4842015-03-24 12:01:30 +01001724 fputc('\n', stderr);
1725 fflush(stderr);
1726
1727 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001728 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001729}
Victor Stinner791da1c2016-03-14 16:53:12 +01001730
1731/* Print the current exception (if an exception is set) with its traceback,
1732 or display the current Python stack.
1733
1734 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1735 called on catastrophic cases.
1736
1737 Return 1 if the traceback was displayed, 0 otherwise. */
1738
1739static int
1740_Py_FatalError_PrintExc(int fd)
1741{
1742 PyObject *ferr, *res;
1743 PyObject *exception, *v, *tb;
1744 int has_tb;
1745
1746 if (PyThreadState_GET() == NULL) {
1747 /* The GIL is released: trying to acquire it is likely to deadlock,
1748 just give up. */
1749 return 0;
1750 }
1751
1752 PyErr_Fetch(&exception, &v, &tb);
1753 if (exception == NULL) {
1754 /* No current exception */
1755 return 0;
1756 }
1757
1758 ferr = _PySys_GetObjectId(&PyId_stderr);
1759 if (ferr == NULL || ferr == Py_None) {
1760 /* sys.stderr is not set yet or set to None,
1761 no need to try to display the exception */
1762 return 0;
1763 }
1764
1765 PyErr_NormalizeException(&exception, &v, &tb);
1766 if (tb == NULL) {
1767 tb = Py_None;
1768 Py_INCREF(tb);
1769 }
1770 PyException_SetTraceback(v, tb);
1771 if (exception == NULL) {
1772 /* PyErr_NormalizeException() failed */
1773 return 0;
1774 }
1775
1776 has_tb = (tb != Py_None);
1777 PyErr_Display(exception, v, tb);
1778 Py_XDECREF(exception);
1779 Py_XDECREF(v);
1780 Py_XDECREF(tb);
1781
1782 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001783 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001784 if (res == NULL)
1785 PyErr_Clear();
1786 else
1787 Py_DECREF(res);
1788
1789 return has_tb;
1790}
1791
Nick Coghland6009512014-11-20 21:39:37 +10001792/* Print fatal error message and abort */
1793
1794void
1795Py_FatalError(const char *msg)
1796{
1797 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001798 static int reentrant = 0;
1799#ifdef MS_WINDOWS
1800 size_t len;
1801 WCHAR* buffer;
1802 size_t i;
1803#endif
1804
1805 if (reentrant) {
1806 /* Py_FatalError() caused a second fatal error.
1807 Example: flush_std_files() raises a recursion error. */
1808 goto exit;
1809 }
1810 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001811
1812 fprintf(stderr, "Fatal Python error: %s\n", msg);
1813 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001814
Victor Stinnere0deff32015-03-24 13:46:18 +01001815 /* Print the exception (if an exception is set) with its traceback,
1816 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001817 if (!_Py_FatalError_PrintExc(fd))
1818 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001819
Victor Stinner2025d782016-03-16 23:19:15 +01001820 /* The main purpose of faulthandler is to display the traceback. We already
1821 * did our best to display it. So faulthandler can now be disabled.
1822 * (Don't trigger it on abort().) */
1823 _PyFaulthandler_Fini();
1824
Victor Stinner791da1c2016-03-14 16:53:12 +01001825 /* Check if the current Python thread hold the GIL */
1826 if (PyThreadState_GET() != NULL) {
1827 /* Flush sys.stdout and sys.stderr */
1828 flush_std_files();
1829 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001830
Nick Coghland6009512014-11-20 21:39:37 +10001831#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001832 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001833
Victor Stinner53345a42015-03-25 01:55:14 +01001834 /* Convert the message to wchar_t. This uses a simple one-to-one
1835 conversion, assuming that the this error message actually uses ASCII
1836 only. If this ceases to be true, we will have to convert. */
1837 buffer = alloca( (len+1) * (sizeof *buffer));
1838 for( i=0; i<=len; ++i)
1839 buffer[i] = msg[i];
1840 OutputDebugStringW(L"Fatal Python error: ");
1841 OutputDebugStringW(buffer);
1842 OutputDebugStringW(L"\n");
1843#endif /* MS_WINDOWS */
1844
1845exit:
1846#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001847 DebugBreak();
1848#endif
Nick Coghland6009512014-11-20 21:39:37 +10001849 abort();
1850}
1851
1852/* Clean up and exit */
1853
1854#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001855# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001856#endif
1857
1858static void (*pyexitfunc)(void) = NULL;
1859/* For the atexit module. */
1860void _Py_PyAtExit(void (*func)(void))
1861{
1862 pyexitfunc = func;
1863}
1864
1865static void
1866call_py_exitfuncs(void)
1867{
1868 if (pyexitfunc == NULL)
1869 return;
1870
1871 (*pyexitfunc)();
1872 PyErr_Clear();
1873}
1874
1875/* Wait until threading._shutdown completes, provided
1876 the threading module was imported in the first place.
1877 The shutdown routine will wait until all non-daemon
1878 "threading" threads have completed. */
1879static void
1880wait_for_thread_shutdown(void)
1881{
1882#ifdef WITH_THREAD
1883 _Py_IDENTIFIER(_shutdown);
1884 PyObject *result;
1885 PyThreadState *tstate = PyThreadState_GET();
1886 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1887 "threading");
1888 if (threading == NULL) {
1889 /* threading not imported */
1890 PyErr_Clear();
1891 return;
1892 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001893 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001894 if (result == NULL) {
1895 PyErr_WriteUnraisable(threading);
1896 }
1897 else {
1898 Py_DECREF(result);
1899 }
1900 Py_DECREF(threading);
1901#endif
1902}
1903
1904#define NEXITFUNCS 32
1905static void (*exitfuncs[NEXITFUNCS])(void);
1906static int nexitfuncs = 0;
1907
1908int Py_AtExit(void (*func)(void))
1909{
1910 if (nexitfuncs >= NEXITFUNCS)
1911 return -1;
1912 exitfuncs[nexitfuncs++] = func;
1913 return 0;
1914}
1915
1916static void
1917call_ll_exitfuncs(void)
1918{
1919 while (nexitfuncs > 0)
1920 (*exitfuncs[--nexitfuncs])();
1921
1922 fflush(stdout);
1923 fflush(stderr);
1924}
1925
1926void
1927Py_Exit(int sts)
1928{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001929 if (Py_FinalizeEx() < 0) {
1930 sts = 120;
1931 }
Nick Coghland6009512014-11-20 21:39:37 +10001932
1933 exit(sts);
1934}
1935
1936static void
1937initsigs(void)
1938{
1939#ifdef SIGPIPE
1940 PyOS_setsig(SIGPIPE, SIG_IGN);
1941#endif
1942#ifdef SIGXFZ
1943 PyOS_setsig(SIGXFZ, SIG_IGN);
1944#endif
1945#ifdef SIGXFSZ
1946 PyOS_setsig(SIGXFSZ, SIG_IGN);
1947#endif
1948 PyOS_InitInterrupts(); /* May imply initsignal() */
1949 if (PyErr_Occurred()) {
1950 Py_FatalError("Py_Initialize: can't import signal");
1951 }
1952}
1953
1954
1955/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1956 *
1957 * All of the code in this function must only use async-signal-safe functions,
1958 * listed at `man 7 signal` or
1959 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1960 */
1961void
1962_Py_RestoreSignals(void)
1963{
1964#ifdef SIGPIPE
1965 PyOS_setsig(SIGPIPE, SIG_DFL);
1966#endif
1967#ifdef SIGXFZ
1968 PyOS_setsig(SIGXFZ, SIG_DFL);
1969#endif
1970#ifdef SIGXFSZ
1971 PyOS_setsig(SIGXFSZ, SIG_DFL);
1972#endif
1973}
1974
1975
1976/*
1977 * The file descriptor fd is considered ``interactive'' if either
1978 * a) isatty(fd) is TRUE, or
1979 * b) the -i flag was given, and the filename associated with
1980 * the descriptor is NULL or "<stdin>" or "???".
1981 */
1982int
1983Py_FdIsInteractive(FILE *fp, const char *filename)
1984{
1985 if (isatty((int)fileno(fp)))
1986 return 1;
1987 if (!Py_InteractiveFlag)
1988 return 0;
1989 return (filename == NULL) ||
1990 (strcmp(filename, "<stdin>") == 0) ||
1991 (strcmp(filename, "???") == 0);
1992}
1993
1994
Nick Coghland6009512014-11-20 21:39:37 +10001995/* Wrappers around sigaction() or signal(). */
1996
1997PyOS_sighandler_t
1998PyOS_getsig(int sig)
1999{
2000#ifdef HAVE_SIGACTION
2001 struct sigaction context;
2002 if (sigaction(sig, NULL, &context) == -1)
2003 return SIG_ERR;
2004 return context.sa_handler;
2005#else
2006 PyOS_sighandler_t handler;
2007/* Special signal handling for the secure CRT in Visual Studio 2005 */
2008#if defined(_MSC_VER) && _MSC_VER >= 1400
2009 switch (sig) {
2010 /* Only these signals are valid */
2011 case SIGINT:
2012 case SIGILL:
2013 case SIGFPE:
2014 case SIGSEGV:
2015 case SIGTERM:
2016 case SIGBREAK:
2017 case SIGABRT:
2018 break;
2019 /* Don't call signal() with other values or it will assert */
2020 default:
2021 return SIG_ERR;
2022 }
2023#endif /* _MSC_VER && _MSC_VER >= 1400 */
2024 handler = signal(sig, SIG_IGN);
2025 if (handler != SIG_ERR)
2026 signal(sig, handler);
2027 return handler;
2028#endif
2029}
2030
2031/*
2032 * All of the code in this function must only use async-signal-safe functions,
2033 * listed at `man 7 signal` or
2034 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2035 */
2036PyOS_sighandler_t
2037PyOS_setsig(int sig, PyOS_sighandler_t handler)
2038{
2039#ifdef HAVE_SIGACTION
2040 /* Some code in Modules/signalmodule.c depends on sigaction() being
2041 * used here if HAVE_SIGACTION is defined. Fix that if this code
2042 * changes to invalidate that assumption.
2043 */
2044 struct sigaction context, ocontext;
2045 context.sa_handler = handler;
2046 sigemptyset(&context.sa_mask);
2047 context.sa_flags = 0;
2048 if (sigaction(sig, &context, &ocontext) == -1)
2049 return SIG_ERR;
2050 return ocontext.sa_handler;
2051#else
2052 PyOS_sighandler_t oldhandler;
2053 oldhandler = signal(sig, handler);
2054#ifdef HAVE_SIGINTERRUPT
2055 siginterrupt(sig, 1);
2056#endif
2057 return oldhandler;
2058#endif
2059}
2060
2061#ifdef __cplusplus
2062}
2063#endif