blob: 3265d7018106216323463c25b00a52aa69567d20 [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 Snow86b7afd2017-09-04 17:54:09 -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 Snow86b7afd2017-09-04 17:54:09 -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 Snow86b7afd2017-09-04 17:54:09 -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");
Nick Coghland6009512014-11-20 21:39:37 +1000677
Eric Snow86b7afd2017-09-04 17:54:09 -0600678 sysmod = _PySys_BeginInit();
679 if (sysmod == NULL)
680 Py_FatalError("Py_InitializeCore: can't initialize sys");
681 interp->sysdict = PyModule_GetDict(sysmod);
682 if (interp->sysdict == NULL)
683 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
684 Py_INCREF(interp->sysdict);
685 PyDict_SetItemString(interp->sysdict, "modules", modules);
686 _PyImport_FixupBuiltin(sysmod, "sys", modules);
687
Nick Coghland6009512014-11-20 21:39:37 +1000688 /* Init Unicode implementation; relies on the codec registry */
689 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700690 Py_FatalError("Py_InitializeCore: can't initialize unicode");
691
Nick Coghland6009512014-11-20 21:39:37 +1000692 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700693 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000694
695 bimod = _PyBuiltin_Init();
696 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700697 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snow86b7afd2017-09-04 17:54:09 -0600698 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000699 interp->builtins = PyModule_GetDict(bimod);
700 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700701 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000702 Py_INCREF(interp->builtins);
703
704 /* initialize builtin exceptions */
705 _PyExc_Init(bimod);
706
Nick Coghland6009512014-11-20 21:39:37 +1000707 /* Set up a preliminary stderr printer until we have enough
708 infrastructure for the io module in place. */
709 pstderr = PyFile_NewStdPrinter(fileno(stderr));
710 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700711 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000712 _PySys_SetObjectId(&PyId_stderr, pstderr);
713 PySys_SetObject("__stderr__", pstderr);
714 Py_DECREF(pstderr);
715
716 _PyImport_Init();
717
718 _PyImportHooks_Init();
719
720 /* Initialize _warnings. */
721 _PyWarnings_Init();
722
Eric Snow1abcf672017-05-23 21:46:51 -0700723 /* This call sets up builtin and frozen import support */
724 if (!interp->core_config._disable_importlib) {
725 initimport(interp, sysmod);
726 }
727
728 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600729 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700730}
731
Eric Snowc7ec9982017-05-23 23:00:52 -0700732/* Read configuration settings from standard locations
733 *
734 * This function doesn't make any changes to the interpreter state - it
735 * merely populates any missing configuration settings. This allows an
736 * embedding application to completely override a config option by
737 * setting it before calling this function, or else modify the default
738 * setting before passing the fully populated config to Py_EndInitialization.
739 *
740 * More advanced selective initialization tricks are possible by calling
741 * this function multiple times with various preconfigured settings.
742 */
743
744int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
745{
746 /* Signal handlers are installed by default */
747 if (config->install_signal_handlers < 0) {
748 config->install_signal_handlers = 1;
749 }
750
751 return 0;
752}
753
754/* Update interpreter state based on supplied configuration settings
755 *
756 * After calling this function, most of the restrictions on the interpreter
757 * are lifted. The only remaining incomplete settings are those related
758 * to the main module (sys.argv[0], __main__ metadata)
759 *
760 * Calling this when the interpreter is not initializing, is already
761 * initialized or without a valid current thread state is a fatal error.
762 * Other errors should be reported as normal Python exceptions with a
763 * non-zero return code.
764 */
765int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700766{
767 PyInterpreterState *interp;
768 PyThreadState *tstate;
769
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600770 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700771 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
772 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600773 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700774 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
775 }
776
Eric Snow1abcf672017-05-23 21:46:51 -0700777 /* Get current thread state and interpreter pointer */
778 tstate = PyThreadState_GET();
779 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700780 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700781 interp = tstate->interp;
782 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700783 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700784
785 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700786 interp->config = *config;
787
Eric Snow1abcf672017-05-23 21:46:51 -0700788 if (interp->core_config._disable_importlib) {
789 /* Special mode for freeze_importlib: run with no import system
790 *
791 * This means anything which needs support from extension modules
792 * or pure Python code in the standard library won't work.
793 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600794 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700795 return 0;
796 }
797 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000798
Victor Stinner13019fd2015-04-03 13:10:54 +0200799 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700800 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200801
Eric Snow1abcf672017-05-23 21:46:51 -0700802 /* Finish setting up the sys module and import system */
803 /* GetPath may initialize state that _PySys_EndInit locks
804 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700805 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700806 PySys_SetPath(Py_GetPath());
807 if (_PySys_EndInit(interp->sysdict) < 0)
808 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700809 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000810
811 /* initialize the faulthandler module */
812 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700813 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000814
Nick Coghland6009512014-11-20 21:39:37 +1000815 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700816 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000817
Eric Snowc7ec9982017-05-23 23:00:52 -0700818 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000819 initsigs(); /* Signal handling stuff, including initintr() */
820
821 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700822 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000823
824 initmain(interp); /* Module __main__ */
825 if (initstdio() < 0)
826 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700827 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000828
829 /* Initialize warnings. */
830 if (PySys_HasWarnOptions()) {
831 PyObject *warnings_module = PyImport_ImportModule("warnings");
832 if (warnings_module == NULL) {
833 fprintf(stderr, "'import warnings' failed; traceback:\n");
834 PyErr_Print();
835 }
836 Py_XDECREF(warnings_module);
837 }
838
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600839 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700840
Nick Coghland6009512014-11-20 21:39:37 +1000841 if (!Py_NoSiteFlag)
842 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700843
Eric Snowc7ec9982017-05-23 23:00:52 -0700844 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000845}
846
Eric Snowc7ec9982017-05-23 23:00:52 -0700847#undef _INIT_DEBUG_PRINT
848
Nick Coghland6009512014-11-20 21:39:37 +1000849void
Eric Snow1abcf672017-05-23 21:46:51 -0700850_Py_InitializeEx_Private(int install_sigs, int install_importlib)
851{
852 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700853 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700854
855 /* TODO: Moar config options! */
856 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
857 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700858 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700859 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700860 /* TODO: Print any exceptions raised by these operations */
861 if (_Py_ReadMainInterpreterConfig(&config))
862 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
863 if (_Py_InitializeMainInterpreter(&config))
864 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700865}
866
867
868void
Nick Coghland6009512014-11-20 21:39:37 +1000869Py_InitializeEx(int install_sigs)
870{
871 _Py_InitializeEx_Private(install_sigs, 1);
872}
873
874void
875Py_Initialize(void)
876{
877 Py_InitializeEx(1);
878}
879
880
881#ifdef COUNT_ALLOCS
882extern void dump_counts(FILE*);
883#endif
884
885/* Flush stdout and stderr */
886
887static int
888file_is_closed(PyObject *fobj)
889{
890 int r;
891 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
892 if (tmp == NULL) {
893 PyErr_Clear();
894 return 0;
895 }
896 r = PyObject_IsTrue(tmp);
897 Py_DECREF(tmp);
898 if (r < 0)
899 PyErr_Clear();
900 return r > 0;
901}
902
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000903static int
Nick Coghland6009512014-11-20 21:39:37 +1000904flush_std_files(void)
905{
906 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
907 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
908 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000909 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000910
911 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700912 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000913 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000914 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000915 status = -1;
916 }
Nick Coghland6009512014-11-20 21:39:37 +1000917 else
918 Py_DECREF(tmp);
919 }
920
921 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700922 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000923 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000924 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000925 status = -1;
926 }
Nick Coghland6009512014-11-20 21:39:37 +1000927 else
928 Py_DECREF(tmp);
929 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000930
931 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000932}
933
934/* Undo the effect of Py_Initialize().
935
936 Beware: if multiple interpreter and/or thread states exist, these
937 are not wiped out; only the current thread and interpreter state
938 are deleted. But since everything else is deleted, those other
939 interpreter and thread states should no longer be used.
940
941 (XXX We should do better, e.g. wipe out all interpreters and
942 threads.)
943
944 Locking: as above.
945
946*/
947
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000948int
949Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000950{
951 PyInterpreterState *interp;
952 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000953 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000954
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600955 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000956 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000957
958 wait_for_thread_shutdown();
959
960 /* The interpreter is still entirely intact at this point, and the
961 * exit funcs may be relying on that. In particular, if some thread
962 * or exit func is still waiting to do an import, the import machinery
963 * expects Py_IsInitialized() to return true. So don't say the
964 * interpreter is uninitialized until after the exit funcs have run.
965 * Note that Threading.py uses an exit func to do a join on all the
966 * threads created thru it, so this also protects pending imports in
967 * the threads created via Threading.
968 */
969 call_py_exitfuncs();
970
971 /* Get current thread state and interpreter pointer */
972 tstate = PyThreadState_GET();
973 interp = tstate->interp;
974
975 /* Remaining threads (e.g. daemon threads) will automatically exit
976 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600977 _PyRuntime.finalizing = tstate;
978 _PyRuntime.initialized = 0;
979 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000980
Victor Stinnere0deff32015-03-24 13:46:18 +0100981 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000982 if (flush_std_files() < 0) {
983 status = -1;
984 }
Nick Coghland6009512014-11-20 21:39:37 +1000985
986 /* Disable signal handling */
987 PyOS_FiniInterrupts();
988
989 /* Collect garbage. This may call finalizers; it's nice to call these
990 * before all modules are destroyed.
991 * XXX If a __del__ or weakref callback is triggered here, and tries to
992 * XXX import a module, bad things can happen, because Python no
993 * XXX longer believes it's initialized.
994 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
995 * XXX is easy to provoke that way. I've also seen, e.g.,
996 * XXX Exception exceptions.ImportError: 'No module named sha'
997 * XXX in <function callback at 0x008F5718> ignored
998 * XXX but I'm unclear on exactly how that one happens. In any case,
999 * XXX I haven't seen a real-life report of either of these.
1000 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001001 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001002#ifdef COUNT_ALLOCS
1003 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1004 each collection might release some types from the type
1005 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001006 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001007 /* nothing */;
1008#endif
Eric Snow87280182017-09-11 17:59:22 -07001009
1010#ifdef Py_REF_DEBUG
1011 PyObject *showrefcount = _PyDebug_XOptionShowRefCount();
1012#endif
1013
Nick Coghland6009512014-11-20 21:39:37 +10001014 /* Destroy all modules */
1015 PyImport_Cleanup();
1016
Victor Stinnere0deff32015-03-24 13:46:18 +01001017 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001018 if (flush_std_files() < 0) {
1019 status = -1;
1020 }
Nick Coghland6009512014-11-20 21:39:37 +10001021
1022 /* Collect final garbage. This disposes of cycles created by
1023 * class definitions, for example.
1024 * XXX This is disabled because it caused too many problems. If
1025 * XXX a __del__ or weakref callback triggers here, Python code has
1026 * XXX a hard time running, because even the sys module has been
1027 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1028 * XXX One symptom is a sequence of information-free messages
1029 * XXX coming from threads (if a __del__ or callback is invoked,
1030 * XXX other threads can execute too, and any exception they encounter
1031 * XXX triggers a comedy of errors as subsystem after subsystem
1032 * XXX fails to find what it *expects* to find in sys to help report
1033 * XXX the exception and consequent unexpected failures). I've also
1034 * XXX seen segfaults then, after adding print statements to the
1035 * XXX Python code getting called.
1036 */
1037#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001038 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001039#endif
1040
1041 /* Disable tracemalloc after all Python objects have been destroyed,
1042 so it is possible to use tracemalloc in objects destructor. */
1043 _PyTraceMalloc_Fini();
1044
1045 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1046 _PyImport_Fini();
1047
1048 /* Cleanup typeobject.c's internal caches. */
1049 _PyType_Fini();
1050
1051 /* unload faulthandler module */
1052 _PyFaulthandler_Fini();
1053
1054 /* Debugging stuff */
1055#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001056 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001057#endif
1058 /* dump hash stats */
1059 _PyHash_Fini();
1060
Eric Snow87280182017-09-11 17:59:22 -07001061#ifdef Py_REF_DEBUG
1062 if (showrefcount == Py_True)
1063 _PyDebug_PrintTotalRefs();
1064#endif
Nick Coghland6009512014-11-20 21:39:37 +10001065
1066#ifdef Py_TRACE_REFS
1067 /* Display all objects still alive -- this can invoke arbitrary
1068 * __repr__ overrides, so requires a mostly-intact interpreter.
1069 * Alas, a lot of stuff may still be alive now that will be cleaned
1070 * up later.
1071 */
1072 if (Py_GETENV("PYTHONDUMPREFS"))
1073 _Py_PrintReferences(stderr);
1074#endif /* Py_TRACE_REFS */
1075
1076 /* Clear interpreter state and all thread states. */
1077 PyInterpreterState_Clear(interp);
1078
1079 /* Now we decref the exception classes. After this point nothing
1080 can raise an exception. That's okay, because each Fini() method
1081 below has been checked to make sure no exceptions are ever
1082 raised.
1083 */
1084
1085 _PyExc_Fini();
1086
1087 /* Sundry finalizers */
1088 PyMethod_Fini();
1089 PyFrame_Fini();
1090 PyCFunction_Fini();
1091 PyTuple_Fini();
1092 PyList_Fini();
1093 PySet_Fini();
1094 PyBytes_Fini();
1095 PyByteArray_Fini();
1096 PyLong_Fini();
1097 PyFloat_Fini();
1098 PyDict_Fini();
1099 PySlice_Fini();
1100 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001101 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001102 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001103 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001104
1105 /* Cleanup Unicode implementation */
1106 _PyUnicode_Fini();
1107
1108 /* reset file system default encoding */
1109 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1110 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1111 Py_FileSystemDefaultEncoding = NULL;
1112 }
1113
1114 /* XXX Still allocated:
1115 - various static ad-hoc pointers to interned strings
1116 - int and float free list blocks
1117 - whatever various modules and libraries allocate
1118 */
1119
1120 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1121
1122 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001123 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001124
1125 /* Delete current thread. After this, many C API calls become crashy. */
1126 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001127
Nick Coghland6009512014-11-20 21:39:37 +10001128 PyInterpreterState_Delete(interp);
1129
1130#ifdef Py_TRACE_REFS
1131 /* Display addresses (& refcnts) of all objects still alive.
1132 * An address can be used to find the repr of the object, printed
1133 * above by _Py_PrintReferences.
1134 */
1135 if (Py_GETENV("PYTHONDUMPREFS"))
1136 _Py_PrintReferenceAddresses(stderr);
1137#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001138#ifdef WITH_PYMALLOC
1139 if (_PyMem_PymallocEnabled()) {
1140 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1141 if (opt != NULL && *opt != '\0')
1142 _PyObject_DebugMallocStats(stderr);
1143 }
Nick Coghland6009512014-11-20 21:39:37 +10001144#endif
1145
1146 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001147 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001148 return status;
1149}
1150
1151void
1152Py_Finalize(void)
1153{
1154 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001155}
1156
1157/* Create and initialize a new interpreter and thread, and return the
1158 new thread. This requires that Py_Initialize() has been called
1159 first.
1160
1161 Unsuccessful initialization yields a NULL pointer. Note that *no*
1162 exception information is available even in this case -- the
1163 exception information is held in the thread, and there is no
1164 thread.
1165
1166 Locking: as above.
1167
1168*/
1169
1170PyThreadState *
1171Py_NewInterpreter(void)
1172{
1173 PyInterpreterState *interp;
1174 PyThreadState *tstate, *save_tstate;
1175 PyObject *bimod, *sysmod;
1176
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001177 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001178 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1179
Victor Stinner8a1be612016-03-14 22:07:55 +01001180 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1181 interpreters: disable PyGILState_Check(). */
1182 _PyGILState_check_enabled = 0;
1183
Nick Coghland6009512014-11-20 21:39:37 +10001184 interp = PyInterpreterState_New();
1185 if (interp == NULL)
1186 return NULL;
1187
1188 tstate = PyThreadState_New(interp);
1189 if (tstate == NULL) {
1190 PyInterpreterState_Delete(interp);
1191 return NULL;
1192 }
1193
1194 save_tstate = PyThreadState_Swap(tstate);
1195
Eric Snow1abcf672017-05-23 21:46:51 -07001196 /* Copy the current interpreter config into the new interpreter */
1197 if (save_tstate != NULL) {
1198 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001199 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001200 } else {
1201 /* No current thread state, copy from the main interpreter */
1202 PyInterpreterState *main_interp = PyInterpreterState_Main();
1203 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001204 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001205 }
1206
Nick Coghland6009512014-11-20 21:39:37 +10001207 /* XXX The following is lax in error checking */
1208
Eric Snow86b7afd2017-09-04 17:54:09 -06001209 PyObject *modules = PyDict_New();
1210 if (modules == NULL)
1211 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +10001212
Eric Snow86b7afd2017-09-04 17:54:09 -06001213 sysmod = _PyImport_FindBuiltin("sys", modules);
1214 if (sysmod != NULL) {
1215 interp->sysdict = PyModule_GetDict(sysmod);
1216 if (interp->sysdict == NULL)
1217 goto handle_error;
1218 Py_INCREF(interp->sysdict);
1219 PyDict_SetItemString(interp->sysdict, "modules", modules);
1220 PySys_SetPath(Py_GetPath());
1221 _PySys_EndInit(interp->sysdict);
1222 }
1223
1224 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001225 if (bimod != NULL) {
1226 interp->builtins = PyModule_GetDict(bimod);
1227 if (interp->builtins == NULL)
1228 goto handle_error;
1229 Py_INCREF(interp->builtins);
1230 }
1231
1232 /* initialize builtin exceptions */
1233 _PyExc_Init(bimod);
1234
Nick Coghland6009512014-11-20 21:39:37 +10001235 if (bimod != NULL && sysmod != NULL) {
1236 PyObject *pstderr;
1237
Nick Coghland6009512014-11-20 21:39:37 +10001238 /* Set up a preliminary stderr printer until we have enough
1239 infrastructure for the io module in place. */
1240 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1241 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001242 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001243 _PySys_SetObjectId(&PyId_stderr, pstderr);
1244 PySys_SetObject("__stderr__", pstderr);
1245 Py_DECREF(pstderr);
1246
1247 _PyImportHooks_Init();
1248
Eric Snow1abcf672017-05-23 21:46:51 -07001249 initimport(interp, sysmod);
1250 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001251
1252 if (initfsencoding(interp) < 0)
1253 goto handle_error;
1254
1255 if (initstdio() < 0)
1256 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001257 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001258 initmain(interp);
1259 if (!Py_NoSiteFlag)
1260 initsite();
1261 }
1262
1263 if (!PyErr_Occurred())
1264 return tstate;
1265
1266handle_error:
1267 /* Oops, it didn't work. Undo it all. */
1268
1269 PyErr_PrintEx(0);
1270 PyThreadState_Clear(tstate);
1271 PyThreadState_Swap(save_tstate);
1272 PyThreadState_Delete(tstate);
1273 PyInterpreterState_Delete(interp);
1274
1275 return NULL;
1276}
1277
1278/* Delete an interpreter and its last thread. This requires that the
1279 given thread state is current, that the thread has no remaining
1280 frames, and that it is its interpreter's only remaining thread.
1281 It is a fatal error to violate these constraints.
1282
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001283 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001284 everything, regardless.)
1285
1286 Locking: as above.
1287
1288*/
1289
1290void
1291Py_EndInterpreter(PyThreadState *tstate)
1292{
1293 PyInterpreterState *interp = tstate->interp;
1294
1295 if (tstate != PyThreadState_GET())
1296 Py_FatalError("Py_EndInterpreter: thread is not current");
1297 if (tstate->frame != NULL)
1298 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1299
1300 wait_for_thread_shutdown();
1301
1302 if (tstate != interp->tstate_head || tstate->next != NULL)
1303 Py_FatalError("Py_EndInterpreter: not the last thread");
1304
1305 PyImport_Cleanup();
1306 PyInterpreterState_Clear(interp);
1307 PyThreadState_Swap(NULL);
1308 PyInterpreterState_Delete(interp);
1309}
1310
1311#ifdef MS_WINDOWS
1312static wchar_t *progname = L"python";
1313#else
1314static wchar_t *progname = L"python3";
1315#endif
1316
1317void
1318Py_SetProgramName(wchar_t *pn)
1319{
1320 if (pn && *pn)
1321 progname = pn;
1322}
1323
1324wchar_t *
1325Py_GetProgramName(void)
1326{
1327 return progname;
1328}
1329
1330static wchar_t *default_home = NULL;
1331static wchar_t env_home[MAXPATHLEN+1];
1332
1333void
1334Py_SetPythonHome(wchar_t *home)
1335{
1336 default_home = home;
1337}
1338
1339wchar_t *
1340Py_GetPythonHome(void)
1341{
1342 wchar_t *home = default_home;
1343 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1344 char* chome = Py_GETENV("PYTHONHOME");
1345 if (chome) {
1346 size_t size = Py_ARRAY_LENGTH(env_home);
1347 size_t r = mbstowcs(env_home, chome, size);
1348 if (r != (size_t)-1 && r < size)
1349 home = env_home;
1350 }
1351
1352 }
1353 return home;
1354}
1355
1356/* Create __main__ module */
1357
1358static void
1359initmain(PyInterpreterState *interp)
1360{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001361 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001362 m = PyImport_AddModule("__main__");
1363 if (m == NULL)
1364 Py_FatalError("can't create __main__ module");
1365 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001366 ann_dict = PyDict_New();
1367 if ((ann_dict == NULL) ||
1368 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1369 Py_FatalError("Failed to initialize __main__.__annotations__");
1370 }
1371 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001372 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1373 PyObject *bimod = PyImport_ImportModule("builtins");
1374 if (bimod == NULL) {
1375 Py_FatalError("Failed to retrieve builtins module");
1376 }
1377 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1378 Py_FatalError("Failed to initialize __main__.__builtins__");
1379 }
1380 Py_DECREF(bimod);
1381 }
1382 /* Main is a little special - imp.is_builtin("__main__") will return
1383 * False, but BuiltinImporter is still the most appropriate initial
1384 * setting for its __loader__ attribute. A more suitable value will
1385 * be set if __main__ gets further initialized later in the startup
1386 * process.
1387 */
1388 loader = PyDict_GetItemString(d, "__loader__");
1389 if (loader == NULL || loader == Py_None) {
1390 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1391 "BuiltinImporter");
1392 if (loader == NULL) {
1393 Py_FatalError("Failed to retrieve BuiltinImporter");
1394 }
1395 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1396 Py_FatalError("Failed to initialize __main__.__loader__");
1397 }
1398 Py_DECREF(loader);
1399 }
1400}
1401
1402static int
1403initfsencoding(PyInterpreterState *interp)
1404{
1405 PyObject *codec;
1406
Steve Dowercc16be82016-09-08 10:35:16 -07001407#ifdef MS_WINDOWS
1408 if (Py_LegacyWindowsFSEncodingFlag)
1409 {
1410 Py_FileSystemDefaultEncoding = "mbcs";
1411 Py_FileSystemDefaultEncodeErrors = "replace";
1412 }
1413 else
1414 {
1415 Py_FileSystemDefaultEncoding = "utf-8";
1416 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1417 }
1418#else
Nick Coghland6009512014-11-20 21:39:37 +10001419 if (Py_FileSystemDefaultEncoding == NULL)
1420 {
1421 Py_FileSystemDefaultEncoding = get_locale_encoding();
1422 if (Py_FileSystemDefaultEncoding == NULL)
1423 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1424
1425 Py_HasFileSystemDefaultEncoding = 0;
1426 interp->fscodec_initialized = 1;
1427 return 0;
1428 }
Steve Dowercc16be82016-09-08 10:35:16 -07001429#endif
Nick Coghland6009512014-11-20 21:39:37 +10001430
1431 /* the encoding is mbcs, utf-8 or ascii */
1432 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1433 if (!codec) {
1434 /* Such error can only occurs in critical situations: no more
1435 * memory, import a module of the standard library failed,
1436 * etc. */
1437 return -1;
1438 }
1439 Py_DECREF(codec);
1440 interp->fscodec_initialized = 1;
1441 return 0;
1442}
1443
1444/* Import the site module (not into __main__ though) */
1445
1446static void
1447initsite(void)
1448{
1449 PyObject *m;
1450 m = PyImport_ImportModule("site");
1451 if (m == NULL) {
1452 fprintf(stderr, "Failed to import the site module\n");
1453 PyErr_Print();
1454 Py_Finalize();
1455 exit(1);
1456 }
1457 else {
1458 Py_DECREF(m);
1459 }
1460}
1461
Victor Stinner874dbe82015-09-04 17:29:57 +02001462/* Check if a file descriptor is valid or not.
1463 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1464static int
1465is_valid_fd(int fd)
1466{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001467#ifdef __APPLE__
1468 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1469 and the other side of the pipe is closed, dup(1) succeed, whereas
1470 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1471 such error. */
1472 struct stat st;
1473 return (fstat(fd, &st) == 0);
1474#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001475 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001476 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001477 return 0;
1478 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001479 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1480 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1481 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001482 fd2 = dup(fd);
1483 if (fd2 >= 0)
1484 close(fd2);
1485 _Py_END_SUPPRESS_IPH
1486 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001487#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001488}
1489
1490/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001491static PyObject*
1492create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001493 int fd, int write_mode, const char* name,
1494 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001495{
1496 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1497 const char* mode;
1498 const char* newline;
1499 PyObject *line_buffering;
1500 int buffering, isatty;
1501 _Py_IDENTIFIER(open);
1502 _Py_IDENTIFIER(isatty);
1503 _Py_IDENTIFIER(TextIOWrapper);
1504 _Py_IDENTIFIER(mode);
1505
Victor Stinner874dbe82015-09-04 17:29:57 +02001506 if (!is_valid_fd(fd))
1507 Py_RETURN_NONE;
1508
Nick Coghland6009512014-11-20 21:39:37 +10001509 /* stdin is always opened in buffered mode, first because it shouldn't
1510 make a difference in common use cases, second because TextIOWrapper
1511 depends on the presence of a read1() method which only exists on
1512 buffered streams.
1513 */
1514 if (Py_UnbufferedStdioFlag && write_mode)
1515 buffering = 0;
1516 else
1517 buffering = -1;
1518 if (write_mode)
1519 mode = "wb";
1520 else
1521 mode = "rb";
1522 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1523 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001524 Py_None, Py_None, /* encoding, errors */
1525 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001526 if (buf == NULL)
1527 goto error;
1528
1529 if (buffering) {
1530 _Py_IDENTIFIER(raw);
1531 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1532 if (raw == NULL)
1533 goto error;
1534 }
1535 else {
1536 raw = buf;
1537 Py_INCREF(raw);
1538 }
1539
Steve Dower39294992016-08-30 21:22:36 -07001540#ifdef MS_WINDOWS
1541 /* Windows console IO is always UTF-8 encoded */
1542 if (PyWindowsConsoleIO_Check(raw))
1543 encoding = "utf-8";
1544#endif
1545
Nick Coghland6009512014-11-20 21:39:37 +10001546 text = PyUnicode_FromString(name);
1547 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1548 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001549 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001550 if (res == NULL)
1551 goto error;
1552 isatty = PyObject_IsTrue(res);
1553 Py_DECREF(res);
1554 if (isatty == -1)
1555 goto error;
1556 if (isatty || Py_UnbufferedStdioFlag)
1557 line_buffering = Py_True;
1558 else
1559 line_buffering = Py_False;
1560
1561 Py_CLEAR(raw);
1562 Py_CLEAR(text);
1563
1564#ifdef MS_WINDOWS
1565 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1566 newlines to "\n".
1567 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1568 newline = NULL;
1569#else
1570 /* sys.stdin: split lines at "\n".
1571 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1572 newline = "\n";
1573#endif
1574
1575 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1576 buf, encoding, errors,
1577 newline, line_buffering);
1578 Py_CLEAR(buf);
1579 if (stream == NULL)
1580 goto error;
1581
1582 if (write_mode)
1583 mode = "w";
1584 else
1585 mode = "r";
1586 text = PyUnicode_FromString(mode);
1587 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1588 goto error;
1589 Py_CLEAR(text);
1590 return stream;
1591
1592error:
1593 Py_XDECREF(buf);
1594 Py_XDECREF(stream);
1595 Py_XDECREF(text);
1596 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001597
Victor Stinner874dbe82015-09-04 17:29:57 +02001598 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1599 /* Issue #24891: the file descriptor was closed after the first
1600 is_valid_fd() check was called. Ignore the OSError and set the
1601 stream to None. */
1602 PyErr_Clear();
1603 Py_RETURN_NONE;
1604 }
1605 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001606}
1607
1608/* Initialize sys.stdin, stdout, stderr and builtins.open */
1609static int
1610initstdio(void)
1611{
1612 PyObject *iomod = NULL, *wrapper;
1613 PyObject *bimod = NULL;
1614 PyObject *m;
1615 PyObject *std = NULL;
1616 int status = 0, fd;
1617 PyObject * encoding_attr;
1618 char *pythonioencoding = NULL, *encoding, *errors;
1619
1620 /* Hack to avoid a nasty recursion issue when Python is invoked
1621 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1622 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1623 goto error;
1624 }
1625 Py_DECREF(m);
1626
1627 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1628 goto error;
1629 }
1630 Py_DECREF(m);
1631
1632 if (!(bimod = PyImport_ImportModule("builtins"))) {
1633 goto error;
1634 }
1635
1636 if (!(iomod = PyImport_ImportModule("io"))) {
1637 goto error;
1638 }
1639 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1640 goto error;
1641 }
1642
1643 /* Set builtins.open */
1644 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1645 Py_DECREF(wrapper);
1646 goto error;
1647 }
1648 Py_DECREF(wrapper);
1649
1650 encoding = _Py_StandardStreamEncoding;
1651 errors = _Py_StandardStreamErrors;
1652 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001653 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1654 if (pythonioencoding) {
1655 char *err;
1656 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1657 if (pythonioencoding == NULL) {
1658 PyErr_NoMemory();
1659 goto error;
1660 }
1661 err = strchr(pythonioencoding, ':');
1662 if (err) {
1663 *err = '\0';
1664 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001665 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001666 errors = err;
1667 }
1668 }
1669 if (*pythonioencoding && !encoding) {
1670 encoding = pythonioencoding;
1671 }
1672 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001673 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001674 /* Choose the default error handler based on the current locale */
1675 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001676 }
Nick Coghland6009512014-11-20 21:39:37 +10001677 }
1678
1679 /* Set sys.stdin */
1680 fd = fileno(stdin);
1681 /* Under some conditions stdin, stdout and stderr may not be connected
1682 * and fileno() may point to an invalid file descriptor. For example
1683 * GUI apps don't have valid standard streams by default.
1684 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001685 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1686 if (std == NULL)
1687 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001688 PySys_SetObject("__stdin__", std);
1689 _PySys_SetObjectId(&PyId_stdin, std);
1690 Py_DECREF(std);
1691
1692 /* Set sys.stdout */
1693 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001694 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1695 if (std == NULL)
1696 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001697 PySys_SetObject("__stdout__", std);
1698 _PySys_SetObjectId(&PyId_stdout, std);
1699 Py_DECREF(std);
1700
1701#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1702 /* Set sys.stderr, replaces the preliminary stderr */
1703 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001704 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1705 if (std == NULL)
1706 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001707
1708 /* Same as hack above, pre-import stderr's codec to avoid recursion
1709 when import.c tries to write to stderr in verbose mode. */
1710 encoding_attr = PyObject_GetAttrString(std, "encoding");
1711 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001712 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001713 if (std_encoding != NULL) {
1714 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1715 Py_XDECREF(codec_info);
1716 }
1717 Py_DECREF(encoding_attr);
1718 }
1719 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1720
1721 if (PySys_SetObject("__stderr__", std) < 0) {
1722 Py_DECREF(std);
1723 goto error;
1724 }
1725 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1726 Py_DECREF(std);
1727 goto error;
1728 }
1729 Py_DECREF(std);
1730#endif
1731
1732 if (0) {
1733 error:
1734 status = -1;
1735 }
1736
1737 /* We won't need them anymore. */
1738 if (_Py_StandardStreamEncoding) {
1739 PyMem_RawFree(_Py_StandardStreamEncoding);
1740 _Py_StandardStreamEncoding = NULL;
1741 }
1742 if (_Py_StandardStreamErrors) {
1743 PyMem_RawFree(_Py_StandardStreamErrors);
1744 _Py_StandardStreamErrors = NULL;
1745 }
1746 PyMem_Free(pythonioencoding);
1747 Py_XDECREF(bimod);
1748 Py_XDECREF(iomod);
1749 return status;
1750}
1751
1752
Victor Stinner10dc4842015-03-24 12:01:30 +01001753static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001754_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001755{
Victor Stinner10dc4842015-03-24 12:01:30 +01001756 fputc('\n', stderr);
1757 fflush(stderr);
1758
1759 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001760 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001761}
Victor Stinner791da1c2016-03-14 16:53:12 +01001762
1763/* Print the current exception (if an exception is set) with its traceback,
1764 or display the current Python stack.
1765
1766 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1767 called on catastrophic cases.
1768
1769 Return 1 if the traceback was displayed, 0 otherwise. */
1770
1771static int
1772_Py_FatalError_PrintExc(int fd)
1773{
1774 PyObject *ferr, *res;
1775 PyObject *exception, *v, *tb;
1776 int has_tb;
1777
1778 if (PyThreadState_GET() == NULL) {
1779 /* The GIL is released: trying to acquire it is likely to deadlock,
1780 just give up. */
1781 return 0;
1782 }
1783
1784 PyErr_Fetch(&exception, &v, &tb);
1785 if (exception == NULL) {
1786 /* No current exception */
1787 return 0;
1788 }
1789
1790 ferr = _PySys_GetObjectId(&PyId_stderr);
1791 if (ferr == NULL || ferr == Py_None) {
1792 /* sys.stderr is not set yet or set to None,
1793 no need to try to display the exception */
1794 return 0;
1795 }
1796
1797 PyErr_NormalizeException(&exception, &v, &tb);
1798 if (tb == NULL) {
1799 tb = Py_None;
1800 Py_INCREF(tb);
1801 }
1802 PyException_SetTraceback(v, tb);
1803 if (exception == NULL) {
1804 /* PyErr_NormalizeException() failed */
1805 return 0;
1806 }
1807
1808 has_tb = (tb != Py_None);
1809 PyErr_Display(exception, v, tb);
1810 Py_XDECREF(exception);
1811 Py_XDECREF(v);
1812 Py_XDECREF(tb);
1813
1814 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001815 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001816 if (res == NULL)
1817 PyErr_Clear();
1818 else
1819 Py_DECREF(res);
1820
1821 return has_tb;
1822}
1823
Nick Coghland6009512014-11-20 21:39:37 +10001824/* Print fatal error message and abort */
1825
1826void
1827Py_FatalError(const char *msg)
1828{
1829 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001830 static int reentrant = 0;
1831#ifdef MS_WINDOWS
1832 size_t len;
1833 WCHAR* buffer;
1834 size_t i;
1835#endif
1836
1837 if (reentrant) {
1838 /* Py_FatalError() caused a second fatal error.
1839 Example: flush_std_files() raises a recursion error. */
1840 goto exit;
1841 }
1842 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001843
1844 fprintf(stderr, "Fatal Python error: %s\n", msg);
1845 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001846
Victor Stinnere0deff32015-03-24 13:46:18 +01001847 /* Print the exception (if an exception is set) with its traceback,
1848 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001849 if (!_Py_FatalError_PrintExc(fd))
1850 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001851
Victor Stinner2025d782016-03-16 23:19:15 +01001852 /* The main purpose of faulthandler is to display the traceback. We already
1853 * did our best to display it. So faulthandler can now be disabled.
1854 * (Don't trigger it on abort().) */
1855 _PyFaulthandler_Fini();
1856
Victor Stinner791da1c2016-03-14 16:53:12 +01001857 /* Check if the current Python thread hold the GIL */
1858 if (PyThreadState_GET() != NULL) {
1859 /* Flush sys.stdout and sys.stderr */
1860 flush_std_files();
1861 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001862
Nick Coghland6009512014-11-20 21:39:37 +10001863#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001864 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001865
Victor Stinner53345a42015-03-25 01:55:14 +01001866 /* Convert the message to wchar_t. This uses a simple one-to-one
1867 conversion, assuming that the this error message actually uses ASCII
1868 only. If this ceases to be true, we will have to convert. */
1869 buffer = alloca( (len+1) * (sizeof *buffer));
1870 for( i=0; i<=len; ++i)
1871 buffer[i] = msg[i];
1872 OutputDebugStringW(L"Fatal Python error: ");
1873 OutputDebugStringW(buffer);
1874 OutputDebugStringW(L"\n");
1875#endif /* MS_WINDOWS */
1876
1877exit:
1878#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001879 DebugBreak();
1880#endif
Nick Coghland6009512014-11-20 21:39:37 +10001881 abort();
1882}
1883
1884/* Clean up and exit */
1885
Victor Stinnerd7292b52016-06-17 12:29:00 +02001886# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001887
Nick Coghland6009512014-11-20 21:39:37 +10001888/* For the atexit module. */
1889void _Py_PyAtExit(void (*func)(void))
1890{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001891 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001892}
1893
1894static void
1895call_py_exitfuncs(void)
1896{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001897 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001898 return;
1899
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001900 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001901 PyErr_Clear();
1902}
1903
1904/* Wait until threading._shutdown completes, provided
1905 the threading module was imported in the first place.
1906 The shutdown routine will wait until all non-daemon
1907 "threading" threads have completed. */
1908static void
1909wait_for_thread_shutdown(void)
1910{
Nick Coghland6009512014-11-20 21:39:37 +10001911 _Py_IDENTIFIER(_shutdown);
1912 PyObject *result;
Eric Snow86b7afd2017-09-04 17:54:09 -06001913 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001914 if (threading == NULL) {
1915 /* threading not imported */
1916 PyErr_Clear();
1917 return;
1918 }
Eric Snow86b7afd2017-09-04 17:54:09 -06001919 Py_INCREF(threading);
Victor Stinner3466bde2016-09-05 18:16:01 -07001920 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001921 if (result == NULL) {
1922 PyErr_WriteUnraisable(threading);
1923 }
1924 else {
1925 Py_DECREF(result);
1926 }
1927 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001928}
1929
1930#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001931int Py_AtExit(void (*func)(void))
1932{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001933 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001934 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001935 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001936 return 0;
1937}
1938
1939static void
1940call_ll_exitfuncs(void)
1941{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001942 while (_PyRuntime.nexitfuncs > 0)
1943 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001944
1945 fflush(stdout);
1946 fflush(stderr);
1947}
1948
1949void
1950Py_Exit(int sts)
1951{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001952 if (Py_FinalizeEx() < 0) {
1953 sts = 120;
1954 }
Nick Coghland6009512014-11-20 21:39:37 +10001955
1956 exit(sts);
1957}
1958
1959static void
1960initsigs(void)
1961{
1962#ifdef SIGPIPE
1963 PyOS_setsig(SIGPIPE, SIG_IGN);
1964#endif
1965#ifdef SIGXFZ
1966 PyOS_setsig(SIGXFZ, SIG_IGN);
1967#endif
1968#ifdef SIGXFSZ
1969 PyOS_setsig(SIGXFSZ, SIG_IGN);
1970#endif
1971 PyOS_InitInterrupts(); /* May imply initsignal() */
1972 if (PyErr_Occurred()) {
1973 Py_FatalError("Py_Initialize: can't import signal");
1974 }
1975}
1976
1977
1978/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1979 *
1980 * All of the code in this function must only use async-signal-safe functions,
1981 * listed at `man 7 signal` or
1982 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1983 */
1984void
1985_Py_RestoreSignals(void)
1986{
1987#ifdef SIGPIPE
1988 PyOS_setsig(SIGPIPE, SIG_DFL);
1989#endif
1990#ifdef SIGXFZ
1991 PyOS_setsig(SIGXFZ, SIG_DFL);
1992#endif
1993#ifdef SIGXFSZ
1994 PyOS_setsig(SIGXFSZ, SIG_DFL);
1995#endif
1996}
1997
1998
1999/*
2000 * The file descriptor fd is considered ``interactive'' if either
2001 * a) isatty(fd) is TRUE, or
2002 * b) the -i flag was given, and the filename associated with
2003 * the descriptor is NULL or "<stdin>" or "???".
2004 */
2005int
2006Py_FdIsInteractive(FILE *fp, const char *filename)
2007{
2008 if (isatty((int)fileno(fp)))
2009 return 1;
2010 if (!Py_InteractiveFlag)
2011 return 0;
2012 return (filename == NULL) ||
2013 (strcmp(filename, "<stdin>") == 0) ||
2014 (strcmp(filename, "???") == 0);
2015}
2016
2017
Nick Coghland6009512014-11-20 21:39:37 +10002018/* Wrappers around sigaction() or signal(). */
2019
2020PyOS_sighandler_t
2021PyOS_getsig(int sig)
2022{
2023#ifdef HAVE_SIGACTION
2024 struct sigaction context;
2025 if (sigaction(sig, NULL, &context) == -1)
2026 return SIG_ERR;
2027 return context.sa_handler;
2028#else
2029 PyOS_sighandler_t handler;
2030/* Special signal handling for the secure CRT in Visual Studio 2005 */
2031#if defined(_MSC_VER) && _MSC_VER >= 1400
2032 switch (sig) {
2033 /* Only these signals are valid */
2034 case SIGINT:
2035 case SIGILL:
2036 case SIGFPE:
2037 case SIGSEGV:
2038 case SIGTERM:
2039 case SIGBREAK:
2040 case SIGABRT:
2041 break;
2042 /* Don't call signal() with other values or it will assert */
2043 default:
2044 return SIG_ERR;
2045 }
2046#endif /* _MSC_VER && _MSC_VER >= 1400 */
2047 handler = signal(sig, SIG_IGN);
2048 if (handler != SIG_ERR)
2049 signal(sig, handler);
2050 return handler;
2051#endif
2052}
2053
2054/*
2055 * All of the code in this function must only use async-signal-safe functions,
2056 * listed at `man 7 signal` or
2057 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2058 */
2059PyOS_sighandler_t
2060PyOS_setsig(int sig, PyOS_sighandler_t handler)
2061{
2062#ifdef HAVE_SIGACTION
2063 /* Some code in Modules/signalmodule.c depends on sigaction() being
2064 * used here if HAVE_SIGACTION is defined. Fix that if this code
2065 * changes to invalidate that assumption.
2066 */
2067 struct sigaction context, ocontext;
2068 context.sa_handler = handler;
2069 sigemptyset(&context.sa_mask);
2070 context.sa_flags = 0;
2071 if (sigaction(sig, &context, &ocontext) == -1)
2072 return SIG_ERR;
2073 return ocontext.sa_handler;
2074#else
2075 PyOS_sighandler_t oldhandler;
2076 oldhandler = signal(sig, handler);
2077#ifdef HAVE_SIGINTERRUPT
2078 siginterrupt(sig, 1);
2079#endif
2080 return oldhandler;
2081#endif
2082}
2083
2084#ifdef __cplusplus
2085}
2086#endif