blob: caa324e3afa25066c5e7193df97b49c5b2988657 [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
1009 /* Destroy all modules */
1010 PyImport_Cleanup();
1011
Victor Stinnere0deff32015-03-24 13:46:18 +01001012 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001013 if (flush_std_files() < 0) {
1014 status = -1;
1015 }
Nick Coghland6009512014-11-20 21:39:37 +10001016
1017 /* Collect final garbage. This disposes of cycles created by
1018 * class definitions, for example.
1019 * XXX This is disabled because it caused too many problems. If
1020 * XXX a __del__ or weakref callback triggers here, Python code has
1021 * XXX a hard time running, because even the sys module has been
1022 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1023 * XXX One symptom is a sequence of information-free messages
1024 * XXX coming from threads (if a __del__ or callback is invoked,
1025 * XXX other threads can execute too, and any exception they encounter
1026 * XXX triggers a comedy of errors as subsystem after subsystem
1027 * XXX fails to find what it *expects* to find in sys to help report
1028 * XXX the exception and consequent unexpected failures). I've also
1029 * XXX seen segfaults then, after adding print statements to the
1030 * XXX Python code getting called.
1031 */
1032#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001033 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001034#endif
1035
1036 /* Disable tracemalloc after all Python objects have been destroyed,
1037 so it is possible to use tracemalloc in objects destructor. */
1038 _PyTraceMalloc_Fini();
1039
1040 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1041 _PyImport_Fini();
1042
1043 /* Cleanup typeobject.c's internal caches. */
1044 _PyType_Fini();
1045
1046 /* unload faulthandler module */
1047 _PyFaulthandler_Fini();
1048
1049 /* Debugging stuff */
1050#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001051 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001052#endif
1053 /* dump hash stats */
1054 _PyHash_Fini();
1055
1056 _PY_DEBUG_PRINT_TOTAL_REFS();
1057
1058#ifdef Py_TRACE_REFS
1059 /* Display all objects still alive -- this can invoke arbitrary
1060 * __repr__ overrides, so requires a mostly-intact interpreter.
1061 * Alas, a lot of stuff may still be alive now that will be cleaned
1062 * up later.
1063 */
1064 if (Py_GETENV("PYTHONDUMPREFS"))
1065 _Py_PrintReferences(stderr);
1066#endif /* Py_TRACE_REFS */
1067
1068 /* Clear interpreter state and all thread states. */
1069 PyInterpreterState_Clear(interp);
1070
1071 /* Now we decref the exception classes. After this point nothing
1072 can raise an exception. That's okay, because each Fini() method
1073 below has been checked to make sure no exceptions are ever
1074 raised.
1075 */
1076
1077 _PyExc_Fini();
1078
1079 /* Sundry finalizers */
1080 PyMethod_Fini();
1081 PyFrame_Fini();
1082 PyCFunction_Fini();
1083 PyTuple_Fini();
1084 PyList_Fini();
1085 PySet_Fini();
1086 PyBytes_Fini();
1087 PyByteArray_Fini();
1088 PyLong_Fini();
1089 PyFloat_Fini();
1090 PyDict_Fini();
1091 PySlice_Fini();
1092 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001093 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001094 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001095 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001096
1097 /* Cleanup Unicode implementation */
1098 _PyUnicode_Fini();
1099
1100 /* reset file system default encoding */
1101 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1102 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1103 Py_FileSystemDefaultEncoding = NULL;
1104 }
1105
1106 /* XXX Still allocated:
1107 - various static ad-hoc pointers to interned strings
1108 - int and float free list blocks
1109 - whatever various modules and libraries allocate
1110 */
1111
1112 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1113
1114 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001115 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001116
1117 /* Delete current thread. After this, many C API calls become crashy. */
1118 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001119
Nick Coghland6009512014-11-20 21:39:37 +10001120 PyInterpreterState_Delete(interp);
1121
1122#ifdef Py_TRACE_REFS
1123 /* Display addresses (& refcnts) of all objects still alive.
1124 * An address can be used to find the repr of the object, printed
1125 * above by _Py_PrintReferences.
1126 */
1127 if (Py_GETENV("PYTHONDUMPREFS"))
1128 _Py_PrintReferenceAddresses(stderr);
1129#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001130#ifdef WITH_PYMALLOC
1131 if (_PyMem_PymallocEnabled()) {
1132 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1133 if (opt != NULL && *opt != '\0')
1134 _PyObject_DebugMallocStats(stderr);
1135 }
Nick Coghland6009512014-11-20 21:39:37 +10001136#endif
1137
1138 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001139 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001140 return status;
1141}
1142
1143void
1144Py_Finalize(void)
1145{
1146 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001147}
1148
1149/* Create and initialize a new interpreter and thread, and return the
1150 new thread. This requires that Py_Initialize() has been called
1151 first.
1152
1153 Unsuccessful initialization yields a NULL pointer. Note that *no*
1154 exception information is available even in this case -- the
1155 exception information is held in the thread, and there is no
1156 thread.
1157
1158 Locking: as above.
1159
1160*/
1161
1162PyThreadState *
1163Py_NewInterpreter(void)
1164{
1165 PyInterpreterState *interp;
1166 PyThreadState *tstate, *save_tstate;
1167 PyObject *bimod, *sysmod;
1168
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001169 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001170 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1171
Victor Stinner8a1be612016-03-14 22:07:55 +01001172 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1173 interpreters: disable PyGILState_Check(). */
1174 _PyGILState_check_enabled = 0;
1175
Nick Coghland6009512014-11-20 21:39:37 +10001176 interp = PyInterpreterState_New();
1177 if (interp == NULL)
1178 return NULL;
1179
1180 tstate = PyThreadState_New(interp);
1181 if (tstate == NULL) {
1182 PyInterpreterState_Delete(interp);
1183 return NULL;
1184 }
1185
1186 save_tstate = PyThreadState_Swap(tstate);
1187
Eric Snow1abcf672017-05-23 21:46:51 -07001188 /* Copy the current interpreter config into the new interpreter */
1189 if (save_tstate != NULL) {
1190 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001191 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001192 } else {
1193 /* No current thread state, copy from the main interpreter */
1194 PyInterpreterState *main_interp = PyInterpreterState_Main();
1195 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001196 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001197 }
1198
Nick Coghland6009512014-11-20 21:39:37 +10001199 /* XXX The following is lax in error checking */
1200
Eric Snow86b7afd2017-09-04 17:54:09 -06001201 PyObject *modules = PyDict_New();
1202 if (modules == NULL)
1203 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +10001204
Eric Snow86b7afd2017-09-04 17:54:09 -06001205 sysmod = _PyImport_FindBuiltin("sys", modules);
1206 if (sysmod != NULL) {
1207 interp->sysdict = PyModule_GetDict(sysmod);
1208 if (interp->sysdict == NULL)
1209 goto handle_error;
1210 Py_INCREF(interp->sysdict);
1211 PyDict_SetItemString(interp->sysdict, "modules", modules);
1212 PySys_SetPath(Py_GetPath());
1213 _PySys_EndInit(interp->sysdict);
1214 }
1215
1216 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001217 if (bimod != NULL) {
1218 interp->builtins = PyModule_GetDict(bimod);
1219 if (interp->builtins == NULL)
1220 goto handle_error;
1221 Py_INCREF(interp->builtins);
1222 }
1223
1224 /* initialize builtin exceptions */
1225 _PyExc_Init(bimod);
1226
Nick Coghland6009512014-11-20 21:39:37 +10001227 if (bimod != NULL && sysmod != NULL) {
1228 PyObject *pstderr;
1229
Nick Coghland6009512014-11-20 21:39:37 +10001230 /* Set up a preliminary stderr printer until we have enough
1231 infrastructure for the io module in place. */
1232 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1233 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001234 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001235 _PySys_SetObjectId(&PyId_stderr, pstderr);
1236 PySys_SetObject("__stderr__", pstderr);
1237 Py_DECREF(pstderr);
1238
1239 _PyImportHooks_Init();
1240
Eric Snow1abcf672017-05-23 21:46:51 -07001241 initimport(interp, sysmod);
1242 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001243
1244 if (initfsencoding(interp) < 0)
1245 goto handle_error;
1246
1247 if (initstdio() < 0)
1248 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001249 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001250 initmain(interp);
1251 if (!Py_NoSiteFlag)
1252 initsite();
1253 }
1254
1255 if (!PyErr_Occurred())
1256 return tstate;
1257
1258handle_error:
1259 /* Oops, it didn't work. Undo it all. */
1260
1261 PyErr_PrintEx(0);
1262 PyThreadState_Clear(tstate);
1263 PyThreadState_Swap(save_tstate);
1264 PyThreadState_Delete(tstate);
1265 PyInterpreterState_Delete(interp);
1266
1267 return NULL;
1268}
1269
1270/* Delete an interpreter and its last thread. This requires that the
1271 given thread state is current, that the thread has no remaining
1272 frames, and that it is its interpreter's only remaining thread.
1273 It is a fatal error to violate these constraints.
1274
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001275 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001276 everything, regardless.)
1277
1278 Locking: as above.
1279
1280*/
1281
1282void
1283Py_EndInterpreter(PyThreadState *tstate)
1284{
1285 PyInterpreterState *interp = tstate->interp;
1286
1287 if (tstate != PyThreadState_GET())
1288 Py_FatalError("Py_EndInterpreter: thread is not current");
1289 if (tstate->frame != NULL)
1290 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1291
1292 wait_for_thread_shutdown();
1293
1294 if (tstate != interp->tstate_head || tstate->next != NULL)
1295 Py_FatalError("Py_EndInterpreter: not the last thread");
1296
1297 PyImport_Cleanup();
1298 PyInterpreterState_Clear(interp);
1299 PyThreadState_Swap(NULL);
1300 PyInterpreterState_Delete(interp);
1301}
1302
1303#ifdef MS_WINDOWS
1304static wchar_t *progname = L"python";
1305#else
1306static wchar_t *progname = L"python3";
1307#endif
1308
1309void
1310Py_SetProgramName(wchar_t *pn)
1311{
1312 if (pn && *pn)
1313 progname = pn;
1314}
1315
1316wchar_t *
1317Py_GetProgramName(void)
1318{
1319 return progname;
1320}
1321
1322static wchar_t *default_home = NULL;
1323static wchar_t env_home[MAXPATHLEN+1];
1324
1325void
1326Py_SetPythonHome(wchar_t *home)
1327{
1328 default_home = home;
1329}
1330
1331wchar_t *
1332Py_GetPythonHome(void)
1333{
1334 wchar_t *home = default_home;
1335 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1336 char* chome = Py_GETENV("PYTHONHOME");
1337 if (chome) {
1338 size_t size = Py_ARRAY_LENGTH(env_home);
1339 size_t r = mbstowcs(env_home, chome, size);
1340 if (r != (size_t)-1 && r < size)
1341 home = env_home;
1342 }
1343
1344 }
1345 return home;
1346}
1347
1348/* Create __main__ module */
1349
1350static void
1351initmain(PyInterpreterState *interp)
1352{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001353 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001354 m = PyImport_AddModule("__main__");
1355 if (m == NULL)
1356 Py_FatalError("can't create __main__ module");
1357 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001358 ann_dict = PyDict_New();
1359 if ((ann_dict == NULL) ||
1360 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1361 Py_FatalError("Failed to initialize __main__.__annotations__");
1362 }
1363 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001364 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1365 PyObject *bimod = PyImport_ImportModule("builtins");
1366 if (bimod == NULL) {
1367 Py_FatalError("Failed to retrieve builtins module");
1368 }
1369 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1370 Py_FatalError("Failed to initialize __main__.__builtins__");
1371 }
1372 Py_DECREF(bimod);
1373 }
1374 /* Main is a little special - imp.is_builtin("__main__") will return
1375 * False, but BuiltinImporter is still the most appropriate initial
1376 * setting for its __loader__ attribute. A more suitable value will
1377 * be set if __main__ gets further initialized later in the startup
1378 * process.
1379 */
1380 loader = PyDict_GetItemString(d, "__loader__");
1381 if (loader == NULL || loader == Py_None) {
1382 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1383 "BuiltinImporter");
1384 if (loader == NULL) {
1385 Py_FatalError("Failed to retrieve BuiltinImporter");
1386 }
1387 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1388 Py_FatalError("Failed to initialize __main__.__loader__");
1389 }
1390 Py_DECREF(loader);
1391 }
1392}
1393
1394static int
1395initfsencoding(PyInterpreterState *interp)
1396{
1397 PyObject *codec;
1398
Steve Dowercc16be82016-09-08 10:35:16 -07001399#ifdef MS_WINDOWS
1400 if (Py_LegacyWindowsFSEncodingFlag)
1401 {
1402 Py_FileSystemDefaultEncoding = "mbcs";
1403 Py_FileSystemDefaultEncodeErrors = "replace";
1404 }
1405 else
1406 {
1407 Py_FileSystemDefaultEncoding = "utf-8";
1408 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1409 }
1410#else
Nick Coghland6009512014-11-20 21:39:37 +10001411 if (Py_FileSystemDefaultEncoding == NULL)
1412 {
1413 Py_FileSystemDefaultEncoding = get_locale_encoding();
1414 if (Py_FileSystemDefaultEncoding == NULL)
1415 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1416
1417 Py_HasFileSystemDefaultEncoding = 0;
1418 interp->fscodec_initialized = 1;
1419 return 0;
1420 }
Steve Dowercc16be82016-09-08 10:35:16 -07001421#endif
Nick Coghland6009512014-11-20 21:39:37 +10001422
1423 /* the encoding is mbcs, utf-8 or ascii */
1424 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1425 if (!codec) {
1426 /* Such error can only occurs in critical situations: no more
1427 * memory, import a module of the standard library failed,
1428 * etc. */
1429 return -1;
1430 }
1431 Py_DECREF(codec);
1432 interp->fscodec_initialized = 1;
1433 return 0;
1434}
1435
1436/* Import the site module (not into __main__ though) */
1437
1438static void
1439initsite(void)
1440{
1441 PyObject *m;
1442 m = PyImport_ImportModule("site");
1443 if (m == NULL) {
1444 fprintf(stderr, "Failed to import the site module\n");
1445 PyErr_Print();
1446 Py_Finalize();
1447 exit(1);
1448 }
1449 else {
1450 Py_DECREF(m);
1451 }
1452}
1453
Victor Stinner874dbe82015-09-04 17:29:57 +02001454/* Check if a file descriptor is valid or not.
1455 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1456static int
1457is_valid_fd(int fd)
1458{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001459#ifdef __APPLE__
1460 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1461 and the other side of the pipe is closed, dup(1) succeed, whereas
1462 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1463 such error. */
1464 struct stat st;
1465 return (fstat(fd, &st) == 0);
1466#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001467 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001468 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001469 return 0;
1470 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001471 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1472 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1473 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001474 fd2 = dup(fd);
1475 if (fd2 >= 0)
1476 close(fd2);
1477 _Py_END_SUPPRESS_IPH
1478 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001479#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001480}
1481
1482/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001483static PyObject*
1484create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001485 int fd, int write_mode, const char* name,
1486 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001487{
1488 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1489 const char* mode;
1490 const char* newline;
1491 PyObject *line_buffering;
1492 int buffering, isatty;
1493 _Py_IDENTIFIER(open);
1494 _Py_IDENTIFIER(isatty);
1495 _Py_IDENTIFIER(TextIOWrapper);
1496 _Py_IDENTIFIER(mode);
1497
Victor Stinner874dbe82015-09-04 17:29:57 +02001498 if (!is_valid_fd(fd))
1499 Py_RETURN_NONE;
1500
Nick Coghland6009512014-11-20 21:39:37 +10001501 /* stdin is always opened in buffered mode, first because it shouldn't
1502 make a difference in common use cases, second because TextIOWrapper
1503 depends on the presence of a read1() method which only exists on
1504 buffered streams.
1505 */
1506 if (Py_UnbufferedStdioFlag && write_mode)
1507 buffering = 0;
1508 else
1509 buffering = -1;
1510 if (write_mode)
1511 mode = "wb";
1512 else
1513 mode = "rb";
1514 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1515 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001516 Py_None, Py_None, /* encoding, errors */
1517 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001518 if (buf == NULL)
1519 goto error;
1520
1521 if (buffering) {
1522 _Py_IDENTIFIER(raw);
1523 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1524 if (raw == NULL)
1525 goto error;
1526 }
1527 else {
1528 raw = buf;
1529 Py_INCREF(raw);
1530 }
1531
Steve Dower39294992016-08-30 21:22:36 -07001532#ifdef MS_WINDOWS
1533 /* Windows console IO is always UTF-8 encoded */
1534 if (PyWindowsConsoleIO_Check(raw))
1535 encoding = "utf-8";
1536#endif
1537
Nick Coghland6009512014-11-20 21:39:37 +10001538 text = PyUnicode_FromString(name);
1539 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1540 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001541 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001542 if (res == NULL)
1543 goto error;
1544 isatty = PyObject_IsTrue(res);
1545 Py_DECREF(res);
1546 if (isatty == -1)
1547 goto error;
1548 if (isatty || Py_UnbufferedStdioFlag)
1549 line_buffering = Py_True;
1550 else
1551 line_buffering = Py_False;
1552
1553 Py_CLEAR(raw);
1554 Py_CLEAR(text);
1555
1556#ifdef MS_WINDOWS
1557 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1558 newlines to "\n".
1559 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1560 newline = NULL;
1561#else
1562 /* sys.stdin: split lines at "\n".
1563 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1564 newline = "\n";
1565#endif
1566
1567 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1568 buf, encoding, errors,
1569 newline, line_buffering);
1570 Py_CLEAR(buf);
1571 if (stream == NULL)
1572 goto error;
1573
1574 if (write_mode)
1575 mode = "w";
1576 else
1577 mode = "r";
1578 text = PyUnicode_FromString(mode);
1579 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1580 goto error;
1581 Py_CLEAR(text);
1582 return stream;
1583
1584error:
1585 Py_XDECREF(buf);
1586 Py_XDECREF(stream);
1587 Py_XDECREF(text);
1588 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001589
Victor Stinner874dbe82015-09-04 17:29:57 +02001590 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1591 /* Issue #24891: the file descriptor was closed after the first
1592 is_valid_fd() check was called. Ignore the OSError and set the
1593 stream to None. */
1594 PyErr_Clear();
1595 Py_RETURN_NONE;
1596 }
1597 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001598}
1599
1600/* Initialize sys.stdin, stdout, stderr and builtins.open */
1601static int
1602initstdio(void)
1603{
1604 PyObject *iomod = NULL, *wrapper;
1605 PyObject *bimod = NULL;
1606 PyObject *m;
1607 PyObject *std = NULL;
1608 int status = 0, fd;
1609 PyObject * encoding_attr;
1610 char *pythonioencoding = NULL, *encoding, *errors;
1611
1612 /* Hack to avoid a nasty recursion issue when Python is invoked
1613 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1614 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1615 goto error;
1616 }
1617 Py_DECREF(m);
1618
1619 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1620 goto error;
1621 }
1622 Py_DECREF(m);
1623
1624 if (!(bimod = PyImport_ImportModule("builtins"))) {
1625 goto error;
1626 }
1627
1628 if (!(iomod = PyImport_ImportModule("io"))) {
1629 goto error;
1630 }
1631 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1632 goto error;
1633 }
1634
1635 /* Set builtins.open */
1636 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1637 Py_DECREF(wrapper);
1638 goto error;
1639 }
1640 Py_DECREF(wrapper);
1641
1642 encoding = _Py_StandardStreamEncoding;
1643 errors = _Py_StandardStreamErrors;
1644 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001645 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1646 if (pythonioencoding) {
1647 char *err;
1648 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1649 if (pythonioencoding == NULL) {
1650 PyErr_NoMemory();
1651 goto error;
1652 }
1653 err = strchr(pythonioencoding, ':');
1654 if (err) {
1655 *err = '\0';
1656 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001657 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001658 errors = err;
1659 }
1660 }
1661 if (*pythonioencoding && !encoding) {
1662 encoding = pythonioencoding;
1663 }
1664 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001665 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001666 /* Choose the default error handler based on the current locale */
1667 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001668 }
Nick Coghland6009512014-11-20 21:39:37 +10001669 }
1670
1671 /* Set sys.stdin */
1672 fd = fileno(stdin);
1673 /* Under some conditions stdin, stdout and stderr may not be connected
1674 * and fileno() may point to an invalid file descriptor. For example
1675 * GUI apps don't have valid standard streams by default.
1676 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001677 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1678 if (std == NULL)
1679 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001680 PySys_SetObject("__stdin__", std);
1681 _PySys_SetObjectId(&PyId_stdin, std);
1682 Py_DECREF(std);
1683
1684 /* Set sys.stdout */
1685 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001686 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1687 if (std == NULL)
1688 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001689 PySys_SetObject("__stdout__", std);
1690 _PySys_SetObjectId(&PyId_stdout, std);
1691 Py_DECREF(std);
1692
1693#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1694 /* Set sys.stderr, replaces the preliminary stderr */
1695 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001696 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1697 if (std == NULL)
1698 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001699
1700 /* Same as hack above, pre-import stderr's codec to avoid recursion
1701 when import.c tries to write to stderr in verbose mode. */
1702 encoding_attr = PyObject_GetAttrString(std, "encoding");
1703 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001704 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001705 if (std_encoding != NULL) {
1706 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1707 Py_XDECREF(codec_info);
1708 }
1709 Py_DECREF(encoding_attr);
1710 }
1711 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1712
1713 if (PySys_SetObject("__stderr__", std) < 0) {
1714 Py_DECREF(std);
1715 goto error;
1716 }
1717 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1718 Py_DECREF(std);
1719 goto error;
1720 }
1721 Py_DECREF(std);
1722#endif
1723
1724 if (0) {
1725 error:
1726 status = -1;
1727 }
1728
1729 /* We won't need them anymore. */
1730 if (_Py_StandardStreamEncoding) {
1731 PyMem_RawFree(_Py_StandardStreamEncoding);
1732 _Py_StandardStreamEncoding = NULL;
1733 }
1734 if (_Py_StandardStreamErrors) {
1735 PyMem_RawFree(_Py_StandardStreamErrors);
1736 _Py_StandardStreamErrors = NULL;
1737 }
1738 PyMem_Free(pythonioencoding);
1739 Py_XDECREF(bimod);
1740 Py_XDECREF(iomod);
1741 return status;
1742}
1743
1744
Victor Stinner10dc4842015-03-24 12:01:30 +01001745static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001746_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001747{
Victor Stinner10dc4842015-03-24 12:01:30 +01001748 fputc('\n', stderr);
1749 fflush(stderr);
1750
1751 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001752 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001753}
Victor Stinner791da1c2016-03-14 16:53:12 +01001754
1755/* Print the current exception (if an exception is set) with its traceback,
1756 or display the current Python stack.
1757
1758 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1759 called on catastrophic cases.
1760
1761 Return 1 if the traceback was displayed, 0 otherwise. */
1762
1763static int
1764_Py_FatalError_PrintExc(int fd)
1765{
1766 PyObject *ferr, *res;
1767 PyObject *exception, *v, *tb;
1768 int has_tb;
1769
1770 if (PyThreadState_GET() == NULL) {
1771 /* The GIL is released: trying to acquire it is likely to deadlock,
1772 just give up. */
1773 return 0;
1774 }
1775
1776 PyErr_Fetch(&exception, &v, &tb);
1777 if (exception == NULL) {
1778 /* No current exception */
1779 return 0;
1780 }
1781
1782 ferr = _PySys_GetObjectId(&PyId_stderr);
1783 if (ferr == NULL || ferr == Py_None) {
1784 /* sys.stderr is not set yet or set to None,
1785 no need to try to display the exception */
1786 return 0;
1787 }
1788
1789 PyErr_NormalizeException(&exception, &v, &tb);
1790 if (tb == NULL) {
1791 tb = Py_None;
1792 Py_INCREF(tb);
1793 }
1794 PyException_SetTraceback(v, tb);
1795 if (exception == NULL) {
1796 /* PyErr_NormalizeException() failed */
1797 return 0;
1798 }
1799
1800 has_tb = (tb != Py_None);
1801 PyErr_Display(exception, v, tb);
1802 Py_XDECREF(exception);
1803 Py_XDECREF(v);
1804 Py_XDECREF(tb);
1805
1806 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001807 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001808 if (res == NULL)
1809 PyErr_Clear();
1810 else
1811 Py_DECREF(res);
1812
1813 return has_tb;
1814}
1815
Nick Coghland6009512014-11-20 21:39:37 +10001816/* Print fatal error message and abort */
1817
1818void
1819Py_FatalError(const char *msg)
1820{
1821 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001822 static int reentrant = 0;
1823#ifdef MS_WINDOWS
1824 size_t len;
1825 WCHAR* buffer;
1826 size_t i;
1827#endif
1828
1829 if (reentrant) {
1830 /* Py_FatalError() caused a second fatal error.
1831 Example: flush_std_files() raises a recursion error. */
1832 goto exit;
1833 }
1834 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001835
1836 fprintf(stderr, "Fatal Python error: %s\n", msg);
1837 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001838
Victor Stinnere0deff32015-03-24 13:46:18 +01001839 /* Print the exception (if an exception is set) with its traceback,
1840 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001841 if (!_Py_FatalError_PrintExc(fd))
1842 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001843
Victor Stinner2025d782016-03-16 23:19:15 +01001844 /* The main purpose of faulthandler is to display the traceback. We already
1845 * did our best to display it. So faulthandler can now be disabled.
1846 * (Don't trigger it on abort().) */
1847 _PyFaulthandler_Fini();
1848
Victor Stinner791da1c2016-03-14 16:53:12 +01001849 /* Check if the current Python thread hold the GIL */
1850 if (PyThreadState_GET() != NULL) {
1851 /* Flush sys.stdout and sys.stderr */
1852 flush_std_files();
1853 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001854
Nick Coghland6009512014-11-20 21:39:37 +10001855#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001856 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001857
Victor Stinner53345a42015-03-25 01:55:14 +01001858 /* Convert the message to wchar_t. This uses a simple one-to-one
1859 conversion, assuming that the this error message actually uses ASCII
1860 only. If this ceases to be true, we will have to convert. */
1861 buffer = alloca( (len+1) * (sizeof *buffer));
1862 for( i=0; i<=len; ++i)
1863 buffer[i] = msg[i];
1864 OutputDebugStringW(L"Fatal Python error: ");
1865 OutputDebugStringW(buffer);
1866 OutputDebugStringW(L"\n");
1867#endif /* MS_WINDOWS */
1868
1869exit:
1870#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001871 DebugBreak();
1872#endif
Nick Coghland6009512014-11-20 21:39:37 +10001873 abort();
1874}
1875
1876/* Clean up and exit */
1877
Victor Stinnerd7292b52016-06-17 12:29:00 +02001878# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001879
Nick Coghland6009512014-11-20 21:39:37 +10001880/* For the atexit module. */
1881void _Py_PyAtExit(void (*func)(void))
1882{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001883 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001884}
1885
1886static void
1887call_py_exitfuncs(void)
1888{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001889 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001890 return;
1891
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001892 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001893 PyErr_Clear();
1894}
1895
1896/* Wait until threading._shutdown completes, provided
1897 the threading module was imported in the first place.
1898 The shutdown routine will wait until all non-daemon
1899 "threading" threads have completed. */
1900static void
1901wait_for_thread_shutdown(void)
1902{
Nick Coghland6009512014-11-20 21:39:37 +10001903 _Py_IDENTIFIER(_shutdown);
1904 PyObject *result;
Eric Snow86b7afd2017-09-04 17:54:09 -06001905 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001906 if (threading == NULL) {
1907 /* threading not imported */
1908 PyErr_Clear();
1909 return;
1910 }
Eric Snow86b7afd2017-09-04 17:54:09 -06001911 Py_INCREF(threading);
Victor Stinner3466bde2016-09-05 18:16:01 -07001912 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001913 if (result == NULL) {
1914 PyErr_WriteUnraisable(threading);
1915 }
1916 else {
1917 Py_DECREF(result);
1918 }
1919 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001920}
1921
1922#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001923int Py_AtExit(void (*func)(void))
1924{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001925 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001926 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001927 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001928 return 0;
1929}
1930
1931static void
1932call_ll_exitfuncs(void)
1933{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001934 while (_PyRuntime.nexitfuncs > 0)
1935 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001936
1937 fflush(stdout);
1938 fflush(stderr);
1939}
1940
1941void
1942Py_Exit(int sts)
1943{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001944 if (Py_FinalizeEx() < 0) {
1945 sts = 120;
1946 }
Nick Coghland6009512014-11-20 21:39:37 +10001947
1948 exit(sts);
1949}
1950
1951static void
1952initsigs(void)
1953{
1954#ifdef SIGPIPE
1955 PyOS_setsig(SIGPIPE, SIG_IGN);
1956#endif
1957#ifdef SIGXFZ
1958 PyOS_setsig(SIGXFZ, SIG_IGN);
1959#endif
1960#ifdef SIGXFSZ
1961 PyOS_setsig(SIGXFSZ, SIG_IGN);
1962#endif
1963 PyOS_InitInterrupts(); /* May imply initsignal() */
1964 if (PyErr_Occurred()) {
1965 Py_FatalError("Py_Initialize: can't import signal");
1966 }
1967}
1968
1969
1970/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1971 *
1972 * All of the code in this function must only use async-signal-safe functions,
1973 * listed at `man 7 signal` or
1974 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1975 */
1976void
1977_Py_RestoreSignals(void)
1978{
1979#ifdef SIGPIPE
1980 PyOS_setsig(SIGPIPE, SIG_DFL);
1981#endif
1982#ifdef SIGXFZ
1983 PyOS_setsig(SIGXFZ, SIG_DFL);
1984#endif
1985#ifdef SIGXFSZ
1986 PyOS_setsig(SIGXFSZ, SIG_DFL);
1987#endif
1988}
1989
1990
1991/*
1992 * The file descriptor fd is considered ``interactive'' if either
1993 * a) isatty(fd) is TRUE, or
1994 * b) the -i flag was given, and the filename associated with
1995 * the descriptor is NULL or "<stdin>" or "???".
1996 */
1997int
1998Py_FdIsInteractive(FILE *fp, const char *filename)
1999{
2000 if (isatty((int)fileno(fp)))
2001 return 1;
2002 if (!Py_InteractiveFlag)
2003 return 0;
2004 return (filename == NULL) ||
2005 (strcmp(filename, "<stdin>") == 0) ||
2006 (strcmp(filename, "???") == 0);
2007}
2008
2009
Nick Coghland6009512014-11-20 21:39:37 +10002010/* Wrappers around sigaction() or signal(). */
2011
2012PyOS_sighandler_t
2013PyOS_getsig(int sig)
2014{
2015#ifdef HAVE_SIGACTION
2016 struct sigaction context;
2017 if (sigaction(sig, NULL, &context) == -1)
2018 return SIG_ERR;
2019 return context.sa_handler;
2020#else
2021 PyOS_sighandler_t handler;
2022/* Special signal handling for the secure CRT in Visual Studio 2005 */
2023#if defined(_MSC_VER) && _MSC_VER >= 1400
2024 switch (sig) {
2025 /* Only these signals are valid */
2026 case SIGINT:
2027 case SIGILL:
2028 case SIGFPE:
2029 case SIGSEGV:
2030 case SIGTERM:
2031 case SIGBREAK:
2032 case SIGABRT:
2033 break;
2034 /* Don't call signal() with other values or it will assert */
2035 default:
2036 return SIG_ERR;
2037 }
2038#endif /* _MSC_VER && _MSC_VER >= 1400 */
2039 handler = signal(sig, SIG_IGN);
2040 if (handler != SIG_ERR)
2041 signal(sig, handler);
2042 return handler;
2043#endif
2044}
2045
2046/*
2047 * All of the code in this function must only use async-signal-safe functions,
2048 * listed at `man 7 signal` or
2049 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2050 */
2051PyOS_sighandler_t
2052PyOS_setsig(int sig, PyOS_sighandler_t handler)
2053{
2054#ifdef HAVE_SIGACTION
2055 /* Some code in Modules/signalmodule.c depends on sigaction() being
2056 * used here if HAVE_SIGACTION is defined. Fix that if this code
2057 * changes to invalidate that assumption.
2058 */
2059 struct sigaction context, ocontext;
2060 context.sa_handler = handler;
2061 sigemptyset(&context.sa_mask);
2062 context.sa_flags = 0;
2063 if (sigaction(sig, &context, &ocontext) == -1)
2064 return SIG_ERR;
2065 return ocontext.sa_handler;
2066#else
2067 PyOS_sighandler_t oldhandler;
2068 oldhandler = signal(sig, handler);
2069#ifdef HAVE_SIGINTERRUPT
2070 siginterrupt(sig, 1);
2071#endif
2072 return oldhandler;
2073#endif
2074}
2075
2076#ifdef __cplusplus
2077}
2078#endif