blob: 662405bdeb312ed350ec022919545e9bedea07ca [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);
Eric Snow86b7afd2017-09-04 17:54:09 -060044_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100045
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50extern wchar_t *Py_GetPath(void);
51
52extern grammar _PyParser_Grammar; /* From graminit.c */
53
54/* Forward */
55static void initmain(PyInterpreterState *interp);
56static int initfsencoding(PyInterpreterState *interp);
57static void initsite(void);
58static int initstdio(void);
59static void initsigs(void);
60static void call_py_exitfuncs(void);
61static void wait_for_thread_shutdown(void);
62static void call_ll_exitfuncs(void);
63extern int _PyUnicode_Init(void);
64extern int _PyStructSequence_Init(void);
65extern void _PyUnicode_Fini(void);
66extern int _PyLong_Init(void);
67extern void PyLong_Fini(void);
68extern int _PyFaulthandler_Init(void);
69extern void _PyFaulthandler_Fini(void);
70extern void _PyHash_Fini(void);
71extern int _PyTraceMalloc_Init(void);
72extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070073extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100074
75#ifdef WITH_THREAD
76extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
78#endif /* WITH_THREAD */
79
80/* Global configuration variable declarations are in pydebug.h */
81/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
82int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
84int Py_QuietFlag; /* Needed by sysmodule.c */
85int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
86int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
87int Py_OptimizeFlag = 0; /* Needed by compile.c */
88int Py_NoSiteFlag; /* Suppress 'import site' */
89int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
90int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
91int Py_FrozenFlag; /* Needed by getpath.c */
92int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080093int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100094int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
95int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
96int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
97int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070098#ifdef MS_WINDOWS
99int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700100int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700101#endif
Nick Coghland6009512014-11-20 21:39:37 +1000102
Eric Snow05351c12017-09-05 21:43:08 -0700103PyThreadState *_Py_Finalizing = NULL;
104
Nick Coghland6009512014-11-20 21:39:37 +1000105/* Hack to force loading of object files */
106int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
107 PyOS_mystrnicmp; /* Python/pystrcmp.o */
108
109/* PyModule_GetWarningsModule is no longer necessary as of 2.6
110since _warnings is builtin. This API should not be used. */
111PyObject *
112PyModule_GetWarningsModule(void)
113{
114 return PyImport_ImportModule("warnings");
115}
116
Eric Snowc7ec9982017-05-23 23:00:52 -0700117
Eric Snow1abcf672017-05-23 21:46:51 -0700118/* APIs to access the initialization flags
119 *
120 * Can be called prior to Py_Initialize.
121 */
Eric Snow05351c12017-09-05 21:43:08 -0700122int _Py_CoreInitialized = 0;
123int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000124
Eric Snow1abcf672017-05-23 21:46:51 -0700125int
126_Py_IsCoreInitialized(void)
127{
Eric Snow05351c12017-09-05 21:43:08 -0700128 return _Py_CoreInitialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700129}
Nick Coghland6009512014-11-20 21:39:37 +1000130
131int
132Py_IsInitialized(void)
133{
Eric Snow05351c12017-09-05 21:43:08 -0700134 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000135}
136
137/* Helper to allow an embedding application to override the normal
138 * mechanism that attempts to figure out an appropriate IO encoding
139 */
140
141static char *_Py_StandardStreamEncoding = NULL;
142static char *_Py_StandardStreamErrors = NULL;
143
144int
145Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
146{
147 if (Py_IsInitialized()) {
148 /* This is too late to have any effect */
149 return -1;
150 }
151 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
152 * initialised yet.
153 *
154 * However, the raw memory allocators are initialised appropriately
155 * as C static variables, so _PyMem_RawStrdup is OK even though
156 * Py_Initialize hasn't been called yet.
157 */
158 if (encoding) {
159 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
160 if (!_Py_StandardStreamEncoding) {
161 return -2;
162 }
163 }
164 if (errors) {
165 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
166 if (!_Py_StandardStreamErrors) {
167 if (_Py_StandardStreamEncoding) {
168 PyMem_RawFree(_Py_StandardStreamEncoding);
169 }
170 return -3;
171 }
172 }
Steve Dower39294992016-08-30 21:22:36 -0700173#ifdef MS_WINDOWS
174 if (_Py_StandardStreamEncoding) {
175 /* Overriding the stream encoding implies legacy streams */
176 Py_LegacyWindowsStdioFlag = 1;
177 }
178#endif
Nick Coghland6009512014-11-20 21:39:37 +1000179 return 0;
180}
181
Nick Coghlan6ea41862017-06-11 13:16:15 +1000182
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000183/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
184 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000185 initializations fail, a fatal error is issued and the function does
186 not return. On return, the first thread and interpreter state have
187 been created.
188
189 Locking: you must hold the interpreter lock while calling this.
190 (If the lock has not yet been initialized, that's equivalent to
191 having the lock, but you cannot use multiple threads.)
192
193*/
194
195static int
196add_flag(int flag, const char *envs)
197{
198 int env = atoi(envs);
199 if (flag < env)
200 flag = env;
201 if (flag < 1)
202 flag = 1;
203 return flag;
204}
205
206static char*
207get_codec_name(const char *encoding)
208{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200209 const char *name_utf8;
210 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000211 PyObject *codec, *name = NULL;
212
213 codec = _PyCodec_Lookup(encoding);
214 if (!codec)
215 goto error;
216
217 name = _PyObject_GetAttrId(codec, &PyId_name);
218 Py_CLEAR(codec);
219 if (!name)
220 goto error;
221
Serhiy Storchaka06515832016-11-20 09:13:07 +0200222 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000223 if (name_utf8 == NULL)
224 goto error;
225 name_str = _PyMem_RawStrdup(name_utf8);
226 Py_DECREF(name);
227 if (name_str == NULL) {
228 PyErr_NoMemory();
229 return NULL;
230 }
231 return name_str;
232
233error:
234 Py_XDECREF(codec);
235 Py_XDECREF(name);
236 return NULL;
237}
238
239static char*
240get_locale_encoding(void)
241{
242#ifdef MS_WINDOWS
243 char codepage[100];
244 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
245 return get_codec_name(codepage);
246#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
247 char* codeset = nl_langinfo(CODESET);
248 if (!codeset || codeset[0] == '\0') {
249 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
250 return NULL;
251 }
252 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200253#elif defined(__ANDROID__)
254 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000255#else
256 PyErr_SetNone(PyExc_NotImplementedError);
257 return NULL;
258#endif
259}
260
261static void
Eric Snow1abcf672017-05-23 21:46:51 -0700262initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000263{
264 PyObject *importlib;
265 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000266 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 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600296 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000297 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
298 }
299
Victor Stinnercd6e6942015-09-18 09:11:57 +0200300 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000301 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200302 if (value != NULL) {
303 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700304 value = PyObject_CallMethod(importlib,
305 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200306 }
Nick Coghland6009512014-11-20 21:39:37 +1000307 if (value == NULL) {
308 PyErr_Print();
309 Py_FatalError("Py_Initialize: importlib install failed");
310 }
311 Py_DECREF(value);
312 Py_DECREF(impmod);
313
314 _PyImportZip_Init();
315}
316
Eric Snow1abcf672017-05-23 21:46:51 -0700317static void
318initexternalimport(PyInterpreterState *interp)
319{
320 PyObject *value;
321 value = PyObject_CallMethod(interp->importlib,
322 "_install_external_importers", "");
323 if (value == NULL) {
324 PyErr_Print();
325 Py_FatalError("Py_EndInitialization: external importer setup failed");
326 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200327 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700328}
Nick Coghland6009512014-11-20 21:39:37 +1000329
Nick Coghlan6ea41862017-06-11 13:16:15 +1000330/* Helper functions to better handle the legacy C locale
331 *
332 * The legacy C locale assumes ASCII as the default text encoding, which
333 * causes problems not only for the CPython runtime, but also other
334 * components like GNU readline.
335 *
336 * Accordingly, when the CLI detects it, it attempts to coerce it to a
337 * more capable UTF-8 based alternative as follows:
338 *
339 * if (_Py_LegacyLocaleDetected()) {
340 * _Py_CoerceLegacyLocale();
341 * }
342 *
343 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
344 *
345 * Locale coercion also impacts the default error handler for the standard
346 * streams: while the usual default is "strict", the default for the legacy
347 * C locale and for any of the coercion target locales is "surrogateescape".
348 */
349
350int
351_Py_LegacyLocaleDetected(void)
352{
353#ifndef MS_WINDOWS
354 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000355 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
356 * the POSIX locale as a simple alias for the C locale, so
357 * we may also want to check for that explicitly.
358 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000359 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
360 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
361#else
362 /* Windows uses code pages instead of locales, so no locale is legacy */
363 return 0;
364#endif
365}
366
Nick Coghlaneb817952017-06-18 12:29:42 +1000367static const char *_C_LOCALE_WARNING =
368 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
369 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
370 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
371 "locales is recommended.\n";
372
373static int
374_legacy_locale_warnings_enabled(void)
375{
376 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
377 return (coerce_c_locale != NULL &&
378 strncmp(coerce_c_locale, "warn", 5) == 0);
379}
380
381static void
382_emit_stderr_warning_for_legacy_locale(void)
383{
384 if (_legacy_locale_warnings_enabled()) {
385 if (_Py_LegacyLocaleDetected()) {
386 fprintf(stderr, "%s", _C_LOCALE_WARNING);
387 }
388 }
389}
390
Nick Coghlan6ea41862017-06-11 13:16:15 +1000391typedef struct _CandidateLocale {
392 const char *locale_name; /* The locale to try as a coercion target */
393} _LocaleCoercionTarget;
394
395static _LocaleCoercionTarget _TARGET_LOCALES[] = {
396 {"C.UTF-8"},
397 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000398 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000399 {NULL}
400};
401
402static char *
403get_default_standard_stream_error_handler(void)
404{
405 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
406 if (ctype_loc != NULL) {
407 /* "surrogateescape" is the default in the legacy C locale */
408 if (strcmp(ctype_loc, "C") == 0) {
409 return "surrogateescape";
410 }
411
412#ifdef PY_COERCE_C_LOCALE
413 /* "surrogateescape" is the default in locale coercion target locales */
414 const _LocaleCoercionTarget *target = NULL;
415 for (target = _TARGET_LOCALES; target->locale_name; target++) {
416 if (strcmp(ctype_loc, target->locale_name) == 0) {
417 return "surrogateescape";
418 }
419 }
420#endif
421 }
422
423 /* Otherwise return NULL to request the typical default error handler */
424 return NULL;
425}
426
427#ifdef PY_COERCE_C_LOCALE
428static const char *_C_LOCALE_COERCION_WARNING =
429 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
430 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
431
432static void
433_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
434{
435 const char *newloc = target->locale_name;
436
437 /* Reset locale back to currently configured defaults */
438 setlocale(LC_ALL, "");
439
440 /* Set the relevant locale environment variable */
441 if (setenv("LC_CTYPE", newloc, 1)) {
442 fprintf(stderr,
443 "Error setting LC_CTYPE, skipping C locale coercion\n");
444 return;
445 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000446 if (_legacy_locale_warnings_enabled()) {
447 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
448 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000449
450 /* Reconfigure with the overridden environment variables */
451 setlocale(LC_ALL, "");
452}
453#endif
454
455void
456_Py_CoerceLegacyLocale(void)
457{
458#ifdef PY_COERCE_C_LOCALE
459 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
460 * the locale settings *before* we try to do anything with the command
461 * line arguments. For cross-platform debugging purposes, we also need
462 * to give end users a way to force even scripts that are otherwise
463 * isolated from their environment to use the legacy ASCII-centric C
464 * locale.
465 *
466 * Ignoring -E and -I is safe from a security perspective, as we only use
467 * the setting to turn *off* the implicit locale coercion, and anyone with
468 * access to the process environment already has the ability to set
469 * `LC_ALL=C` to override the C level locale settings anyway.
470 */
471 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
472 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
473 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
474 const char *locale_override = getenv("LC_ALL");
475 if (locale_override == NULL || *locale_override == '\0') {
476 /* LC_ALL is also not set (or is set to an empty string) */
477 const _LocaleCoercionTarget *target = NULL;
478 for (target = _TARGET_LOCALES; target->locale_name; target++) {
479 const char *new_locale = setlocale(LC_CTYPE,
480 target->locale_name);
481 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000482#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
483 /* Also ensure that nl_langinfo works in this locale */
484 char *codeset = nl_langinfo(CODESET);
485 if (!codeset || *codeset == '\0') {
486 /* CODESET is not set or empty, so skip coercion */
487 new_locale = NULL;
488 setlocale(LC_CTYPE, "");
489 continue;
490 }
491#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000492 /* Successfully configured locale, so make it the default */
493 _coerce_default_locale_settings(target);
494 return;
495 }
496 }
497 }
498 }
499 /* No C locale warning here, as Py_Initialize will emit one later */
500#endif
501}
502
503
Eric Snow1abcf672017-05-23 21:46:51 -0700504/* Global initializations. Can be undone by Py_Finalize(). Don't
505 call this twice without an intervening Py_Finalize() call.
506
507 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
508 must have a corresponding call to Py_Finalize.
509
510 Locking: you must hold the interpreter lock while calling these APIs.
511 (If the lock has not yet been initialized, that's equivalent to
512 having the lock, but you cannot use multiple threads.)
513
514*/
515
516/* Begin interpreter initialization
517 *
518 * On return, the first thread and interpreter state have been created,
519 * but the compiler, signal handling, multithreading and
520 * multiple interpreter support, and codec infrastructure are not yet
521 * available.
522 *
523 * The import system will support builtin and frozen modules only.
524 * The only supported io is writing to sys.stderr
525 *
526 * If any operation invoked by this function fails, a fatal error is
527 * issued and the function does not return.
528 *
529 * Any code invoked from this function should *not* assume it has access
530 * to the Python C API (unless the API is explicitly listed as being
531 * safe to call without calling Py_Initialize first)
532 */
533
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200534/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700535 * Py_ReadConfig and Py_EndInitialization
536 */
537
538void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000539{
540 PyInterpreterState *interp;
541 PyThreadState *tstate;
542 PyObject *bimod, *sysmod, *pstderr;
543 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700544 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700545 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000546
Eric Snow1abcf672017-05-23 21:46:51 -0700547 if (config != NULL) {
548 core_config = *config;
549 }
550
Eric Snow05351c12017-09-05 21:43:08 -0700551 if (_Py_Initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700552 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
553 }
Eric Snow05351c12017-09-05 21:43:08 -0700554 if (_Py_CoreInitialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700555 Py_FatalError("Py_InitializeCore: runtime core already initialized");
556 }
557
558 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
559 * threads behave a little more gracefully at interpreter shutdown.
560 * We clobber it here so the new interpreter can start with a clean
561 * slate.
562 *
563 * However, this may still lead to misbehaviour if there are daemon
564 * threads still hanging around from a previous Py_Initialize/Finalize
565 * pair :(
566 */
Eric Snow05351c12017-09-05 21:43:08 -0700567 _Py_Finalizing = NULL;
Nick Coghland6009512014-11-20 21:39:37 +1000568
Nick Coghlan6ea41862017-06-11 13:16:15 +1000569#ifdef __ANDROID__
570 /* Passing "" to setlocale() on Android requests the C locale rather
571 * than checking environment variables, so request C.UTF-8 explicitly
572 */
573 setlocale(LC_CTYPE, "C.UTF-8");
574#else
575#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000576 /* Set up the LC_CTYPE locale, so we can obtain
577 the locale's charset without having to switch
578 locales. */
579 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000580 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000581#endif
Nick Coghland6009512014-11-20 21:39:37 +1000582#endif
583
584 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
585 Py_DebugFlag = add_flag(Py_DebugFlag, p);
586 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
587 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
588 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
589 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
590 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
591 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700592 /* The variable is only tested for existence here;
593 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000594 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
595 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700596#ifdef MS_WINDOWS
597 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
598 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700599 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
600 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700601#endif
Nick Coghland6009512014-11-20 21:39:37 +1000602
Eric Snow1abcf672017-05-23 21:46:51 -0700603 _Py_HashRandomization_Init(&core_config);
604 if (!core_config.use_hash_seed || core_config.hash_seed) {
605 /* Random or non-zero hash seed */
606 Py_HashRandomizationFlag = 1;
607 }
Nick Coghland6009512014-11-20 21:39:37 +1000608
Eric Snow05351c12017-09-05 21:43:08 -0700609 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000610 interp = PyInterpreterState_New();
611 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700612 Py_FatalError("Py_InitializeCore: can't make main interpreter");
613 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700614 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000615
616 tstate = PyThreadState_New(interp);
617 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700618 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000619 (void) PyThreadState_Swap(tstate);
620
621#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000622 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000623 destroying the GIL might fail when it is being referenced from
624 another running thread (see issue #9901).
625 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000626 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000627 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000628 /* Auto-thread-state API */
629 _PyGILState_Init(interp, tstate);
630#endif /* WITH_THREAD */
631
632 _Py_ReadyTypes();
633
634 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700635 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000636
637 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700638 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000639
640 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700641 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000642
643 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700644 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000645
Eric Snow86b7afd2017-09-04 17:54:09 -0600646 PyObject *modules = PyDict_New();
647 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700648 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000649
Eric Snow86b7afd2017-09-04 17:54:09 -0600650 sysmod = _PySys_BeginInit();
651 if (sysmod == NULL)
652 Py_FatalError("Py_InitializeCore: can't initialize sys");
653 interp->sysdict = PyModule_GetDict(sysmod);
654 if (interp->sysdict == NULL)
655 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
656 Py_INCREF(interp->sysdict);
657 PyDict_SetItemString(interp->sysdict, "modules", modules);
658 _PyImport_FixupBuiltin(sysmod, "sys", modules);
659
Nick Coghland6009512014-11-20 21:39:37 +1000660 /* Init Unicode implementation; relies on the codec registry */
661 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700662 Py_FatalError("Py_InitializeCore: can't initialize unicode");
663
Nick Coghland6009512014-11-20 21:39:37 +1000664 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700665 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000666
667 bimod = _PyBuiltin_Init();
668 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700669 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snow86b7afd2017-09-04 17:54:09 -0600670 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000671 interp->builtins = PyModule_GetDict(bimod);
672 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700673 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000674 Py_INCREF(interp->builtins);
675
676 /* initialize builtin exceptions */
677 _PyExc_Init(bimod);
678
Nick Coghland6009512014-11-20 21:39:37 +1000679 /* Set up a preliminary stderr printer until we have enough
680 infrastructure for the io module in place. */
681 pstderr = PyFile_NewStdPrinter(fileno(stderr));
682 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700683 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000684 _PySys_SetObjectId(&PyId_stderr, pstderr);
685 PySys_SetObject("__stderr__", pstderr);
686 Py_DECREF(pstderr);
687
688 _PyImport_Init();
689
690 _PyImportHooks_Init();
691
692 /* Initialize _warnings. */
693 _PyWarnings_Init();
694
Eric Snow1abcf672017-05-23 21:46:51 -0700695 /* This call sets up builtin and frozen import support */
696 if (!interp->core_config._disable_importlib) {
697 initimport(interp, sysmod);
698 }
699
700 /* Only when we get here is the runtime core fully initialized */
Eric Snow05351c12017-09-05 21:43:08 -0700701 _Py_CoreInitialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700702}
703
Eric Snowc7ec9982017-05-23 23:00:52 -0700704/* Read configuration settings from standard locations
705 *
706 * This function doesn't make any changes to the interpreter state - it
707 * merely populates any missing configuration settings. This allows an
708 * embedding application to completely override a config option by
709 * setting it before calling this function, or else modify the default
710 * setting before passing the fully populated config to Py_EndInitialization.
711 *
712 * More advanced selective initialization tricks are possible by calling
713 * this function multiple times with various preconfigured settings.
714 */
715
716int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
717{
718 /* Signal handlers are installed by default */
719 if (config->install_signal_handlers < 0) {
720 config->install_signal_handlers = 1;
721 }
722
723 return 0;
724}
725
726/* Update interpreter state based on supplied configuration settings
727 *
728 * After calling this function, most of the restrictions on the interpreter
729 * are lifted. The only remaining incomplete settings are those related
730 * to the main module (sys.argv[0], __main__ metadata)
731 *
732 * Calling this when the interpreter is not initializing, is already
733 * initialized or without a valid current thread state is a fatal error.
734 * Other errors should be reported as normal Python exceptions with a
735 * non-zero return code.
736 */
737int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700738{
739 PyInterpreterState *interp;
740 PyThreadState *tstate;
741
Eric Snow05351c12017-09-05 21:43:08 -0700742 if (!_Py_CoreInitialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700743 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
744 }
Eric Snow05351c12017-09-05 21:43:08 -0700745 if (_Py_Initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700746 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
747 }
748
Eric Snow1abcf672017-05-23 21:46:51 -0700749 /* Get current thread state and interpreter pointer */
750 tstate = PyThreadState_GET();
751 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700752 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700753 interp = tstate->interp;
754 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700755 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700756
757 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700758 interp->config = *config;
759
Eric Snow1abcf672017-05-23 21:46:51 -0700760 if (interp->core_config._disable_importlib) {
761 /* Special mode for freeze_importlib: run with no import system
762 *
763 * This means anything which needs support from extension modules
764 * or pure Python code in the standard library won't work.
765 */
Eric Snow05351c12017-09-05 21:43:08 -0700766 _Py_Initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700767 return 0;
768 }
769 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000770
Victor Stinner13019fd2015-04-03 13:10:54 +0200771 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700772 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200773
Eric Snow1abcf672017-05-23 21:46:51 -0700774 /* Finish setting up the sys module and import system */
775 /* GetPath may initialize state that _PySys_EndInit locks
776 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700777 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700778 PySys_SetPath(Py_GetPath());
779 if (_PySys_EndInit(interp->sysdict) < 0)
780 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700781 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000782
783 /* initialize the faulthandler module */
784 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700785 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000786
Nick Coghland6009512014-11-20 21:39:37 +1000787 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700788 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000789
Eric Snowc7ec9982017-05-23 23:00:52 -0700790 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000791 initsigs(); /* Signal handling stuff, including initintr() */
792
793 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700794 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000795
796 initmain(interp); /* Module __main__ */
797 if (initstdio() < 0)
798 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700799 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000800
801 /* Initialize warnings. */
802 if (PySys_HasWarnOptions()) {
803 PyObject *warnings_module = PyImport_ImportModule("warnings");
804 if (warnings_module == NULL) {
805 fprintf(stderr, "'import warnings' failed; traceback:\n");
806 PyErr_Print();
807 }
808 Py_XDECREF(warnings_module);
809 }
810
Eric Snow05351c12017-09-05 21:43:08 -0700811 _Py_Initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700812
Nick Coghland6009512014-11-20 21:39:37 +1000813 if (!Py_NoSiteFlag)
814 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700815
Eric Snowc7ec9982017-05-23 23:00:52 -0700816 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000817}
818
Eric Snowc7ec9982017-05-23 23:00:52 -0700819#undef _INIT_DEBUG_PRINT
820
Nick Coghland6009512014-11-20 21:39:37 +1000821void
Eric Snow1abcf672017-05-23 21:46:51 -0700822_Py_InitializeEx_Private(int install_sigs, int install_importlib)
823{
824 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700825 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700826
827 /* TODO: Moar config options! */
828 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
829 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700830 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700831 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 /* TODO: Print any exceptions raised by these operations */
833 if (_Py_ReadMainInterpreterConfig(&config))
834 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
835 if (_Py_InitializeMainInterpreter(&config))
836 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700837}
838
839
840void
Nick Coghland6009512014-11-20 21:39:37 +1000841Py_InitializeEx(int install_sigs)
842{
843 _Py_InitializeEx_Private(install_sigs, 1);
844}
845
846void
847Py_Initialize(void)
848{
849 Py_InitializeEx(1);
850}
851
852
853#ifdef COUNT_ALLOCS
854extern void dump_counts(FILE*);
855#endif
856
857/* Flush stdout and stderr */
858
859static int
860file_is_closed(PyObject *fobj)
861{
862 int r;
863 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
864 if (tmp == NULL) {
865 PyErr_Clear();
866 return 0;
867 }
868 r = PyObject_IsTrue(tmp);
869 Py_DECREF(tmp);
870 if (r < 0)
871 PyErr_Clear();
872 return r > 0;
873}
874
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000875static int
Nick Coghland6009512014-11-20 21:39:37 +1000876flush_std_files(void)
877{
878 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
879 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
880 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000881 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000882
883 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700884 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000885 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000886 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000887 status = -1;
888 }
Nick Coghland6009512014-11-20 21:39:37 +1000889 else
890 Py_DECREF(tmp);
891 }
892
893 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700894 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000895 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000896 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000897 status = -1;
898 }
Nick Coghland6009512014-11-20 21:39:37 +1000899 else
900 Py_DECREF(tmp);
901 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000902
903 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000904}
905
906/* Undo the effect of Py_Initialize().
907
908 Beware: if multiple interpreter and/or thread states exist, these
909 are not wiped out; only the current thread and interpreter state
910 are deleted. But since everything else is deleted, those other
911 interpreter and thread states should no longer be used.
912
913 (XXX We should do better, e.g. wipe out all interpreters and
914 threads.)
915
916 Locking: as above.
917
918*/
919
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000920int
921Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000922{
923 PyInterpreterState *interp;
924 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000925 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000926
Eric Snow05351c12017-09-05 21:43:08 -0700927 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000928 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000929
930 wait_for_thread_shutdown();
931
932 /* The interpreter is still entirely intact at this point, and the
933 * exit funcs may be relying on that. In particular, if some thread
934 * or exit func is still waiting to do an import, the import machinery
935 * expects Py_IsInitialized() to return true. So don't say the
936 * interpreter is uninitialized until after the exit funcs have run.
937 * Note that Threading.py uses an exit func to do a join on all the
938 * threads created thru it, so this also protects pending imports in
939 * the threads created via Threading.
940 */
941 call_py_exitfuncs();
942
943 /* Get current thread state and interpreter pointer */
944 tstate = PyThreadState_GET();
945 interp = tstate->interp;
946
947 /* Remaining threads (e.g. daemon threads) will automatically exit
948 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow05351c12017-09-05 21:43:08 -0700949 _Py_Finalizing = tstate;
950 _Py_Initialized = 0;
951 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000952
Victor Stinnere0deff32015-03-24 13:46:18 +0100953 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000954 if (flush_std_files() < 0) {
955 status = -1;
956 }
Nick Coghland6009512014-11-20 21:39:37 +1000957
958 /* Disable signal handling */
959 PyOS_FiniInterrupts();
960
961 /* Collect garbage. This may call finalizers; it's nice to call these
962 * before all modules are destroyed.
963 * XXX If a __del__ or weakref callback is triggered here, and tries to
964 * XXX import a module, bad things can happen, because Python no
965 * XXX longer believes it's initialized.
966 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
967 * XXX is easy to provoke that way. I've also seen, e.g.,
968 * XXX Exception exceptions.ImportError: 'No module named sha'
969 * XXX in <function callback at 0x008F5718> ignored
970 * XXX but I'm unclear on exactly how that one happens. In any case,
971 * XXX I haven't seen a real-life report of either of these.
972 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700973 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000974#ifdef COUNT_ALLOCS
975 /* With COUNT_ALLOCS, it helps to run GC multiple times:
976 each collection might release some types from the type
977 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700978 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000979 /* nothing */;
980#endif
981 /* Destroy all modules */
982 PyImport_Cleanup();
983
Victor Stinnere0deff32015-03-24 13:46:18 +0100984 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000985 if (flush_std_files() < 0) {
986 status = -1;
987 }
Nick Coghland6009512014-11-20 21:39:37 +1000988
989 /* Collect final garbage. This disposes of cycles created by
990 * class definitions, for example.
991 * XXX This is disabled because it caused too many problems. If
992 * XXX a __del__ or weakref callback triggers here, Python code has
993 * XXX a hard time running, because even the sys module has been
994 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
995 * XXX One symptom is a sequence of information-free messages
996 * XXX coming from threads (if a __del__ or callback is invoked,
997 * XXX other threads can execute too, and any exception they encounter
998 * XXX triggers a comedy of errors as subsystem after subsystem
999 * XXX fails to find what it *expects* to find in sys to help report
1000 * XXX the exception and consequent unexpected failures). I've also
1001 * XXX seen segfaults then, after adding print statements to the
1002 * XXX Python code getting called.
1003 */
1004#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001005 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001006#endif
1007
1008 /* Disable tracemalloc after all Python objects have been destroyed,
1009 so it is possible to use tracemalloc in objects destructor. */
1010 _PyTraceMalloc_Fini();
1011
1012 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1013 _PyImport_Fini();
1014
1015 /* Cleanup typeobject.c's internal caches. */
1016 _PyType_Fini();
1017
1018 /* unload faulthandler module */
1019 _PyFaulthandler_Fini();
1020
1021 /* Debugging stuff */
1022#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001023 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001024#endif
1025 /* dump hash stats */
1026 _PyHash_Fini();
1027
1028 _PY_DEBUG_PRINT_TOTAL_REFS();
1029
1030#ifdef Py_TRACE_REFS
1031 /* Display all objects still alive -- this can invoke arbitrary
1032 * __repr__ overrides, so requires a mostly-intact interpreter.
1033 * Alas, a lot of stuff may still be alive now that will be cleaned
1034 * up later.
1035 */
1036 if (Py_GETENV("PYTHONDUMPREFS"))
1037 _Py_PrintReferences(stderr);
1038#endif /* Py_TRACE_REFS */
1039
1040 /* Clear interpreter state and all thread states. */
1041 PyInterpreterState_Clear(interp);
1042
1043 /* Now we decref the exception classes. After this point nothing
1044 can raise an exception. That's okay, because each Fini() method
1045 below has been checked to make sure no exceptions are ever
1046 raised.
1047 */
1048
1049 _PyExc_Fini();
1050
1051 /* Sundry finalizers */
1052 PyMethod_Fini();
1053 PyFrame_Fini();
1054 PyCFunction_Fini();
1055 PyTuple_Fini();
1056 PyList_Fini();
1057 PySet_Fini();
1058 PyBytes_Fini();
1059 PyByteArray_Fini();
1060 PyLong_Fini();
1061 PyFloat_Fini();
1062 PyDict_Fini();
1063 PySlice_Fini();
1064 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001065 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001066 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001067 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001068
1069 /* Cleanup Unicode implementation */
1070 _PyUnicode_Fini();
1071
1072 /* reset file system default encoding */
1073 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1074 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1075 Py_FileSystemDefaultEncoding = NULL;
1076 }
1077
1078 /* XXX Still allocated:
1079 - various static ad-hoc pointers to interned strings
1080 - int and float free list blocks
1081 - whatever various modules and libraries allocate
1082 */
1083
1084 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1085
1086 /* Cleanup auto-thread-state */
1087#ifdef WITH_THREAD
1088 _PyGILState_Fini();
1089#endif /* WITH_THREAD */
1090
1091 /* Delete current thread. After this, many C API calls become crashy. */
1092 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001093
Nick Coghland6009512014-11-20 21:39:37 +10001094 PyInterpreterState_Delete(interp);
1095
1096#ifdef Py_TRACE_REFS
1097 /* Display addresses (& refcnts) of all objects still alive.
1098 * An address can be used to find the repr of the object, printed
1099 * above by _Py_PrintReferences.
1100 */
1101 if (Py_GETENV("PYTHONDUMPREFS"))
1102 _Py_PrintReferenceAddresses(stderr);
1103#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001104#ifdef WITH_PYMALLOC
1105 if (_PyMem_PymallocEnabled()) {
1106 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1107 if (opt != NULL && *opt != '\0')
1108 _PyObject_DebugMallocStats(stderr);
1109 }
Nick Coghland6009512014-11-20 21:39:37 +10001110#endif
1111
1112 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001113 return status;
1114}
1115
1116void
1117Py_Finalize(void)
1118{
1119 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001120}
1121
1122/* Create and initialize a new interpreter and thread, and return the
1123 new thread. This requires that Py_Initialize() has been called
1124 first.
1125
1126 Unsuccessful initialization yields a NULL pointer. Note that *no*
1127 exception information is available even in this case -- the
1128 exception information is held in the thread, and there is no
1129 thread.
1130
1131 Locking: as above.
1132
1133*/
1134
1135PyThreadState *
1136Py_NewInterpreter(void)
1137{
1138 PyInterpreterState *interp;
1139 PyThreadState *tstate, *save_tstate;
1140 PyObject *bimod, *sysmod;
1141
Eric Snow05351c12017-09-05 21:43:08 -07001142 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001143 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1144
Victor Stinnerd7292b52016-06-17 12:29:00 +02001145#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +01001146 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1147 interpreters: disable PyGILState_Check(). */
1148 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +03001149#endif
Victor Stinner8a1be612016-03-14 22:07:55 +01001150
Nick Coghland6009512014-11-20 21:39:37 +10001151 interp = PyInterpreterState_New();
1152 if (interp == NULL)
1153 return NULL;
1154
1155 tstate = PyThreadState_New(interp);
1156 if (tstate == NULL) {
1157 PyInterpreterState_Delete(interp);
1158 return NULL;
1159 }
1160
1161 save_tstate = PyThreadState_Swap(tstate);
1162
Eric Snow1abcf672017-05-23 21:46:51 -07001163 /* Copy the current interpreter config into the new interpreter */
1164 if (save_tstate != NULL) {
1165 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001166 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001167 } else {
1168 /* No current thread state, copy from the main interpreter */
1169 PyInterpreterState *main_interp = PyInterpreterState_Main();
1170 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001171 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001172 }
1173
Nick Coghland6009512014-11-20 21:39:37 +10001174 /* XXX The following is lax in error checking */
1175
Eric Snow86b7afd2017-09-04 17:54:09 -06001176 PyObject *modules = PyDict_New();
1177 if (modules == NULL)
1178 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +10001179
Eric Snow86b7afd2017-09-04 17:54:09 -06001180 sysmod = _PyImport_FindBuiltin("sys", modules);
1181 if (sysmod != NULL) {
1182 interp->sysdict = PyModule_GetDict(sysmod);
1183 if (interp->sysdict == NULL)
1184 goto handle_error;
1185 Py_INCREF(interp->sysdict);
1186 PyDict_SetItemString(interp->sysdict, "modules", modules);
1187 PySys_SetPath(Py_GetPath());
1188 _PySys_EndInit(interp->sysdict);
1189 }
1190
1191 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001192 if (bimod != NULL) {
1193 interp->builtins = PyModule_GetDict(bimod);
1194 if (interp->builtins == NULL)
1195 goto handle_error;
1196 Py_INCREF(interp->builtins);
1197 }
1198
1199 /* initialize builtin exceptions */
1200 _PyExc_Init(bimod);
1201
Nick Coghland6009512014-11-20 21:39:37 +10001202 if (bimod != NULL && sysmod != NULL) {
1203 PyObject *pstderr;
1204
Nick Coghland6009512014-11-20 21:39:37 +10001205 /* Set up a preliminary stderr printer until we have enough
1206 infrastructure for the io module in place. */
1207 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1208 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001209 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001210 _PySys_SetObjectId(&PyId_stderr, pstderr);
1211 PySys_SetObject("__stderr__", pstderr);
1212 Py_DECREF(pstderr);
1213
1214 _PyImportHooks_Init();
1215
Eric Snow1abcf672017-05-23 21:46:51 -07001216 initimport(interp, sysmod);
1217 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001218
1219 if (initfsencoding(interp) < 0)
1220 goto handle_error;
1221
1222 if (initstdio() < 0)
1223 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001224 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001225 initmain(interp);
1226 if (!Py_NoSiteFlag)
1227 initsite();
1228 }
1229
1230 if (!PyErr_Occurred())
1231 return tstate;
1232
1233handle_error:
1234 /* Oops, it didn't work. Undo it all. */
1235
1236 PyErr_PrintEx(0);
1237 PyThreadState_Clear(tstate);
1238 PyThreadState_Swap(save_tstate);
1239 PyThreadState_Delete(tstate);
1240 PyInterpreterState_Delete(interp);
1241
1242 return NULL;
1243}
1244
1245/* Delete an interpreter and its last thread. This requires that the
1246 given thread state is current, that the thread has no remaining
1247 frames, and that it is its interpreter's only remaining thread.
1248 It is a fatal error to violate these constraints.
1249
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001250 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001251 everything, regardless.)
1252
1253 Locking: as above.
1254
1255*/
1256
1257void
1258Py_EndInterpreter(PyThreadState *tstate)
1259{
1260 PyInterpreterState *interp = tstate->interp;
1261
1262 if (tstate != PyThreadState_GET())
1263 Py_FatalError("Py_EndInterpreter: thread is not current");
1264 if (tstate->frame != NULL)
1265 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1266
1267 wait_for_thread_shutdown();
1268
1269 if (tstate != interp->tstate_head || tstate->next != NULL)
1270 Py_FatalError("Py_EndInterpreter: not the last thread");
1271
1272 PyImport_Cleanup();
1273 PyInterpreterState_Clear(interp);
1274 PyThreadState_Swap(NULL);
1275 PyInterpreterState_Delete(interp);
1276}
1277
1278#ifdef MS_WINDOWS
1279static wchar_t *progname = L"python";
1280#else
1281static wchar_t *progname = L"python3";
1282#endif
1283
1284void
1285Py_SetProgramName(wchar_t *pn)
1286{
1287 if (pn && *pn)
1288 progname = pn;
1289}
1290
1291wchar_t *
1292Py_GetProgramName(void)
1293{
1294 return progname;
1295}
1296
1297static wchar_t *default_home = NULL;
1298static wchar_t env_home[MAXPATHLEN+1];
1299
1300void
1301Py_SetPythonHome(wchar_t *home)
1302{
1303 default_home = home;
1304}
1305
1306wchar_t *
1307Py_GetPythonHome(void)
1308{
1309 wchar_t *home = default_home;
1310 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1311 char* chome = Py_GETENV("PYTHONHOME");
1312 if (chome) {
1313 size_t size = Py_ARRAY_LENGTH(env_home);
1314 size_t r = mbstowcs(env_home, chome, size);
1315 if (r != (size_t)-1 && r < size)
1316 home = env_home;
1317 }
1318
1319 }
1320 return home;
1321}
1322
1323/* Create __main__ module */
1324
1325static void
1326initmain(PyInterpreterState *interp)
1327{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001328 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001329 m = PyImport_AddModule("__main__");
1330 if (m == NULL)
1331 Py_FatalError("can't create __main__ module");
1332 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001333 ann_dict = PyDict_New();
1334 if ((ann_dict == NULL) ||
1335 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1336 Py_FatalError("Failed to initialize __main__.__annotations__");
1337 }
1338 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001339 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1340 PyObject *bimod = PyImport_ImportModule("builtins");
1341 if (bimod == NULL) {
1342 Py_FatalError("Failed to retrieve builtins module");
1343 }
1344 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1345 Py_FatalError("Failed to initialize __main__.__builtins__");
1346 }
1347 Py_DECREF(bimod);
1348 }
1349 /* Main is a little special - imp.is_builtin("__main__") will return
1350 * False, but BuiltinImporter is still the most appropriate initial
1351 * setting for its __loader__ attribute. A more suitable value will
1352 * be set if __main__ gets further initialized later in the startup
1353 * process.
1354 */
1355 loader = PyDict_GetItemString(d, "__loader__");
1356 if (loader == NULL || loader == Py_None) {
1357 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1358 "BuiltinImporter");
1359 if (loader == NULL) {
1360 Py_FatalError("Failed to retrieve BuiltinImporter");
1361 }
1362 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1363 Py_FatalError("Failed to initialize __main__.__loader__");
1364 }
1365 Py_DECREF(loader);
1366 }
1367}
1368
1369static int
1370initfsencoding(PyInterpreterState *interp)
1371{
1372 PyObject *codec;
1373
Steve Dowercc16be82016-09-08 10:35:16 -07001374#ifdef MS_WINDOWS
1375 if (Py_LegacyWindowsFSEncodingFlag)
1376 {
1377 Py_FileSystemDefaultEncoding = "mbcs";
1378 Py_FileSystemDefaultEncodeErrors = "replace";
1379 }
1380 else
1381 {
1382 Py_FileSystemDefaultEncoding = "utf-8";
1383 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1384 }
1385#else
Nick Coghland6009512014-11-20 21:39:37 +10001386 if (Py_FileSystemDefaultEncoding == NULL)
1387 {
1388 Py_FileSystemDefaultEncoding = get_locale_encoding();
1389 if (Py_FileSystemDefaultEncoding == NULL)
1390 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1391
1392 Py_HasFileSystemDefaultEncoding = 0;
1393 interp->fscodec_initialized = 1;
1394 return 0;
1395 }
Steve Dowercc16be82016-09-08 10:35:16 -07001396#endif
Nick Coghland6009512014-11-20 21:39:37 +10001397
1398 /* the encoding is mbcs, utf-8 or ascii */
1399 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1400 if (!codec) {
1401 /* Such error can only occurs in critical situations: no more
1402 * memory, import a module of the standard library failed,
1403 * etc. */
1404 return -1;
1405 }
1406 Py_DECREF(codec);
1407 interp->fscodec_initialized = 1;
1408 return 0;
1409}
1410
1411/* Import the site module (not into __main__ though) */
1412
1413static void
1414initsite(void)
1415{
1416 PyObject *m;
1417 m = PyImport_ImportModule("site");
1418 if (m == NULL) {
1419 fprintf(stderr, "Failed to import the site module\n");
1420 PyErr_Print();
1421 Py_Finalize();
1422 exit(1);
1423 }
1424 else {
1425 Py_DECREF(m);
1426 }
1427}
1428
Victor Stinner874dbe82015-09-04 17:29:57 +02001429/* Check if a file descriptor is valid or not.
1430 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1431static int
1432is_valid_fd(int fd)
1433{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001434#ifdef __APPLE__
1435 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1436 and the other side of the pipe is closed, dup(1) succeed, whereas
1437 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1438 such error. */
1439 struct stat st;
1440 return (fstat(fd, &st) == 0);
1441#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001442 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001443 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001444 return 0;
1445 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001446 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1447 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1448 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001449 fd2 = dup(fd);
1450 if (fd2 >= 0)
1451 close(fd2);
1452 _Py_END_SUPPRESS_IPH
1453 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001454#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001455}
1456
1457/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001458static PyObject*
1459create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001460 int fd, int write_mode, const char* name,
1461 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001462{
1463 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1464 const char* mode;
1465 const char* newline;
1466 PyObject *line_buffering;
1467 int buffering, isatty;
1468 _Py_IDENTIFIER(open);
1469 _Py_IDENTIFIER(isatty);
1470 _Py_IDENTIFIER(TextIOWrapper);
1471 _Py_IDENTIFIER(mode);
1472
Victor Stinner874dbe82015-09-04 17:29:57 +02001473 if (!is_valid_fd(fd))
1474 Py_RETURN_NONE;
1475
Nick Coghland6009512014-11-20 21:39:37 +10001476 /* stdin is always opened in buffered mode, first because it shouldn't
1477 make a difference in common use cases, second because TextIOWrapper
1478 depends on the presence of a read1() method which only exists on
1479 buffered streams.
1480 */
1481 if (Py_UnbufferedStdioFlag && write_mode)
1482 buffering = 0;
1483 else
1484 buffering = -1;
1485 if (write_mode)
1486 mode = "wb";
1487 else
1488 mode = "rb";
1489 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1490 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001491 Py_None, Py_None, /* encoding, errors */
1492 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001493 if (buf == NULL)
1494 goto error;
1495
1496 if (buffering) {
1497 _Py_IDENTIFIER(raw);
1498 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1499 if (raw == NULL)
1500 goto error;
1501 }
1502 else {
1503 raw = buf;
1504 Py_INCREF(raw);
1505 }
1506
Steve Dower39294992016-08-30 21:22:36 -07001507#ifdef MS_WINDOWS
1508 /* Windows console IO is always UTF-8 encoded */
1509 if (PyWindowsConsoleIO_Check(raw))
1510 encoding = "utf-8";
1511#endif
1512
Nick Coghland6009512014-11-20 21:39:37 +10001513 text = PyUnicode_FromString(name);
1514 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1515 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001516 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001517 if (res == NULL)
1518 goto error;
1519 isatty = PyObject_IsTrue(res);
1520 Py_DECREF(res);
1521 if (isatty == -1)
1522 goto error;
1523 if (isatty || Py_UnbufferedStdioFlag)
1524 line_buffering = Py_True;
1525 else
1526 line_buffering = Py_False;
1527
1528 Py_CLEAR(raw);
1529 Py_CLEAR(text);
1530
1531#ifdef MS_WINDOWS
1532 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1533 newlines to "\n".
1534 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1535 newline = NULL;
1536#else
1537 /* sys.stdin: split lines at "\n".
1538 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1539 newline = "\n";
1540#endif
1541
1542 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1543 buf, encoding, errors,
1544 newline, line_buffering);
1545 Py_CLEAR(buf);
1546 if (stream == NULL)
1547 goto error;
1548
1549 if (write_mode)
1550 mode = "w";
1551 else
1552 mode = "r";
1553 text = PyUnicode_FromString(mode);
1554 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1555 goto error;
1556 Py_CLEAR(text);
1557 return stream;
1558
1559error:
1560 Py_XDECREF(buf);
1561 Py_XDECREF(stream);
1562 Py_XDECREF(text);
1563 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001564
Victor Stinner874dbe82015-09-04 17:29:57 +02001565 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1566 /* Issue #24891: the file descriptor was closed after the first
1567 is_valid_fd() check was called. Ignore the OSError and set the
1568 stream to None. */
1569 PyErr_Clear();
1570 Py_RETURN_NONE;
1571 }
1572 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001573}
1574
1575/* Initialize sys.stdin, stdout, stderr and builtins.open */
1576static int
1577initstdio(void)
1578{
1579 PyObject *iomod = NULL, *wrapper;
1580 PyObject *bimod = NULL;
1581 PyObject *m;
1582 PyObject *std = NULL;
1583 int status = 0, fd;
1584 PyObject * encoding_attr;
1585 char *pythonioencoding = NULL, *encoding, *errors;
1586
1587 /* Hack to avoid a nasty recursion issue when Python is invoked
1588 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1589 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1590 goto error;
1591 }
1592 Py_DECREF(m);
1593
1594 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1595 goto error;
1596 }
1597 Py_DECREF(m);
1598
1599 if (!(bimod = PyImport_ImportModule("builtins"))) {
1600 goto error;
1601 }
1602
1603 if (!(iomod = PyImport_ImportModule("io"))) {
1604 goto error;
1605 }
1606 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1607 goto error;
1608 }
1609
1610 /* Set builtins.open */
1611 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1612 Py_DECREF(wrapper);
1613 goto error;
1614 }
1615 Py_DECREF(wrapper);
1616
1617 encoding = _Py_StandardStreamEncoding;
1618 errors = _Py_StandardStreamErrors;
1619 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001620 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1621 if (pythonioencoding) {
1622 char *err;
1623 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1624 if (pythonioencoding == NULL) {
1625 PyErr_NoMemory();
1626 goto error;
1627 }
1628 err = strchr(pythonioencoding, ':');
1629 if (err) {
1630 *err = '\0';
1631 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001632 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001633 errors = err;
1634 }
1635 }
1636 if (*pythonioencoding && !encoding) {
1637 encoding = pythonioencoding;
1638 }
1639 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001640 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001641 /* Choose the default error handler based on the current locale */
1642 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001643 }
Nick Coghland6009512014-11-20 21:39:37 +10001644 }
1645
1646 /* Set sys.stdin */
1647 fd = fileno(stdin);
1648 /* Under some conditions stdin, stdout and stderr may not be connected
1649 * and fileno() may point to an invalid file descriptor. For example
1650 * GUI apps don't have valid standard streams by default.
1651 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001652 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1653 if (std == NULL)
1654 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001655 PySys_SetObject("__stdin__", std);
1656 _PySys_SetObjectId(&PyId_stdin, std);
1657 Py_DECREF(std);
1658
1659 /* Set sys.stdout */
1660 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001661 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1662 if (std == NULL)
1663 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001664 PySys_SetObject("__stdout__", std);
1665 _PySys_SetObjectId(&PyId_stdout, std);
1666 Py_DECREF(std);
1667
1668#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1669 /* Set sys.stderr, replaces the preliminary stderr */
1670 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001671 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1672 if (std == NULL)
1673 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001674
1675 /* Same as hack above, pre-import stderr's codec to avoid recursion
1676 when import.c tries to write to stderr in verbose mode. */
1677 encoding_attr = PyObject_GetAttrString(std, "encoding");
1678 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001679 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001680 if (std_encoding != NULL) {
1681 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1682 Py_XDECREF(codec_info);
1683 }
1684 Py_DECREF(encoding_attr);
1685 }
1686 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1687
1688 if (PySys_SetObject("__stderr__", std) < 0) {
1689 Py_DECREF(std);
1690 goto error;
1691 }
1692 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1693 Py_DECREF(std);
1694 goto error;
1695 }
1696 Py_DECREF(std);
1697#endif
1698
1699 if (0) {
1700 error:
1701 status = -1;
1702 }
1703
1704 /* We won't need them anymore. */
1705 if (_Py_StandardStreamEncoding) {
1706 PyMem_RawFree(_Py_StandardStreamEncoding);
1707 _Py_StandardStreamEncoding = NULL;
1708 }
1709 if (_Py_StandardStreamErrors) {
1710 PyMem_RawFree(_Py_StandardStreamErrors);
1711 _Py_StandardStreamErrors = NULL;
1712 }
1713 PyMem_Free(pythonioencoding);
1714 Py_XDECREF(bimod);
1715 Py_XDECREF(iomod);
1716 return status;
1717}
1718
1719
Victor Stinner10dc4842015-03-24 12:01:30 +01001720static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001721_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001722{
Victor Stinner10dc4842015-03-24 12:01:30 +01001723 fputc('\n', stderr);
1724 fflush(stderr);
1725
1726 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001727 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001728}
Victor Stinner791da1c2016-03-14 16:53:12 +01001729
1730/* Print the current exception (if an exception is set) with its traceback,
1731 or display the current Python stack.
1732
1733 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1734 called on catastrophic cases.
1735
1736 Return 1 if the traceback was displayed, 0 otherwise. */
1737
1738static int
1739_Py_FatalError_PrintExc(int fd)
1740{
1741 PyObject *ferr, *res;
1742 PyObject *exception, *v, *tb;
1743 int has_tb;
1744
1745 if (PyThreadState_GET() == NULL) {
1746 /* The GIL is released: trying to acquire it is likely to deadlock,
1747 just give up. */
1748 return 0;
1749 }
1750
1751 PyErr_Fetch(&exception, &v, &tb);
1752 if (exception == NULL) {
1753 /* No current exception */
1754 return 0;
1755 }
1756
1757 ferr = _PySys_GetObjectId(&PyId_stderr);
1758 if (ferr == NULL || ferr == Py_None) {
1759 /* sys.stderr is not set yet or set to None,
1760 no need to try to display the exception */
1761 return 0;
1762 }
1763
1764 PyErr_NormalizeException(&exception, &v, &tb);
1765 if (tb == NULL) {
1766 tb = Py_None;
1767 Py_INCREF(tb);
1768 }
1769 PyException_SetTraceback(v, tb);
1770 if (exception == NULL) {
1771 /* PyErr_NormalizeException() failed */
1772 return 0;
1773 }
1774
1775 has_tb = (tb != Py_None);
1776 PyErr_Display(exception, v, tb);
1777 Py_XDECREF(exception);
1778 Py_XDECREF(v);
1779 Py_XDECREF(tb);
1780
1781 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001782 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001783 if (res == NULL)
1784 PyErr_Clear();
1785 else
1786 Py_DECREF(res);
1787
1788 return has_tb;
1789}
1790
Nick Coghland6009512014-11-20 21:39:37 +10001791/* Print fatal error message and abort */
1792
1793void
1794Py_FatalError(const char *msg)
1795{
1796 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001797 static int reentrant = 0;
1798#ifdef MS_WINDOWS
1799 size_t len;
1800 WCHAR* buffer;
1801 size_t i;
1802#endif
1803
1804 if (reentrant) {
1805 /* Py_FatalError() caused a second fatal error.
1806 Example: flush_std_files() raises a recursion error. */
1807 goto exit;
1808 }
1809 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001810
1811 fprintf(stderr, "Fatal Python error: %s\n", msg);
1812 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001813
Victor Stinnere0deff32015-03-24 13:46:18 +01001814 /* Print the exception (if an exception is set) with its traceback,
1815 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001816 if (!_Py_FatalError_PrintExc(fd))
1817 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001818
Victor Stinner2025d782016-03-16 23:19:15 +01001819 /* The main purpose of faulthandler is to display the traceback. We already
1820 * did our best to display it. So faulthandler can now be disabled.
1821 * (Don't trigger it on abort().) */
1822 _PyFaulthandler_Fini();
1823
Victor Stinner791da1c2016-03-14 16:53:12 +01001824 /* Check if the current Python thread hold the GIL */
1825 if (PyThreadState_GET() != NULL) {
1826 /* Flush sys.stdout and sys.stderr */
1827 flush_std_files();
1828 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001829
Nick Coghland6009512014-11-20 21:39:37 +10001830#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001831 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001832
Victor Stinner53345a42015-03-25 01:55:14 +01001833 /* Convert the message to wchar_t. This uses a simple one-to-one
1834 conversion, assuming that the this error message actually uses ASCII
1835 only. If this ceases to be true, we will have to convert. */
1836 buffer = alloca( (len+1) * (sizeof *buffer));
1837 for( i=0; i<=len; ++i)
1838 buffer[i] = msg[i];
1839 OutputDebugStringW(L"Fatal Python error: ");
1840 OutputDebugStringW(buffer);
1841 OutputDebugStringW(L"\n");
1842#endif /* MS_WINDOWS */
1843
1844exit:
1845#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001846 DebugBreak();
1847#endif
Nick Coghland6009512014-11-20 21:39:37 +10001848 abort();
1849}
1850
1851/* Clean up and exit */
1852
1853#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001854# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001855#endif
1856
Eric Snow05351c12017-09-05 21:43:08 -07001857static void (*pyexitfunc)(void) = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001858/* For the atexit module. */
1859void _Py_PyAtExit(void (*func)(void))
1860{
Eric Snow05351c12017-09-05 21:43:08 -07001861 pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001862}
1863
1864static void
1865call_py_exitfuncs(void)
1866{
Eric Snow05351c12017-09-05 21:43:08 -07001867 if (pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001868 return;
1869
Eric Snow05351c12017-09-05 21:43:08 -07001870 (*pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001871 PyErr_Clear();
1872}
1873
1874/* Wait until threading._shutdown completes, provided
1875 the threading module was imported in the first place.
1876 The shutdown routine will wait until all non-daemon
1877 "threading" threads have completed. */
1878static void
1879wait_for_thread_shutdown(void)
1880{
1881#ifdef WITH_THREAD
1882 _Py_IDENTIFIER(_shutdown);
1883 PyObject *result;
Eric Snow86b7afd2017-09-04 17:54:09 -06001884 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001885 if (threading == NULL) {
1886 /* threading not imported */
1887 PyErr_Clear();
1888 return;
1889 }
Eric Snow86b7afd2017-09-04 17:54:09 -06001890 Py_INCREF(threading);
Victor Stinner3466bde2016-09-05 18:16:01 -07001891 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001892 if (result == NULL) {
1893 PyErr_WriteUnraisable(threading);
1894 }
1895 else {
1896 Py_DECREF(result);
1897 }
1898 Py_DECREF(threading);
1899#endif
1900}
1901
1902#define NEXITFUNCS 32
Eric Snow05351c12017-09-05 21:43:08 -07001903static void (*exitfuncs[NEXITFUNCS])(void);
1904static int nexitfuncs = 0;
1905
Nick Coghland6009512014-11-20 21:39:37 +10001906int Py_AtExit(void (*func)(void))
1907{
Eric Snow05351c12017-09-05 21:43:08 -07001908 if (nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001909 return -1;
Eric Snow05351c12017-09-05 21:43:08 -07001910 exitfuncs[nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001911 return 0;
1912}
1913
1914static void
1915call_ll_exitfuncs(void)
1916{
Eric Snow05351c12017-09-05 21:43:08 -07001917 while (nexitfuncs > 0)
1918 (*exitfuncs[--nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001919
1920 fflush(stdout);
1921 fflush(stderr);
1922}
1923
1924void
1925Py_Exit(int sts)
1926{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001927 if (Py_FinalizeEx() < 0) {
1928 sts = 120;
1929 }
Nick Coghland6009512014-11-20 21:39:37 +10001930
1931 exit(sts);
1932}
1933
1934static void
1935initsigs(void)
1936{
1937#ifdef SIGPIPE
1938 PyOS_setsig(SIGPIPE, SIG_IGN);
1939#endif
1940#ifdef SIGXFZ
1941 PyOS_setsig(SIGXFZ, SIG_IGN);
1942#endif
1943#ifdef SIGXFSZ
1944 PyOS_setsig(SIGXFSZ, SIG_IGN);
1945#endif
1946 PyOS_InitInterrupts(); /* May imply initsignal() */
1947 if (PyErr_Occurred()) {
1948 Py_FatalError("Py_Initialize: can't import signal");
1949 }
1950}
1951
1952
1953/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1954 *
1955 * All of the code in this function must only use async-signal-safe functions,
1956 * listed at `man 7 signal` or
1957 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1958 */
1959void
1960_Py_RestoreSignals(void)
1961{
1962#ifdef SIGPIPE
1963 PyOS_setsig(SIGPIPE, SIG_DFL);
1964#endif
1965#ifdef SIGXFZ
1966 PyOS_setsig(SIGXFZ, SIG_DFL);
1967#endif
1968#ifdef SIGXFSZ
1969 PyOS_setsig(SIGXFSZ, SIG_DFL);
1970#endif
1971}
1972
1973
1974/*
1975 * The file descriptor fd is considered ``interactive'' if either
1976 * a) isatty(fd) is TRUE, or
1977 * b) the -i flag was given, and the filename associated with
1978 * the descriptor is NULL or "<stdin>" or "???".
1979 */
1980int
1981Py_FdIsInteractive(FILE *fp, const char *filename)
1982{
1983 if (isatty((int)fileno(fp)))
1984 return 1;
1985 if (!Py_InteractiveFlag)
1986 return 0;
1987 return (filename == NULL) ||
1988 (strcmp(filename, "<stdin>") == 0) ||
1989 (strcmp(filename, "???") == 0);
1990}
1991
1992
Nick Coghland6009512014-11-20 21:39:37 +10001993/* Wrappers around sigaction() or signal(). */
1994
1995PyOS_sighandler_t
1996PyOS_getsig(int sig)
1997{
1998#ifdef HAVE_SIGACTION
1999 struct sigaction context;
2000 if (sigaction(sig, NULL, &context) == -1)
2001 return SIG_ERR;
2002 return context.sa_handler;
2003#else
2004 PyOS_sighandler_t handler;
2005/* Special signal handling for the secure CRT in Visual Studio 2005 */
2006#if defined(_MSC_VER) && _MSC_VER >= 1400
2007 switch (sig) {
2008 /* Only these signals are valid */
2009 case SIGINT:
2010 case SIGILL:
2011 case SIGFPE:
2012 case SIGSEGV:
2013 case SIGTERM:
2014 case SIGBREAK:
2015 case SIGABRT:
2016 break;
2017 /* Don't call signal() with other values or it will assert */
2018 default:
2019 return SIG_ERR;
2020 }
2021#endif /* _MSC_VER && _MSC_VER >= 1400 */
2022 handler = signal(sig, SIG_IGN);
2023 if (handler != SIG_ERR)
2024 signal(sig, handler);
2025 return handler;
2026#endif
2027}
2028
2029/*
2030 * All of the code in this function must only use async-signal-safe functions,
2031 * listed at `man 7 signal` or
2032 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2033 */
2034PyOS_sighandler_t
2035PyOS_setsig(int sig, PyOS_sighandler_t handler)
2036{
2037#ifdef HAVE_SIGACTION
2038 /* Some code in Modules/signalmodule.c depends on sigaction() being
2039 * used here if HAVE_SIGACTION is defined. Fix that if this code
2040 * changes to invalidate that assumption.
2041 */
2042 struct sigaction context, ocontext;
2043 context.sa_handler = handler;
2044 sigemptyset(&context.sa_mask);
2045 context.sa_flags = 0;
2046 if (sigaction(sig, &context, &ocontext) == -1)
2047 return SIG_ERR;
2048 return ocontext.sa_handler;
2049#else
2050 PyOS_sighandler_t oldhandler;
2051 oldhandler = signal(sig, handler);
2052#ifdef HAVE_SIGINTERRUPT
2053 siginterrupt(sig, 1);
2054#endif
2055 return oldhandler;
2056#endif
2057}
2058
2059#ifdef __cplusplus
2060}
2061#endif