blob: 5b13bc45822b2ad2acf899ccebe91a3e33257cd5 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
51extern wchar_t *Py_GetPath(void);
52
53extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
56static void initmain(PyInterpreterState *interp);
57static int initfsencoding(PyInterpreterState *interp);
58static void initsite(void);
59static int initstdio(void);
60static void initsigs(void);
61static void call_py_exitfuncs(void);
62static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
69extern int _PyFaulthandler_Init(void);
70extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
72extern int _PyTraceMalloc_Init(void);
73extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079_PyRuntimeState _PyRuntime = {0, 0};
80
81void
82_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
91 if (initialized)
92 return;
93 initialized = 1;
94 _PyRuntimeState_Init(&_PyRuntime);
95}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
119int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
120int Py_FrozenFlag; /* Needed by getpath.c */
121int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800122int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000123int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
124int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
125int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
126int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700127#ifdef MS_WINDOWS
128int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700129int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700130#endif
Nick Coghland6009512014-11-20 21:39:37 +1000131
Nick Coghland6009512014-11-20 21:39:37 +1000132/* Hack to force loading of object files */
133int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
134 PyOS_mystrnicmp; /* Python/pystrcmp.o */
135
136/* PyModule_GetWarningsModule is no longer necessary as of 2.6
137since _warnings is builtin. This API should not be used. */
138PyObject *
139PyModule_GetWarningsModule(void)
140{
141 return PyImport_ImportModule("warnings");
142}
143
Eric Snowc7ec9982017-05-23 23:00:52 -0700144
Eric Snow1abcf672017-05-23 21:46:51 -0700145/* APIs to access the initialization flags
146 *
147 * Can be called prior to Py_Initialize.
148 */
Nick Coghland6009512014-11-20 21:39:37 +1000149
Eric Snow1abcf672017-05-23 21:46:51 -0700150int
151_Py_IsCoreInitialized(void)
152{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600153 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700154}
Nick Coghland6009512014-11-20 21:39:37 +1000155
156int
157Py_IsInitialized(void)
158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600159 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000160}
161
162/* Helper to allow an embedding application to override the normal
163 * mechanism that attempts to figure out an appropriate IO encoding
164 */
165
166static char *_Py_StandardStreamEncoding = NULL;
167static char *_Py_StandardStreamErrors = NULL;
168
169int
170Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
171{
172 if (Py_IsInitialized()) {
173 /* This is too late to have any effect */
174 return -1;
175 }
176 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
177 * initialised yet.
178 *
179 * However, the raw memory allocators are initialised appropriately
180 * as C static variables, so _PyMem_RawStrdup is OK even though
181 * Py_Initialize hasn't been called yet.
182 */
183 if (encoding) {
184 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
185 if (!_Py_StandardStreamEncoding) {
186 return -2;
187 }
188 }
189 if (errors) {
190 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
191 if (!_Py_StandardStreamErrors) {
192 if (_Py_StandardStreamEncoding) {
193 PyMem_RawFree(_Py_StandardStreamEncoding);
194 }
195 return -3;
196 }
197 }
Steve Dower39294992016-08-30 21:22:36 -0700198#ifdef MS_WINDOWS
199 if (_Py_StandardStreamEncoding) {
200 /* Overriding the stream encoding implies legacy streams */
201 Py_LegacyWindowsStdioFlag = 1;
202 }
203#endif
Nick Coghland6009512014-11-20 21:39:37 +1000204 return 0;
205}
206
Nick Coghlan6ea41862017-06-11 13:16:15 +1000207
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000208/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
209 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000210 initializations fail, a fatal error is issued and the function does
211 not return. On return, the first thread and interpreter state have
212 been created.
213
214 Locking: you must hold the interpreter lock while calling this.
215 (If the lock has not yet been initialized, that's equivalent to
216 having the lock, but you cannot use multiple threads.)
217
218*/
219
220static int
221add_flag(int flag, const char *envs)
222{
223 int env = atoi(envs);
224 if (flag < env)
225 flag = env;
226 if (flag < 1)
227 flag = 1;
228 return flag;
229}
230
231static char*
232get_codec_name(const char *encoding)
233{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200234 const char *name_utf8;
235 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000236 PyObject *codec, *name = NULL;
237
238 codec = _PyCodec_Lookup(encoding);
239 if (!codec)
240 goto error;
241
242 name = _PyObject_GetAttrId(codec, &PyId_name);
243 Py_CLEAR(codec);
244 if (!name)
245 goto error;
246
Serhiy Storchaka06515832016-11-20 09:13:07 +0200247 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000248 if (name_utf8 == NULL)
249 goto error;
250 name_str = _PyMem_RawStrdup(name_utf8);
251 Py_DECREF(name);
252 if (name_str == NULL) {
253 PyErr_NoMemory();
254 return NULL;
255 }
256 return name_str;
257
258error:
259 Py_XDECREF(codec);
260 Py_XDECREF(name);
261 return NULL;
262}
263
264static char*
265get_locale_encoding(void)
266{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700267#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000268 char* codeset = nl_langinfo(CODESET);
269 if (!codeset || codeset[0] == '\0') {
270 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
271 return NULL;
272 }
273 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200274#elif defined(__ANDROID__)
275 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000276#else
277 PyErr_SetNone(PyExc_NotImplementedError);
278 return NULL;
279#endif
280}
281
282static void
Eric Snow1abcf672017-05-23 21:46:51 -0700283initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000284{
285 PyObject *importlib;
286 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000287 PyObject *value;
288
289 /* Import _importlib through its frozen version, _frozen_importlib. */
290 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
291 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
292 }
293 else if (Py_VerboseFlag) {
294 PySys_FormatStderr("import _frozen_importlib # frozen\n");
295 }
296 importlib = PyImport_AddModule("_frozen_importlib");
297 if (importlib == NULL) {
298 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
299 "sys.modules");
300 }
301 interp->importlib = importlib;
302 Py_INCREF(interp->importlib);
303
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300304 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
305 if (interp->import_func == NULL)
306 Py_FatalError("Py_Initialize: __import__ not found");
307 Py_INCREF(interp->import_func);
308
Victor Stinnercd6e6942015-09-18 09:11:57 +0200309 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000310 impmod = PyInit_imp();
311 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200312 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000313 }
314 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200315 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000316 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600317 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000318 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
319 }
320
Victor Stinnercd6e6942015-09-18 09:11:57 +0200321 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000322 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200323 if (value != NULL) {
324 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700325 value = PyObject_CallMethod(importlib,
326 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200327 }
Nick Coghland6009512014-11-20 21:39:37 +1000328 if (value == NULL) {
329 PyErr_Print();
330 Py_FatalError("Py_Initialize: importlib install failed");
331 }
332 Py_DECREF(value);
333 Py_DECREF(impmod);
334
335 _PyImportZip_Init();
336}
337
Eric Snow1abcf672017-05-23 21:46:51 -0700338static void
339initexternalimport(PyInterpreterState *interp)
340{
341 PyObject *value;
342 value = PyObject_CallMethod(interp->importlib,
343 "_install_external_importers", "");
344 if (value == NULL) {
345 PyErr_Print();
346 Py_FatalError("Py_EndInitialization: external importer setup failed");
347 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200348 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700349}
Nick Coghland6009512014-11-20 21:39:37 +1000350
Nick Coghlan6ea41862017-06-11 13:16:15 +1000351/* Helper functions to better handle the legacy C locale
352 *
353 * The legacy C locale assumes ASCII as the default text encoding, which
354 * causes problems not only for the CPython runtime, but also other
355 * components like GNU readline.
356 *
357 * Accordingly, when the CLI detects it, it attempts to coerce it to a
358 * more capable UTF-8 based alternative as follows:
359 *
360 * if (_Py_LegacyLocaleDetected()) {
361 * _Py_CoerceLegacyLocale();
362 * }
363 *
364 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
365 *
366 * Locale coercion also impacts the default error handler for the standard
367 * streams: while the usual default is "strict", the default for the legacy
368 * C locale and for any of the coercion target locales is "surrogateescape".
369 */
370
371int
372_Py_LegacyLocaleDetected(void)
373{
374#ifndef MS_WINDOWS
375 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000376 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
377 * the POSIX locale as a simple alias for the C locale, so
378 * we may also want to check for that explicitly.
379 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000380 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
381 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
382#else
383 /* Windows uses code pages instead of locales, so no locale is legacy */
384 return 0;
385#endif
386}
387
Nick Coghlaneb817952017-06-18 12:29:42 +1000388static const char *_C_LOCALE_WARNING =
389 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
390 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
391 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
392 "locales is recommended.\n";
393
394static int
395_legacy_locale_warnings_enabled(void)
396{
397 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
398 return (coerce_c_locale != NULL &&
399 strncmp(coerce_c_locale, "warn", 5) == 0);
400}
401
402static void
403_emit_stderr_warning_for_legacy_locale(void)
404{
405 if (_legacy_locale_warnings_enabled()) {
406 if (_Py_LegacyLocaleDetected()) {
407 fprintf(stderr, "%s", _C_LOCALE_WARNING);
408 }
409 }
410}
411
Nick Coghlan6ea41862017-06-11 13:16:15 +1000412typedef struct _CandidateLocale {
413 const char *locale_name; /* The locale to try as a coercion target */
414} _LocaleCoercionTarget;
415
416static _LocaleCoercionTarget _TARGET_LOCALES[] = {
417 {"C.UTF-8"},
418 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000419 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000420 {NULL}
421};
422
423static char *
424get_default_standard_stream_error_handler(void)
425{
426 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
427 if (ctype_loc != NULL) {
428 /* "surrogateescape" is the default in the legacy C locale */
429 if (strcmp(ctype_loc, "C") == 0) {
430 return "surrogateescape";
431 }
432
433#ifdef PY_COERCE_C_LOCALE
434 /* "surrogateescape" is the default in locale coercion target locales */
435 const _LocaleCoercionTarget *target = NULL;
436 for (target = _TARGET_LOCALES; target->locale_name; target++) {
437 if (strcmp(ctype_loc, target->locale_name) == 0) {
438 return "surrogateescape";
439 }
440 }
441#endif
442 }
443
444 /* Otherwise return NULL to request the typical default error handler */
445 return NULL;
446}
447
448#ifdef PY_COERCE_C_LOCALE
449static const char *_C_LOCALE_COERCION_WARNING =
450 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
451 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
452
453static void
454_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
455{
456 const char *newloc = target->locale_name;
457
458 /* Reset locale back to currently configured defaults */
459 setlocale(LC_ALL, "");
460
461 /* Set the relevant locale environment variable */
462 if (setenv("LC_CTYPE", newloc, 1)) {
463 fprintf(stderr,
464 "Error setting LC_CTYPE, skipping C locale coercion\n");
465 return;
466 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000467 if (_legacy_locale_warnings_enabled()) {
468 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
469 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000470
471 /* Reconfigure with the overridden environment variables */
472 setlocale(LC_ALL, "");
473}
474#endif
475
476void
477_Py_CoerceLegacyLocale(void)
478{
479#ifdef PY_COERCE_C_LOCALE
480 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
481 * the locale settings *before* we try to do anything with the command
482 * line arguments. For cross-platform debugging purposes, we also need
483 * to give end users a way to force even scripts that are otherwise
484 * isolated from their environment to use the legacy ASCII-centric C
485 * locale.
486 *
487 * Ignoring -E and -I is safe from a security perspective, as we only use
488 * the setting to turn *off* the implicit locale coercion, and anyone with
489 * access to the process environment already has the ability to set
490 * `LC_ALL=C` to override the C level locale settings anyway.
491 */
492 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
493 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
494 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
495 const char *locale_override = getenv("LC_ALL");
496 if (locale_override == NULL || *locale_override == '\0') {
497 /* LC_ALL is also not set (or is set to an empty string) */
498 const _LocaleCoercionTarget *target = NULL;
499 for (target = _TARGET_LOCALES; target->locale_name; target++) {
500 const char *new_locale = setlocale(LC_CTYPE,
501 target->locale_name);
502 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000503#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
504 /* Also ensure that nl_langinfo works in this locale */
505 char *codeset = nl_langinfo(CODESET);
506 if (!codeset || *codeset == '\0') {
507 /* CODESET is not set or empty, so skip coercion */
508 new_locale = NULL;
509 setlocale(LC_CTYPE, "");
510 continue;
511 }
512#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000513 /* Successfully configured locale, so make it the default */
514 _coerce_default_locale_settings(target);
515 return;
516 }
517 }
518 }
519 }
520 /* No C locale warning here, as Py_Initialize will emit one later */
521#endif
522}
523
524
Eric Snow1abcf672017-05-23 21:46:51 -0700525/* Global initializations. Can be undone by Py_Finalize(). Don't
526 call this twice without an intervening Py_Finalize() call.
527
528 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
529 must have a corresponding call to Py_Finalize.
530
531 Locking: you must hold the interpreter lock while calling these APIs.
532 (If the lock has not yet been initialized, that's equivalent to
533 having the lock, but you cannot use multiple threads.)
534
535*/
536
537/* Begin interpreter initialization
538 *
539 * On return, the first thread and interpreter state have been created,
540 * but the compiler, signal handling, multithreading and
541 * multiple interpreter support, and codec infrastructure are not yet
542 * available.
543 *
544 * The import system will support builtin and frozen modules only.
545 * The only supported io is writing to sys.stderr
546 *
547 * If any operation invoked by this function fails, a fatal error is
548 * issued and the function does not return.
549 *
550 * Any code invoked from this function should *not* assume it has access
551 * to the Python C API (unless the API is explicitly listed as being
552 * safe to call without calling Py_Initialize first)
553 */
554
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200555/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700556 * Py_ReadConfig and Py_EndInitialization
557 */
558
559void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000560{
561 PyInterpreterState *interp;
562 PyThreadState *tstate;
563 PyObject *bimod, *sysmod, *pstderr;
564 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700565 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700566 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000567
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600568 _PyRuntime_Initialize();
569
Eric Snow1abcf672017-05-23 21:46:51 -0700570 if (config != NULL) {
571 core_config = *config;
572 }
573
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600574 if (_PyRuntime.initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700575 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
576 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600577 if (_PyRuntime.core_initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700578 Py_FatalError("Py_InitializeCore: runtime core already initialized");
579 }
580
581 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
582 * threads behave a little more gracefully at interpreter shutdown.
583 * We clobber it here so the new interpreter can start with a clean
584 * slate.
585 *
586 * However, this may still lead to misbehaviour if there are daemon
587 * threads still hanging around from a previous Py_Initialize/Finalize
588 * pair :(
589 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600590 _PyRuntime.finalizing = NULL;
591
592 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
593 fprintf(stderr,
594 "Error in PYTHONMALLOC: unknown allocator \"%s\"!\n",
595 core_config.allocator);
596 exit(1);
597 }
Nick Coghland6009512014-11-20 21:39:37 +1000598
Nick Coghlan6ea41862017-06-11 13:16:15 +1000599#ifdef __ANDROID__
600 /* Passing "" to setlocale() on Android requests the C locale rather
601 * than checking environment variables, so request C.UTF-8 explicitly
602 */
603 setlocale(LC_CTYPE, "C.UTF-8");
604#else
605#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000606 /* Set up the LC_CTYPE locale, so we can obtain
607 the locale's charset without having to switch
608 locales. */
609 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000610 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000611#endif
Nick Coghland6009512014-11-20 21:39:37 +1000612#endif
613
614 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
615 Py_DebugFlag = add_flag(Py_DebugFlag, p);
616 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
617 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
618 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
619 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
620 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
621 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700622 /* The variable is only tested for existence here;
623 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000624 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
625 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700626#ifdef MS_WINDOWS
627 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
628 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700629 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
630 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700631#endif
Nick Coghland6009512014-11-20 21:39:37 +1000632
Eric Snow1abcf672017-05-23 21:46:51 -0700633 _Py_HashRandomization_Init(&core_config);
634 if (!core_config.use_hash_seed || core_config.hash_seed) {
635 /* Random or non-zero hash seed */
636 Py_HashRandomizationFlag = 1;
637 }
Nick Coghland6009512014-11-20 21:39:37 +1000638
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600639 _PyInterpreterState_Enable(&_PyRuntime);
Nick Coghland6009512014-11-20 21:39:37 +1000640 interp = PyInterpreterState_New();
641 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700642 Py_FatalError("Py_InitializeCore: can't make main interpreter");
643 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700644 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000645
646 tstate = PyThreadState_New(interp);
647 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700648 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000649 (void) PyThreadState_Swap(tstate);
650
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000651 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000652 destroying the GIL might fail when it is being referenced from
653 another running thread (see issue #9901).
654 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000655 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000656 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000657 /* Auto-thread-state API */
658 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000659
660 _Py_ReadyTypes();
661
662 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700663 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000664
665 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700666 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000667
668 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700669 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000670
671 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700672 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000673
Eric Snowd393c1b2017-09-14 12:18:12 -0600674 PyObject *modules = PyDict_New();
675 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700676 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600677 interp->modules = modules;
678
679 sysmod = _PySys_BeginInit();
680 if (sysmod == NULL)
681 Py_FatalError("Py_InitializeCore: can't initialize sys");
682 interp->sysdict = PyModule_GetDict(sysmod);
683 if (interp->sysdict == NULL)
684 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
685 Py_INCREF(interp->sysdict);
686 PyDict_SetItemString(interp->sysdict, "modules", modules);
687 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000688
689 /* Init Unicode implementation; relies on the codec registry */
690 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700691 Py_FatalError("Py_InitializeCore: can't initialize unicode");
692
Nick Coghland6009512014-11-20 21:39:37 +1000693 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700694 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000695
696 bimod = _PyBuiltin_Init();
697 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700698 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600699 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000700 interp->builtins = PyModule_GetDict(bimod);
701 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700702 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000703 Py_INCREF(interp->builtins);
704
705 /* initialize builtin exceptions */
706 _PyExc_Init(bimod);
707
Nick Coghland6009512014-11-20 21:39:37 +1000708 /* Set up a preliminary stderr printer until we have enough
709 infrastructure for the io module in place. */
710 pstderr = PyFile_NewStdPrinter(fileno(stderr));
711 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700712 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000713 _PySys_SetObjectId(&PyId_stderr, pstderr);
714 PySys_SetObject("__stderr__", pstderr);
715 Py_DECREF(pstderr);
716
717 _PyImport_Init();
718
719 _PyImportHooks_Init();
720
721 /* Initialize _warnings. */
722 _PyWarnings_Init();
723
Eric Snow1abcf672017-05-23 21:46:51 -0700724 /* This call sets up builtin and frozen import support */
725 if (!interp->core_config._disable_importlib) {
726 initimport(interp, sysmod);
727 }
728
729 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600730 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700731}
732
Eric Snowc7ec9982017-05-23 23:00:52 -0700733/* Read configuration settings from standard locations
734 *
735 * This function doesn't make any changes to the interpreter state - it
736 * merely populates any missing configuration settings. This allows an
737 * embedding application to completely override a config option by
738 * setting it before calling this function, or else modify the default
739 * setting before passing the fully populated config to Py_EndInitialization.
740 *
741 * More advanced selective initialization tricks are possible by calling
742 * this function multiple times with various preconfigured settings.
743 */
744
745int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
746{
747 /* Signal handlers are installed by default */
748 if (config->install_signal_handlers < 0) {
749 config->install_signal_handlers = 1;
750 }
751
752 return 0;
753}
754
755/* Update interpreter state based on supplied configuration settings
756 *
757 * After calling this function, most of the restrictions on the interpreter
758 * are lifted. The only remaining incomplete settings are those related
759 * to the main module (sys.argv[0], __main__ metadata)
760 *
761 * Calling this when the interpreter is not initializing, is already
762 * initialized or without a valid current thread state is a fatal error.
763 * Other errors should be reported as normal Python exceptions with a
764 * non-zero return code.
765 */
766int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700767{
768 PyInterpreterState *interp;
769 PyThreadState *tstate;
770
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600771 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700772 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
773 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600774 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700775 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
776 }
777
Eric Snow1abcf672017-05-23 21:46:51 -0700778 /* Get current thread state and interpreter pointer */
779 tstate = PyThreadState_GET();
780 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700781 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700782 interp = tstate->interp;
783 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700784 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700785
786 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700787 interp->config = *config;
788
Eric Snow1abcf672017-05-23 21:46:51 -0700789 if (interp->core_config._disable_importlib) {
790 /* Special mode for freeze_importlib: run with no import system
791 *
792 * This means anything which needs support from extension modules
793 * or pure Python code in the standard library won't work.
794 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600795 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700796 return 0;
797 }
798 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000799
Victor Stinner13019fd2015-04-03 13:10:54 +0200800 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700801 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200802
Eric Snow1abcf672017-05-23 21:46:51 -0700803 /* Finish setting up the sys module and import system */
804 /* GetPath may initialize state that _PySys_EndInit locks
805 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700806 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700807 PySys_SetPath(Py_GetPath());
808 if (_PySys_EndInit(interp->sysdict) < 0)
809 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700810 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000811
812 /* initialize the faulthandler module */
813 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700814 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000815
Nick Coghland6009512014-11-20 21:39:37 +1000816 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700817 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000818
Eric Snowc7ec9982017-05-23 23:00:52 -0700819 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000820 initsigs(); /* Signal handling stuff, including initintr() */
821
822 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700823 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000824
825 initmain(interp); /* Module __main__ */
826 if (initstdio() < 0)
827 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700828 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000829
830 /* Initialize warnings. */
831 if (PySys_HasWarnOptions()) {
832 PyObject *warnings_module = PyImport_ImportModule("warnings");
833 if (warnings_module == NULL) {
834 fprintf(stderr, "'import warnings' failed; traceback:\n");
835 PyErr_Print();
836 }
837 Py_XDECREF(warnings_module);
838 }
839
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600840 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700841
Nick Coghland6009512014-11-20 21:39:37 +1000842 if (!Py_NoSiteFlag)
843 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700844
Eric Snowc7ec9982017-05-23 23:00:52 -0700845 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000846}
847
Eric Snowc7ec9982017-05-23 23:00:52 -0700848#undef _INIT_DEBUG_PRINT
849
Nick Coghland6009512014-11-20 21:39:37 +1000850void
Eric Snow1abcf672017-05-23 21:46:51 -0700851_Py_InitializeEx_Private(int install_sigs, int install_importlib)
852{
853 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700854 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700855
856 /* TODO: Moar config options! */
857 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
858 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700859 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700860 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700861 /* TODO: Print any exceptions raised by these operations */
862 if (_Py_ReadMainInterpreterConfig(&config))
863 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
864 if (_Py_InitializeMainInterpreter(&config))
865 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700866}
867
868
869void
Nick Coghland6009512014-11-20 21:39:37 +1000870Py_InitializeEx(int install_sigs)
871{
872 _Py_InitializeEx_Private(install_sigs, 1);
873}
874
875void
876Py_Initialize(void)
877{
878 Py_InitializeEx(1);
879}
880
881
882#ifdef COUNT_ALLOCS
883extern void dump_counts(FILE*);
884#endif
885
886/* Flush stdout and stderr */
887
888static int
889file_is_closed(PyObject *fobj)
890{
891 int r;
892 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
893 if (tmp == NULL) {
894 PyErr_Clear();
895 return 0;
896 }
897 r = PyObject_IsTrue(tmp);
898 Py_DECREF(tmp);
899 if (r < 0)
900 PyErr_Clear();
901 return r > 0;
902}
903
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000904static int
Nick Coghland6009512014-11-20 21:39:37 +1000905flush_std_files(void)
906{
907 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
908 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
909 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000910 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000911
912 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700913 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000914 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000915 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000916 status = -1;
917 }
Nick Coghland6009512014-11-20 21:39:37 +1000918 else
919 Py_DECREF(tmp);
920 }
921
922 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700923 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000924 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000925 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000926 status = -1;
927 }
Nick Coghland6009512014-11-20 21:39:37 +1000928 else
929 Py_DECREF(tmp);
930 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000931
932 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000933}
934
935/* Undo the effect of Py_Initialize().
936
937 Beware: if multiple interpreter and/or thread states exist, these
938 are not wiped out; only the current thread and interpreter state
939 are deleted. But since everything else is deleted, those other
940 interpreter and thread states should no longer be used.
941
942 (XXX We should do better, e.g. wipe out all interpreters and
943 threads.)
944
945 Locking: as above.
946
947*/
948
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000949int
950Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000951{
952 PyInterpreterState *interp;
953 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000954 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000955
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600956 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000957 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000958
959 wait_for_thread_shutdown();
960
961 /* The interpreter is still entirely intact at this point, and the
962 * exit funcs may be relying on that. In particular, if some thread
963 * or exit func is still waiting to do an import, the import machinery
964 * expects Py_IsInitialized() to return true. So don't say the
965 * interpreter is uninitialized until after the exit funcs have run.
966 * Note that Threading.py uses an exit func to do a join on all the
967 * threads created thru it, so this also protects pending imports in
968 * the threads created via Threading.
969 */
970 call_py_exitfuncs();
971
972 /* Get current thread state and interpreter pointer */
973 tstate = PyThreadState_GET();
974 interp = tstate->interp;
975
976 /* Remaining threads (e.g. daemon threads) will automatically exit
977 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600978 _PyRuntime.finalizing = tstate;
979 _PyRuntime.initialized = 0;
980 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000981
Victor Stinnere0deff32015-03-24 13:46:18 +0100982 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000983 if (flush_std_files() < 0) {
984 status = -1;
985 }
Nick Coghland6009512014-11-20 21:39:37 +1000986
987 /* Disable signal handling */
988 PyOS_FiniInterrupts();
989
990 /* Collect garbage. This may call finalizers; it's nice to call these
991 * before all modules are destroyed.
992 * XXX If a __del__ or weakref callback is triggered here, and tries to
993 * XXX import a module, bad things can happen, because Python no
994 * XXX longer believes it's initialized.
995 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
996 * XXX is easy to provoke that way. I've also seen, e.g.,
997 * XXX Exception exceptions.ImportError: 'No module named sha'
998 * XXX in <function callback at 0x008F5718> ignored
999 * XXX but I'm unclear on exactly how that one happens. In any case,
1000 * XXX I haven't seen a real-life report of either of these.
1001 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001002 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001003#ifdef COUNT_ALLOCS
1004 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1005 each collection might release some types from the type
1006 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001007 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001008 /* nothing */;
1009#endif
Eric Snowdae02762017-09-14 00:35:58 -07001010
1011#ifdef Py_REF_DEBUG
1012 PyObject *showrefcount = _PyDebug_XOptionShowRefCount();
1013#endif
1014
Nick Coghland6009512014-11-20 21:39:37 +10001015 /* Destroy all modules */
1016 PyImport_Cleanup();
1017
Victor Stinnere0deff32015-03-24 13:46:18 +01001018 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 if (flush_std_files() < 0) {
1020 status = -1;
1021 }
Nick Coghland6009512014-11-20 21:39:37 +10001022
1023 /* Collect final garbage. This disposes of cycles created by
1024 * class definitions, for example.
1025 * XXX This is disabled because it caused too many problems. If
1026 * XXX a __del__ or weakref callback triggers here, Python code has
1027 * XXX a hard time running, because even the sys module has been
1028 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1029 * XXX One symptom is a sequence of information-free messages
1030 * XXX coming from threads (if a __del__ or callback is invoked,
1031 * XXX other threads can execute too, and any exception they encounter
1032 * XXX triggers a comedy of errors as subsystem after subsystem
1033 * XXX fails to find what it *expects* to find in sys to help report
1034 * XXX the exception and consequent unexpected failures). I've also
1035 * XXX seen segfaults then, after adding print statements to the
1036 * XXX Python code getting called.
1037 */
1038#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001039 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001040#endif
1041
1042 /* Disable tracemalloc after all Python objects have been destroyed,
1043 so it is possible to use tracemalloc in objects destructor. */
1044 _PyTraceMalloc_Fini();
1045
1046 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1047 _PyImport_Fini();
1048
1049 /* Cleanup typeobject.c's internal caches. */
1050 _PyType_Fini();
1051
1052 /* unload faulthandler module */
1053 _PyFaulthandler_Fini();
1054
1055 /* Debugging stuff */
1056#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001057 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001058#endif
1059 /* dump hash stats */
1060 _PyHash_Fini();
1061
Eric Snowdae02762017-09-14 00:35:58 -07001062#ifdef Py_REF_DEBUG
1063 if (showrefcount == Py_True)
1064 _PyDebug_PrintTotalRefs();
1065#endif
Nick Coghland6009512014-11-20 21:39:37 +10001066
1067#ifdef Py_TRACE_REFS
1068 /* Display all objects still alive -- this can invoke arbitrary
1069 * __repr__ overrides, so requires a mostly-intact interpreter.
1070 * Alas, a lot of stuff may still be alive now that will be cleaned
1071 * up later.
1072 */
1073 if (Py_GETENV("PYTHONDUMPREFS"))
1074 _Py_PrintReferences(stderr);
1075#endif /* Py_TRACE_REFS */
1076
1077 /* Clear interpreter state and all thread states. */
1078 PyInterpreterState_Clear(interp);
1079
1080 /* Now we decref the exception classes. After this point nothing
1081 can raise an exception. That's okay, because each Fini() method
1082 below has been checked to make sure no exceptions are ever
1083 raised.
1084 */
1085
1086 _PyExc_Fini();
1087
1088 /* Sundry finalizers */
1089 PyMethod_Fini();
1090 PyFrame_Fini();
1091 PyCFunction_Fini();
1092 PyTuple_Fini();
1093 PyList_Fini();
1094 PySet_Fini();
1095 PyBytes_Fini();
1096 PyByteArray_Fini();
1097 PyLong_Fini();
1098 PyFloat_Fini();
1099 PyDict_Fini();
1100 PySlice_Fini();
1101 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001102 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001103 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001104 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001105
1106 /* Cleanup Unicode implementation */
1107 _PyUnicode_Fini();
1108
1109 /* reset file system default encoding */
1110 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1111 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1112 Py_FileSystemDefaultEncoding = NULL;
1113 }
1114
1115 /* XXX Still allocated:
1116 - various static ad-hoc pointers to interned strings
1117 - int and float free list blocks
1118 - whatever various modules and libraries allocate
1119 */
1120
1121 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1122
1123 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001124 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001125
1126 /* Delete current thread. After this, many C API calls become crashy. */
1127 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001128
Nick Coghland6009512014-11-20 21:39:37 +10001129 PyInterpreterState_Delete(interp);
1130
1131#ifdef Py_TRACE_REFS
1132 /* Display addresses (& refcnts) of all objects still alive.
1133 * An address can be used to find the repr of the object, printed
1134 * above by _Py_PrintReferences.
1135 */
1136 if (Py_GETENV("PYTHONDUMPREFS"))
1137 _Py_PrintReferenceAddresses(stderr);
1138#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001139#ifdef WITH_PYMALLOC
1140 if (_PyMem_PymallocEnabled()) {
1141 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1142 if (opt != NULL && *opt != '\0')
1143 _PyObject_DebugMallocStats(stderr);
1144 }
Nick Coghland6009512014-11-20 21:39:37 +10001145#endif
1146
1147 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001148 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001149 return status;
1150}
1151
1152void
1153Py_Finalize(void)
1154{
1155 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001156}
1157
1158/* Create and initialize a new interpreter and thread, and return the
1159 new thread. This requires that Py_Initialize() has been called
1160 first.
1161
1162 Unsuccessful initialization yields a NULL pointer. Note that *no*
1163 exception information is available even in this case -- the
1164 exception information is held in the thread, and there is no
1165 thread.
1166
1167 Locking: as above.
1168
1169*/
1170
1171PyThreadState *
1172Py_NewInterpreter(void)
1173{
1174 PyInterpreterState *interp;
1175 PyThreadState *tstate, *save_tstate;
1176 PyObject *bimod, *sysmod;
1177
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001178 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001179 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1180
Victor Stinner8a1be612016-03-14 22:07:55 +01001181 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1182 interpreters: disable PyGILState_Check(). */
1183 _PyGILState_check_enabled = 0;
1184
Nick Coghland6009512014-11-20 21:39:37 +10001185 interp = PyInterpreterState_New();
1186 if (interp == NULL)
1187 return NULL;
1188
1189 tstate = PyThreadState_New(interp);
1190 if (tstate == NULL) {
1191 PyInterpreterState_Delete(interp);
1192 return NULL;
1193 }
1194
1195 save_tstate = PyThreadState_Swap(tstate);
1196
Eric Snow1abcf672017-05-23 21:46:51 -07001197 /* Copy the current interpreter config into the new interpreter */
1198 if (save_tstate != NULL) {
1199 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001200 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001201 } else {
1202 /* No current thread state, copy from the main interpreter */
1203 PyInterpreterState *main_interp = PyInterpreterState_Main();
1204 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001205 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001206 }
1207
Nick Coghland6009512014-11-20 21:39:37 +10001208 /* XXX The following is lax in error checking */
1209
Eric Snowd393c1b2017-09-14 12:18:12 -06001210 PyObject *modules = PyDict_New();
1211 if (modules == NULL)
1212 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
1213 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001214
Eric Snowd393c1b2017-09-14 12:18:12 -06001215 sysmod = _PyImport_FindBuiltin("sys", modules);
1216 if (sysmod != NULL) {
1217 interp->sysdict = PyModule_GetDict(sysmod);
1218 if (interp->sysdict == NULL)
1219 goto handle_error;
1220 Py_INCREF(interp->sysdict);
1221 PyDict_SetItemString(interp->sysdict, "modules", modules);
1222 PySys_SetPath(Py_GetPath());
1223 _PySys_EndInit(interp->sysdict);
1224 }
1225
1226 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001227 if (bimod != NULL) {
1228 interp->builtins = PyModule_GetDict(bimod);
1229 if (interp->builtins == NULL)
1230 goto handle_error;
1231 Py_INCREF(interp->builtins);
1232 }
1233
1234 /* initialize builtin exceptions */
1235 _PyExc_Init(bimod);
1236
Nick Coghland6009512014-11-20 21:39:37 +10001237 if (bimod != NULL && sysmod != NULL) {
1238 PyObject *pstderr;
1239
Nick Coghland6009512014-11-20 21:39:37 +10001240 /* Set up a preliminary stderr printer until we have enough
1241 infrastructure for the io module in place. */
1242 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1243 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001244 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001245 _PySys_SetObjectId(&PyId_stderr, pstderr);
1246 PySys_SetObject("__stderr__", pstderr);
1247 Py_DECREF(pstderr);
1248
1249 _PyImportHooks_Init();
1250
Eric Snow1abcf672017-05-23 21:46:51 -07001251 initimport(interp, sysmod);
1252 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001253
1254 if (initfsencoding(interp) < 0)
1255 goto handle_error;
1256
1257 if (initstdio() < 0)
1258 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001259 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001260 initmain(interp);
1261 if (!Py_NoSiteFlag)
1262 initsite();
1263 }
1264
1265 if (!PyErr_Occurred())
1266 return tstate;
1267
1268handle_error:
1269 /* Oops, it didn't work. Undo it all. */
1270
1271 PyErr_PrintEx(0);
1272 PyThreadState_Clear(tstate);
1273 PyThreadState_Swap(save_tstate);
1274 PyThreadState_Delete(tstate);
1275 PyInterpreterState_Delete(interp);
1276
1277 return NULL;
1278}
1279
1280/* Delete an interpreter and its last thread. This requires that the
1281 given thread state is current, that the thread has no remaining
1282 frames, and that it is its interpreter's only remaining thread.
1283 It is a fatal error to violate these constraints.
1284
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001285 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001286 everything, regardless.)
1287
1288 Locking: as above.
1289
1290*/
1291
1292void
1293Py_EndInterpreter(PyThreadState *tstate)
1294{
1295 PyInterpreterState *interp = tstate->interp;
1296
1297 if (tstate != PyThreadState_GET())
1298 Py_FatalError("Py_EndInterpreter: thread is not current");
1299 if (tstate->frame != NULL)
1300 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1301
1302 wait_for_thread_shutdown();
1303
1304 if (tstate != interp->tstate_head || tstate->next != NULL)
1305 Py_FatalError("Py_EndInterpreter: not the last thread");
1306
1307 PyImport_Cleanup();
1308 PyInterpreterState_Clear(interp);
1309 PyThreadState_Swap(NULL);
1310 PyInterpreterState_Delete(interp);
1311}
1312
1313#ifdef MS_WINDOWS
1314static wchar_t *progname = L"python";
1315#else
1316static wchar_t *progname = L"python3";
1317#endif
1318
1319void
1320Py_SetProgramName(wchar_t *pn)
1321{
1322 if (pn && *pn)
1323 progname = pn;
1324}
1325
1326wchar_t *
1327Py_GetProgramName(void)
1328{
1329 return progname;
1330}
1331
1332static wchar_t *default_home = NULL;
1333static wchar_t env_home[MAXPATHLEN+1];
1334
1335void
1336Py_SetPythonHome(wchar_t *home)
1337{
1338 default_home = home;
1339}
1340
1341wchar_t *
1342Py_GetPythonHome(void)
1343{
1344 wchar_t *home = default_home;
1345 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1346 char* chome = Py_GETENV("PYTHONHOME");
1347 if (chome) {
1348 size_t size = Py_ARRAY_LENGTH(env_home);
1349 size_t r = mbstowcs(env_home, chome, size);
1350 if (r != (size_t)-1 && r < size)
1351 home = env_home;
1352 }
1353
1354 }
1355 return home;
1356}
1357
1358/* Create __main__ module */
1359
1360static void
1361initmain(PyInterpreterState *interp)
1362{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001363 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001364 m = PyImport_AddModule("__main__");
1365 if (m == NULL)
1366 Py_FatalError("can't create __main__ module");
1367 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001368 ann_dict = PyDict_New();
1369 if ((ann_dict == NULL) ||
1370 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1371 Py_FatalError("Failed to initialize __main__.__annotations__");
1372 }
1373 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001374 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1375 PyObject *bimod = PyImport_ImportModule("builtins");
1376 if (bimod == NULL) {
1377 Py_FatalError("Failed to retrieve builtins module");
1378 }
1379 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1380 Py_FatalError("Failed to initialize __main__.__builtins__");
1381 }
1382 Py_DECREF(bimod);
1383 }
1384 /* Main is a little special - imp.is_builtin("__main__") will return
1385 * False, but BuiltinImporter is still the most appropriate initial
1386 * setting for its __loader__ attribute. A more suitable value will
1387 * be set if __main__ gets further initialized later in the startup
1388 * process.
1389 */
1390 loader = PyDict_GetItemString(d, "__loader__");
1391 if (loader == NULL || loader == Py_None) {
1392 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1393 "BuiltinImporter");
1394 if (loader == NULL) {
1395 Py_FatalError("Failed to retrieve BuiltinImporter");
1396 }
1397 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1398 Py_FatalError("Failed to initialize __main__.__loader__");
1399 }
1400 Py_DECREF(loader);
1401 }
1402}
1403
1404static int
1405initfsencoding(PyInterpreterState *interp)
1406{
1407 PyObject *codec;
1408
Steve Dowercc16be82016-09-08 10:35:16 -07001409#ifdef MS_WINDOWS
1410 if (Py_LegacyWindowsFSEncodingFlag)
1411 {
1412 Py_FileSystemDefaultEncoding = "mbcs";
1413 Py_FileSystemDefaultEncodeErrors = "replace";
1414 }
1415 else
1416 {
1417 Py_FileSystemDefaultEncoding = "utf-8";
1418 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1419 }
1420#else
Nick Coghland6009512014-11-20 21:39:37 +10001421 if (Py_FileSystemDefaultEncoding == NULL)
1422 {
1423 Py_FileSystemDefaultEncoding = get_locale_encoding();
1424 if (Py_FileSystemDefaultEncoding == NULL)
1425 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1426
1427 Py_HasFileSystemDefaultEncoding = 0;
1428 interp->fscodec_initialized = 1;
1429 return 0;
1430 }
Steve Dowercc16be82016-09-08 10:35:16 -07001431#endif
Nick Coghland6009512014-11-20 21:39:37 +10001432
1433 /* the encoding is mbcs, utf-8 or ascii */
1434 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1435 if (!codec) {
1436 /* Such error can only occurs in critical situations: no more
1437 * memory, import a module of the standard library failed,
1438 * etc. */
1439 return -1;
1440 }
1441 Py_DECREF(codec);
1442 interp->fscodec_initialized = 1;
1443 return 0;
1444}
1445
1446/* Import the site module (not into __main__ though) */
1447
1448static void
1449initsite(void)
1450{
1451 PyObject *m;
1452 m = PyImport_ImportModule("site");
1453 if (m == NULL) {
1454 fprintf(stderr, "Failed to import the site module\n");
1455 PyErr_Print();
1456 Py_Finalize();
1457 exit(1);
1458 }
1459 else {
1460 Py_DECREF(m);
1461 }
1462}
1463
Victor Stinner874dbe82015-09-04 17:29:57 +02001464/* Check if a file descriptor is valid or not.
1465 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1466static int
1467is_valid_fd(int fd)
1468{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001469#ifdef __APPLE__
1470 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1471 and the other side of the pipe is closed, dup(1) succeed, whereas
1472 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1473 such error. */
1474 struct stat st;
1475 return (fstat(fd, &st) == 0);
1476#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001477 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001478 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001479 return 0;
1480 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001481 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1482 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1483 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001484 fd2 = dup(fd);
1485 if (fd2 >= 0)
1486 close(fd2);
1487 _Py_END_SUPPRESS_IPH
1488 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001489#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001490}
1491
1492/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001493static PyObject*
1494create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001495 int fd, int write_mode, const char* name,
1496 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001497{
1498 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1499 const char* mode;
1500 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001501 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001502 int buffering, isatty;
1503 _Py_IDENTIFIER(open);
1504 _Py_IDENTIFIER(isatty);
1505 _Py_IDENTIFIER(TextIOWrapper);
1506 _Py_IDENTIFIER(mode);
1507
Victor Stinner874dbe82015-09-04 17:29:57 +02001508 if (!is_valid_fd(fd))
1509 Py_RETURN_NONE;
1510
Nick Coghland6009512014-11-20 21:39:37 +10001511 /* stdin is always opened in buffered mode, first because it shouldn't
1512 make a difference in common use cases, second because TextIOWrapper
1513 depends on the presence of a read1() method which only exists on
1514 buffered streams.
1515 */
1516 if (Py_UnbufferedStdioFlag && write_mode)
1517 buffering = 0;
1518 else
1519 buffering = -1;
1520 if (write_mode)
1521 mode = "wb";
1522 else
1523 mode = "rb";
1524 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1525 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001526 Py_None, Py_None, /* encoding, errors */
1527 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001528 if (buf == NULL)
1529 goto error;
1530
1531 if (buffering) {
1532 _Py_IDENTIFIER(raw);
1533 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1534 if (raw == NULL)
1535 goto error;
1536 }
1537 else {
1538 raw = buf;
1539 Py_INCREF(raw);
1540 }
1541
Steve Dower39294992016-08-30 21:22:36 -07001542#ifdef MS_WINDOWS
1543 /* Windows console IO is always UTF-8 encoded */
1544 if (PyWindowsConsoleIO_Check(raw))
1545 encoding = "utf-8";
1546#endif
1547
Nick Coghland6009512014-11-20 21:39:37 +10001548 text = PyUnicode_FromString(name);
1549 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1550 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001551 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001552 if (res == NULL)
1553 goto error;
1554 isatty = PyObject_IsTrue(res);
1555 Py_DECREF(res);
1556 if (isatty == -1)
1557 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001558 if (Py_UnbufferedStdioFlag)
1559 write_through = Py_True;
1560 else
1561 write_through = Py_False;
1562 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001563 line_buffering = Py_True;
1564 else
1565 line_buffering = Py_False;
1566
1567 Py_CLEAR(raw);
1568 Py_CLEAR(text);
1569
1570#ifdef MS_WINDOWS
1571 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1572 newlines to "\n".
1573 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1574 newline = NULL;
1575#else
1576 /* sys.stdin: split lines at "\n".
1577 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1578 newline = "\n";
1579#endif
1580
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001581 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001582 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001583 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001584 Py_CLEAR(buf);
1585 if (stream == NULL)
1586 goto error;
1587
1588 if (write_mode)
1589 mode = "w";
1590 else
1591 mode = "r";
1592 text = PyUnicode_FromString(mode);
1593 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1594 goto error;
1595 Py_CLEAR(text);
1596 return stream;
1597
1598error:
1599 Py_XDECREF(buf);
1600 Py_XDECREF(stream);
1601 Py_XDECREF(text);
1602 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001603
Victor Stinner874dbe82015-09-04 17:29:57 +02001604 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1605 /* Issue #24891: the file descriptor was closed after the first
1606 is_valid_fd() check was called. Ignore the OSError and set the
1607 stream to None. */
1608 PyErr_Clear();
1609 Py_RETURN_NONE;
1610 }
1611 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001612}
1613
1614/* Initialize sys.stdin, stdout, stderr and builtins.open */
1615static int
1616initstdio(void)
1617{
1618 PyObject *iomod = NULL, *wrapper;
1619 PyObject *bimod = NULL;
1620 PyObject *m;
1621 PyObject *std = NULL;
1622 int status = 0, fd;
1623 PyObject * encoding_attr;
1624 char *pythonioencoding = NULL, *encoding, *errors;
1625
1626 /* Hack to avoid a nasty recursion issue when Python is invoked
1627 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1628 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1629 goto error;
1630 }
1631 Py_DECREF(m);
1632
1633 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1634 goto error;
1635 }
1636 Py_DECREF(m);
1637
1638 if (!(bimod = PyImport_ImportModule("builtins"))) {
1639 goto error;
1640 }
1641
1642 if (!(iomod = PyImport_ImportModule("io"))) {
1643 goto error;
1644 }
1645 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1646 goto error;
1647 }
1648
1649 /* Set builtins.open */
1650 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1651 Py_DECREF(wrapper);
1652 goto error;
1653 }
1654 Py_DECREF(wrapper);
1655
1656 encoding = _Py_StandardStreamEncoding;
1657 errors = _Py_StandardStreamErrors;
1658 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001659 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1660 if (pythonioencoding) {
1661 char *err;
1662 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1663 if (pythonioencoding == NULL) {
1664 PyErr_NoMemory();
1665 goto error;
1666 }
1667 err = strchr(pythonioencoding, ':');
1668 if (err) {
1669 *err = '\0';
1670 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001671 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001672 errors = err;
1673 }
1674 }
1675 if (*pythonioencoding && !encoding) {
1676 encoding = pythonioencoding;
1677 }
1678 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001679 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001680 /* Choose the default error handler based on the current locale */
1681 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001682 }
Nick Coghland6009512014-11-20 21:39:37 +10001683 }
1684
1685 /* Set sys.stdin */
1686 fd = fileno(stdin);
1687 /* Under some conditions stdin, stdout and stderr may not be connected
1688 * and fileno() may point to an invalid file descriptor. For example
1689 * GUI apps don't have valid standard streams by default.
1690 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001691 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1692 if (std == NULL)
1693 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001694 PySys_SetObject("__stdin__", std);
1695 _PySys_SetObjectId(&PyId_stdin, std);
1696 Py_DECREF(std);
1697
1698 /* Set sys.stdout */
1699 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001700 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1701 if (std == NULL)
1702 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001703 PySys_SetObject("__stdout__", std);
1704 _PySys_SetObjectId(&PyId_stdout, std);
1705 Py_DECREF(std);
1706
1707#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1708 /* Set sys.stderr, replaces the preliminary stderr */
1709 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001710 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1711 if (std == NULL)
1712 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001713
1714 /* Same as hack above, pre-import stderr's codec to avoid recursion
1715 when import.c tries to write to stderr in verbose mode. */
1716 encoding_attr = PyObject_GetAttrString(std, "encoding");
1717 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001718 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001719 if (std_encoding != NULL) {
1720 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1721 Py_XDECREF(codec_info);
1722 }
1723 Py_DECREF(encoding_attr);
1724 }
1725 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1726
1727 if (PySys_SetObject("__stderr__", std) < 0) {
1728 Py_DECREF(std);
1729 goto error;
1730 }
1731 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1732 Py_DECREF(std);
1733 goto error;
1734 }
1735 Py_DECREF(std);
1736#endif
1737
1738 if (0) {
1739 error:
1740 status = -1;
1741 }
1742
1743 /* We won't need them anymore. */
1744 if (_Py_StandardStreamEncoding) {
1745 PyMem_RawFree(_Py_StandardStreamEncoding);
1746 _Py_StandardStreamEncoding = NULL;
1747 }
1748 if (_Py_StandardStreamErrors) {
1749 PyMem_RawFree(_Py_StandardStreamErrors);
1750 _Py_StandardStreamErrors = NULL;
1751 }
1752 PyMem_Free(pythonioencoding);
1753 Py_XDECREF(bimod);
1754 Py_XDECREF(iomod);
1755 return status;
1756}
1757
1758
Victor Stinner10dc4842015-03-24 12:01:30 +01001759static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001760_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001761{
Victor Stinner10dc4842015-03-24 12:01:30 +01001762 fputc('\n', stderr);
1763 fflush(stderr);
1764
1765 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001766 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001767}
Victor Stinner791da1c2016-03-14 16:53:12 +01001768
1769/* Print the current exception (if an exception is set) with its traceback,
1770 or display the current Python stack.
1771
1772 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1773 called on catastrophic cases.
1774
1775 Return 1 if the traceback was displayed, 0 otherwise. */
1776
1777static int
1778_Py_FatalError_PrintExc(int fd)
1779{
1780 PyObject *ferr, *res;
1781 PyObject *exception, *v, *tb;
1782 int has_tb;
1783
1784 if (PyThreadState_GET() == NULL) {
1785 /* The GIL is released: trying to acquire it is likely to deadlock,
1786 just give up. */
1787 return 0;
1788 }
1789
1790 PyErr_Fetch(&exception, &v, &tb);
1791 if (exception == NULL) {
1792 /* No current exception */
1793 return 0;
1794 }
1795
1796 ferr = _PySys_GetObjectId(&PyId_stderr);
1797 if (ferr == NULL || ferr == Py_None) {
1798 /* sys.stderr is not set yet or set to None,
1799 no need to try to display the exception */
1800 return 0;
1801 }
1802
1803 PyErr_NormalizeException(&exception, &v, &tb);
1804 if (tb == NULL) {
1805 tb = Py_None;
1806 Py_INCREF(tb);
1807 }
1808 PyException_SetTraceback(v, tb);
1809 if (exception == NULL) {
1810 /* PyErr_NormalizeException() failed */
1811 return 0;
1812 }
1813
1814 has_tb = (tb != Py_None);
1815 PyErr_Display(exception, v, tb);
1816 Py_XDECREF(exception);
1817 Py_XDECREF(v);
1818 Py_XDECREF(tb);
1819
1820 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001821 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001822 if (res == NULL)
1823 PyErr_Clear();
1824 else
1825 Py_DECREF(res);
1826
1827 return has_tb;
1828}
1829
Nick Coghland6009512014-11-20 21:39:37 +10001830/* Print fatal error message and abort */
1831
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001832#ifdef MS_WINDOWS
1833static void
1834fatal_output_debug(const char *msg)
1835{
1836 /* buffer of 256 bytes allocated on the stack */
1837 WCHAR buffer[256 / sizeof(WCHAR)];
1838 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1839 size_t msglen;
1840
1841 OutputDebugStringW(L"Fatal Python error: ");
1842
1843 msglen = strlen(msg);
1844 while (msglen) {
1845 size_t i;
1846
1847 if (buflen > msglen) {
1848 buflen = msglen;
1849 }
1850
1851 /* Convert the message to wchar_t. This uses a simple one-to-one
1852 conversion, assuming that the this error message actually uses
1853 ASCII only. If this ceases to be true, we will have to convert. */
1854 for (i=0; i < buflen; ++i) {
1855 buffer[i] = msg[i];
1856 }
1857 buffer[i] = L'\0';
1858 OutputDebugStringW(buffer);
1859
1860 msg += buflen;
1861 msglen -= buflen;
1862 }
1863 OutputDebugStringW(L"\n");
1864}
1865#endif
1866
Nick Coghland6009512014-11-20 21:39:37 +10001867void
1868Py_FatalError(const char *msg)
1869{
1870 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001871 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001872
1873 if (reentrant) {
1874 /* Py_FatalError() caused a second fatal error.
1875 Example: flush_std_files() raises a recursion error. */
1876 goto exit;
1877 }
1878 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001879
1880 fprintf(stderr, "Fatal Python error: %s\n", msg);
1881 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001882
Victor Stinnere0deff32015-03-24 13:46:18 +01001883 /* Print the exception (if an exception is set) with its traceback,
1884 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001885 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001886 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001887 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001888
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001889 /* The main purpose of faulthandler is to display the traceback.
1890 This function already did its best to display a traceback.
1891 Disable faulthandler to prevent writing a second traceback
1892 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001893 _PyFaulthandler_Fini();
1894
Victor Stinner791da1c2016-03-14 16:53:12 +01001895 /* Check if the current Python thread hold the GIL */
1896 if (PyThreadState_GET() != NULL) {
1897 /* Flush sys.stdout and sys.stderr */
1898 flush_std_files();
1899 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001900
Nick Coghland6009512014-11-20 21:39:37 +10001901#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001902 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001903#endif /* MS_WINDOWS */
1904
1905exit:
1906#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001907 DebugBreak();
1908#endif
Nick Coghland6009512014-11-20 21:39:37 +10001909 abort();
1910}
1911
1912/* Clean up and exit */
1913
Victor Stinnerd7292b52016-06-17 12:29:00 +02001914# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001915
Nick Coghland6009512014-11-20 21:39:37 +10001916/* For the atexit module. */
1917void _Py_PyAtExit(void (*func)(void))
1918{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001919 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001920}
1921
1922static void
1923call_py_exitfuncs(void)
1924{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001925 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001926 return;
1927
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001928 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001929 PyErr_Clear();
1930}
1931
1932/* Wait until threading._shutdown completes, provided
1933 the threading module was imported in the first place.
1934 The shutdown routine will wait until all non-daemon
1935 "threading" threads have completed. */
1936static void
1937wait_for_thread_shutdown(void)
1938{
Nick Coghland6009512014-11-20 21:39:37 +10001939 _Py_IDENTIFIER(_shutdown);
1940 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06001941 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001942 if (threading == NULL) {
1943 /* threading not imported */
1944 PyErr_Clear();
1945 return;
1946 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001947 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001948 if (result == NULL) {
1949 PyErr_WriteUnraisable(threading);
1950 }
1951 else {
1952 Py_DECREF(result);
1953 }
1954 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001955}
1956
1957#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001958int Py_AtExit(void (*func)(void))
1959{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001960 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001961 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001962 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001963 return 0;
1964}
1965
1966static void
1967call_ll_exitfuncs(void)
1968{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001969 while (_PyRuntime.nexitfuncs > 0)
1970 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001971
1972 fflush(stdout);
1973 fflush(stderr);
1974}
1975
1976void
1977Py_Exit(int sts)
1978{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001979 if (Py_FinalizeEx() < 0) {
1980 sts = 120;
1981 }
Nick Coghland6009512014-11-20 21:39:37 +10001982
1983 exit(sts);
1984}
1985
1986static void
1987initsigs(void)
1988{
1989#ifdef SIGPIPE
1990 PyOS_setsig(SIGPIPE, SIG_IGN);
1991#endif
1992#ifdef SIGXFZ
1993 PyOS_setsig(SIGXFZ, SIG_IGN);
1994#endif
1995#ifdef SIGXFSZ
1996 PyOS_setsig(SIGXFSZ, SIG_IGN);
1997#endif
1998 PyOS_InitInterrupts(); /* May imply initsignal() */
1999 if (PyErr_Occurred()) {
2000 Py_FatalError("Py_Initialize: can't import signal");
2001 }
2002}
2003
2004
2005/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2006 *
2007 * All of the code in this function must only use async-signal-safe functions,
2008 * listed at `man 7 signal` or
2009 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2010 */
2011void
2012_Py_RestoreSignals(void)
2013{
2014#ifdef SIGPIPE
2015 PyOS_setsig(SIGPIPE, SIG_DFL);
2016#endif
2017#ifdef SIGXFZ
2018 PyOS_setsig(SIGXFZ, SIG_DFL);
2019#endif
2020#ifdef SIGXFSZ
2021 PyOS_setsig(SIGXFSZ, SIG_DFL);
2022#endif
2023}
2024
2025
2026/*
2027 * The file descriptor fd is considered ``interactive'' if either
2028 * a) isatty(fd) is TRUE, or
2029 * b) the -i flag was given, and the filename associated with
2030 * the descriptor is NULL or "<stdin>" or "???".
2031 */
2032int
2033Py_FdIsInteractive(FILE *fp, const char *filename)
2034{
2035 if (isatty((int)fileno(fp)))
2036 return 1;
2037 if (!Py_InteractiveFlag)
2038 return 0;
2039 return (filename == NULL) ||
2040 (strcmp(filename, "<stdin>") == 0) ||
2041 (strcmp(filename, "???") == 0);
2042}
2043
2044
Nick Coghland6009512014-11-20 21:39:37 +10002045/* Wrappers around sigaction() or signal(). */
2046
2047PyOS_sighandler_t
2048PyOS_getsig(int sig)
2049{
2050#ifdef HAVE_SIGACTION
2051 struct sigaction context;
2052 if (sigaction(sig, NULL, &context) == -1)
2053 return SIG_ERR;
2054 return context.sa_handler;
2055#else
2056 PyOS_sighandler_t handler;
2057/* Special signal handling for the secure CRT in Visual Studio 2005 */
2058#if defined(_MSC_VER) && _MSC_VER >= 1400
2059 switch (sig) {
2060 /* Only these signals are valid */
2061 case SIGINT:
2062 case SIGILL:
2063 case SIGFPE:
2064 case SIGSEGV:
2065 case SIGTERM:
2066 case SIGBREAK:
2067 case SIGABRT:
2068 break;
2069 /* Don't call signal() with other values or it will assert */
2070 default:
2071 return SIG_ERR;
2072 }
2073#endif /* _MSC_VER && _MSC_VER >= 1400 */
2074 handler = signal(sig, SIG_IGN);
2075 if (handler != SIG_ERR)
2076 signal(sig, handler);
2077 return handler;
2078#endif
2079}
2080
2081/*
2082 * All of the code in this function must only use async-signal-safe functions,
2083 * listed at `man 7 signal` or
2084 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2085 */
2086PyOS_sighandler_t
2087PyOS_setsig(int sig, PyOS_sighandler_t handler)
2088{
2089#ifdef HAVE_SIGACTION
2090 /* Some code in Modules/signalmodule.c depends on sigaction() being
2091 * used here if HAVE_SIGACTION is defined. Fix that if this code
2092 * changes to invalidate that assumption.
2093 */
2094 struct sigaction context, ocontext;
2095 context.sa_handler = handler;
2096 sigemptyset(&context.sa_mask);
2097 context.sa_flags = 0;
2098 if (sigaction(sig, &context, &ocontext) == -1)
2099 return SIG_ERR;
2100 return ocontext.sa_handler;
2101#else
2102 PyOS_sighandler_t oldhandler;
2103 oldhandler = signal(sig, handler);
2104#ifdef HAVE_SIGINTERRUPT
2105 siginterrupt(sig, 1);
2106#endif
2107 return oldhandler;
2108#endif
2109}
2110
2111#ifdef __cplusplus
2112}
2113#endif