blob: b9f916bf39fac3a06fe49569b262402b02918e25 [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{
267#ifdef MS_WINDOWS
268 char codepage[100];
269 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
270 return get_codec_name(codepage);
271#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
272 char* codeset = nl_langinfo(CODESET);
273 if (!codeset || codeset[0] == '\0') {
274 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
275 return NULL;
276 }
277 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200278#elif defined(__ANDROID__)
279 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000280#else
281 PyErr_SetNone(PyExc_NotImplementedError);
282 return NULL;
283#endif
284}
285
286static void
Eric Snow1abcf672017-05-23 21:46:51 -0700287initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000288{
289 PyObject *importlib;
290 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000291 PyObject *value;
292
293 /* Import _importlib through its frozen version, _frozen_importlib. */
294 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
295 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
296 }
297 else if (Py_VerboseFlag) {
298 PySys_FormatStderr("import _frozen_importlib # frozen\n");
299 }
300 importlib = PyImport_AddModule("_frozen_importlib");
301 if (importlib == NULL) {
302 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
303 "sys.modules");
304 }
305 interp->importlib = importlib;
306 Py_INCREF(interp->importlib);
307
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300308 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
309 if (interp->import_func == NULL)
310 Py_FatalError("Py_Initialize: __import__ not found");
311 Py_INCREF(interp->import_func);
312
Victor Stinnercd6e6942015-09-18 09:11:57 +0200313 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000314 impmod = PyInit_imp();
315 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200316 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000317 }
318 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200319 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000320 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600321 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000322 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
323 }
324
Victor Stinnercd6e6942015-09-18 09:11:57 +0200325 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000326 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200327 if (value != NULL) {
328 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700329 value = PyObject_CallMethod(importlib,
330 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200331 }
Nick Coghland6009512014-11-20 21:39:37 +1000332 if (value == NULL) {
333 PyErr_Print();
334 Py_FatalError("Py_Initialize: importlib install failed");
335 }
336 Py_DECREF(value);
337 Py_DECREF(impmod);
338
339 _PyImportZip_Init();
340}
341
Eric Snow1abcf672017-05-23 21:46:51 -0700342static void
343initexternalimport(PyInterpreterState *interp)
344{
345 PyObject *value;
346 value = PyObject_CallMethod(interp->importlib,
347 "_install_external_importers", "");
348 if (value == NULL) {
349 PyErr_Print();
350 Py_FatalError("Py_EndInitialization: external importer setup failed");
351 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200352 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700353}
Nick Coghland6009512014-11-20 21:39:37 +1000354
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355/* Helper functions to better handle the legacy C locale
356 *
357 * The legacy C locale assumes ASCII as the default text encoding, which
358 * causes problems not only for the CPython runtime, but also other
359 * components like GNU readline.
360 *
361 * Accordingly, when the CLI detects it, it attempts to coerce it to a
362 * more capable UTF-8 based alternative as follows:
363 *
364 * if (_Py_LegacyLocaleDetected()) {
365 * _Py_CoerceLegacyLocale();
366 * }
367 *
368 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
369 *
370 * Locale coercion also impacts the default error handler for the standard
371 * streams: while the usual default is "strict", the default for the legacy
372 * C locale and for any of the coercion target locales is "surrogateescape".
373 */
374
375int
376_Py_LegacyLocaleDetected(void)
377{
378#ifndef MS_WINDOWS
379 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000380 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
381 * the POSIX locale as a simple alias for the C locale, so
382 * we may also want to check for that explicitly.
383 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000384 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
385 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
386#else
387 /* Windows uses code pages instead of locales, so no locale is legacy */
388 return 0;
389#endif
390}
391
Nick Coghlaneb817952017-06-18 12:29:42 +1000392static const char *_C_LOCALE_WARNING =
393 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
394 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
395 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
396 "locales is recommended.\n";
397
398static int
399_legacy_locale_warnings_enabled(void)
400{
401 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
402 return (coerce_c_locale != NULL &&
403 strncmp(coerce_c_locale, "warn", 5) == 0);
404}
405
406static void
407_emit_stderr_warning_for_legacy_locale(void)
408{
409 if (_legacy_locale_warnings_enabled()) {
410 if (_Py_LegacyLocaleDetected()) {
411 fprintf(stderr, "%s", _C_LOCALE_WARNING);
412 }
413 }
414}
415
Nick Coghlan6ea41862017-06-11 13:16:15 +1000416typedef struct _CandidateLocale {
417 const char *locale_name; /* The locale to try as a coercion target */
418} _LocaleCoercionTarget;
419
420static _LocaleCoercionTarget _TARGET_LOCALES[] = {
421 {"C.UTF-8"},
422 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000423 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000424 {NULL}
425};
426
427static char *
428get_default_standard_stream_error_handler(void)
429{
430 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
431 if (ctype_loc != NULL) {
432 /* "surrogateescape" is the default in the legacy C locale */
433 if (strcmp(ctype_loc, "C") == 0) {
434 return "surrogateescape";
435 }
436
437#ifdef PY_COERCE_C_LOCALE
438 /* "surrogateescape" is the default in locale coercion target locales */
439 const _LocaleCoercionTarget *target = NULL;
440 for (target = _TARGET_LOCALES; target->locale_name; target++) {
441 if (strcmp(ctype_loc, target->locale_name) == 0) {
442 return "surrogateescape";
443 }
444 }
445#endif
446 }
447
448 /* Otherwise return NULL to request the typical default error handler */
449 return NULL;
450}
451
452#ifdef PY_COERCE_C_LOCALE
453static const char *_C_LOCALE_COERCION_WARNING =
454 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
455 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
456
457static void
458_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
459{
460 const char *newloc = target->locale_name;
461
462 /* Reset locale back to currently configured defaults */
463 setlocale(LC_ALL, "");
464
465 /* Set the relevant locale environment variable */
466 if (setenv("LC_CTYPE", newloc, 1)) {
467 fprintf(stderr,
468 "Error setting LC_CTYPE, skipping C locale coercion\n");
469 return;
470 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000471 if (_legacy_locale_warnings_enabled()) {
472 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
473 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000474
475 /* Reconfigure with the overridden environment variables */
476 setlocale(LC_ALL, "");
477}
478#endif
479
480void
481_Py_CoerceLegacyLocale(void)
482{
483#ifdef PY_COERCE_C_LOCALE
484 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
485 * the locale settings *before* we try to do anything with the command
486 * line arguments. For cross-platform debugging purposes, we also need
487 * to give end users a way to force even scripts that are otherwise
488 * isolated from their environment to use the legacy ASCII-centric C
489 * locale.
490 *
491 * Ignoring -E and -I is safe from a security perspective, as we only use
492 * the setting to turn *off* the implicit locale coercion, and anyone with
493 * access to the process environment already has the ability to set
494 * `LC_ALL=C` to override the C level locale settings anyway.
495 */
496 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
497 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
498 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
499 const char *locale_override = getenv("LC_ALL");
500 if (locale_override == NULL || *locale_override == '\0') {
501 /* LC_ALL is also not set (or is set to an empty string) */
502 const _LocaleCoercionTarget *target = NULL;
503 for (target = _TARGET_LOCALES; target->locale_name; target++) {
504 const char *new_locale = setlocale(LC_CTYPE,
505 target->locale_name);
506 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000507#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
508 /* Also ensure that nl_langinfo works in this locale */
509 char *codeset = nl_langinfo(CODESET);
510 if (!codeset || *codeset == '\0') {
511 /* CODESET is not set or empty, so skip coercion */
512 new_locale = NULL;
513 setlocale(LC_CTYPE, "");
514 continue;
515 }
516#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000517 /* Successfully configured locale, so make it the default */
518 _coerce_default_locale_settings(target);
519 return;
520 }
521 }
522 }
523 }
524 /* No C locale warning here, as Py_Initialize will emit one later */
525#endif
526}
527
528
Eric Snow1abcf672017-05-23 21:46:51 -0700529/* Global initializations. Can be undone by Py_Finalize(). Don't
530 call this twice without an intervening Py_Finalize() call.
531
532 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
533 must have a corresponding call to Py_Finalize.
534
535 Locking: you must hold the interpreter lock while calling these APIs.
536 (If the lock has not yet been initialized, that's equivalent to
537 having the lock, but you cannot use multiple threads.)
538
539*/
540
541/* Begin interpreter initialization
542 *
543 * On return, the first thread and interpreter state have been created,
544 * but the compiler, signal handling, multithreading and
545 * multiple interpreter support, and codec infrastructure are not yet
546 * available.
547 *
548 * The import system will support builtin and frozen modules only.
549 * The only supported io is writing to sys.stderr
550 *
551 * If any operation invoked by this function fails, a fatal error is
552 * issued and the function does not return.
553 *
554 * Any code invoked from this function should *not* assume it has access
555 * to the Python C API (unless the API is explicitly listed as being
556 * safe to call without calling Py_Initialize first)
557 */
558
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200559/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700560 * Py_ReadConfig and Py_EndInitialization
561 */
562
563void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000564{
565 PyInterpreterState *interp;
566 PyThreadState *tstate;
567 PyObject *bimod, *sysmod, *pstderr;
568 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700569 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700570 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000571
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600572 _PyRuntime_Initialize();
573
Eric Snow1abcf672017-05-23 21:46:51 -0700574 if (config != NULL) {
575 core_config = *config;
576 }
577
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600578 if (_PyRuntime.initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700579 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
580 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600581 if (_PyRuntime.core_initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700582 Py_FatalError("Py_InitializeCore: runtime core already initialized");
583 }
584
585 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
586 * threads behave a little more gracefully at interpreter shutdown.
587 * We clobber it here so the new interpreter can start with a clean
588 * slate.
589 *
590 * However, this may still lead to misbehaviour if there are daemon
591 * threads still hanging around from a previous Py_Initialize/Finalize
592 * pair :(
593 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600594 _PyRuntime.finalizing = NULL;
595
596 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
597 fprintf(stderr,
598 "Error in PYTHONMALLOC: unknown allocator \"%s\"!\n",
599 core_config.allocator);
600 exit(1);
601 }
Nick Coghland6009512014-11-20 21:39:37 +1000602
Nick Coghlan6ea41862017-06-11 13:16:15 +1000603#ifdef __ANDROID__
604 /* Passing "" to setlocale() on Android requests the C locale rather
605 * than checking environment variables, so request C.UTF-8 explicitly
606 */
607 setlocale(LC_CTYPE, "C.UTF-8");
608#else
609#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000610 /* Set up the LC_CTYPE locale, so we can obtain
611 the locale's charset without having to switch
612 locales. */
613 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000614 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000615#endif
Nick Coghland6009512014-11-20 21:39:37 +1000616#endif
617
618 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
619 Py_DebugFlag = add_flag(Py_DebugFlag, p);
620 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
621 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
622 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
623 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
624 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
625 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700626 /* The variable is only tested for existence here;
627 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000628 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
629 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700630#ifdef MS_WINDOWS
631 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
632 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700633 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
634 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700635#endif
Nick Coghland6009512014-11-20 21:39:37 +1000636
Eric Snow1abcf672017-05-23 21:46:51 -0700637 _Py_HashRandomization_Init(&core_config);
638 if (!core_config.use_hash_seed || core_config.hash_seed) {
639 /* Random or non-zero hash seed */
640 Py_HashRandomizationFlag = 1;
641 }
Nick Coghland6009512014-11-20 21:39:37 +1000642
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600643 _PyInterpreterState_Enable(&_PyRuntime);
Nick Coghland6009512014-11-20 21:39:37 +1000644 interp = PyInterpreterState_New();
645 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700646 Py_FatalError("Py_InitializeCore: can't make main interpreter");
647 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700648 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000649
650 tstate = PyThreadState_New(interp);
651 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700652 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000653 (void) PyThreadState_Swap(tstate);
654
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000655 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000656 destroying the GIL might fail when it is being referenced from
657 another running thread (see issue #9901).
658 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000659 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000660 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000661 /* Auto-thread-state API */
662 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000663
664 _Py_ReadyTypes();
665
666 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700667 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000668
669 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700670 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000671
672 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700673 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000674
675 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700676 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000677
Eric Snow86b7afd2017-09-04 17:54:09 -0600678 PyObject *modules = PyDict_New();
679 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700680 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000681
Eric Snow86b7afd2017-09-04 17:54:09 -0600682 sysmod = _PySys_BeginInit();
683 if (sysmod == NULL)
684 Py_FatalError("Py_InitializeCore: can't initialize sys");
685 interp->sysdict = PyModule_GetDict(sysmod);
686 if (interp->sysdict == NULL)
687 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
688 Py_INCREF(interp->sysdict);
689 PyDict_SetItemString(interp->sysdict, "modules", modules);
690 _PyImport_FixupBuiltin(sysmod, "sys", modules);
691
Nick Coghland6009512014-11-20 21:39:37 +1000692 /* Init Unicode implementation; relies on the codec registry */
693 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700694 Py_FatalError("Py_InitializeCore: can't initialize unicode");
695
Nick Coghland6009512014-11-20 21:39:37 +1000696 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700697 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000698
699 bimod = _PyBuiltin_Init();
700 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700701 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snow86b7afd2017-09-04 17:54:09 -0600702 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000703 interp->builtins = PyModule_GetDict(bimod);
704 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700705 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000706 Py_INCREF(interp->builtins);
707
708 /* initialize builtin exceptions */
709 _PyExc_Init(bimod);
710
Nick Coghland6009512014-11-20 21:39:37 +1000711 /* Set up a preliminary stderr printer until we have enough
712 infrastructure for the io module in place. */
713 pstderr = PyFile_NewStdPrinter(fileno(stderr));
714 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700715 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000716 _PySys_SetObjectId(&PyId_stderr, pstderr);
717 PySys_SetObject("__stderr__", pstderr);
718 Py_DECREF(pstderr);
719
720 _PyImport_Init();
721
722 _PyImportHooks_Init();
723
724 /* Initialize _warnings. */
725 _PyWarnings_Init();
726
Eric Snow1abcf672017-05-23 21:46:51 -0700727 /* This call sets up builtin and frozen import support */
728 if (!interp->core_config._disable_importlib) {
729 initimport(interp, sysmod);
730 }
731
732 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600733 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700734}
735
Eric Snowc7ec9982017-05-23 23:00:52 -0700736/* Read configuration settings from standard locations
737 *
738 * This function doesn't make any changes to the interpreter state - it
739 * merely populates any missing configuration settings. This allows an
740 * embedding application to completely override a config option by
741 * setting it before calling this function, or else modify the default
742 * setting before passing the fully populated config to Py_EndInitialization.
743 *
744 * More advanced selective initialization tricks are possible by calling
745 * this function multiple times with various preconfigured settings.
746 */
747
748int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
749{
750 /* Signal handlers are installed by default */
751 if (config->install_signal_handlers < 0) {
752 config->install_signal_handlers = 1;
753 }
754
755 return 0;
756}
757
758/* Update interpreter state based on supplied configuration settings
759 *
760 * After calling this function, most of the restrictions on the interpreter
761 * are lifted. The only remaining incomplete settings are those related
762 * to the main module (sys.argv[0], __main__ metadata)
763 *
764 * Calling this when the interpreter is not initializing, is already
765 * initialized or without a valid current thread state is a fatal error.
766 * Other errors should be reported as normal Python exceptions with a
767 * non-zero return code.
768 */
769int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700770{
771 PyInterpreterState *interp;
772 PyThreadState *tstate;
773
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600774 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700775 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
776 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600777 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700778 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
779 }
780
Eric Snow1abcf672017-05-23 21:46:51 -0700781 /* Get current thread state and interpreter pointer */
782 tstate = PyThreadState_GET();
783 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700784 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700785 interp = tstate->interp;
786 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700787 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700788
789 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700790 interp->config = *config;
791
Eric Snow1abcf672017-05-23 21:46:51 -0700792 if (interp->core_config._disable_importlib) {
793 /* Special mode for freeze_importlib: run with no import system
794 *
795 * This means anything which needs support from extension modules
796 * or pure Python code in the standard library won't work.
797 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600798 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700799 return 0;
800 }
801 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000802
Victor Stinner13019fd2015-04-03 13:10:54 +0200803 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700804 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200805
Eric Snow1abcf672017-05-23 21:46:51 -0700806 /* Finish setting up the sys module and import system */
807 /* GetPath may initialize state that _PySys_EndInit locks
808 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700809 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700810 PySys_SetPath(Py_GetPath());
811 if (_PySys_EndInit(interp->sysdict) < 0)
812 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700813 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000814
815 /* initialize the faulthandler module */
816 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700817 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000818
Nick Coghland6009512014-11-20 21:39:37 +1000819 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700820 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000821
Eric Snowc7ec9982017-05-23 23:00:52 -0700822 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000823 initsigs(); /* Signal handling stuff, including initintr() */
824
825 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700826 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000827
828 initmain(interp); /* Module __main__ */
829 if (initstdio() < 0)
830 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700831 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000832
833 /* Initialize warnings. */
834 if (PySys_HasWarnOptions()) {
835 PyObject *warnings_module = PyImport_ImportModule("warnings");
836 if (warnings_module == NULL) {
837 fprintf(stderr, "'import warnings' failed; traceback:\n");
838 PyErr_Print();
839 }
840 Py_XDECREF(warnings_module);
841 }
842
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600843 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700844
Nick Coghland6009512014-11-20 21:39:37 +1000845 if (!Py_NoSiteFlag)
846 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700847
Eric Snowc7ec9982017-05-23 23:00:52 -0700848 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000849}
850
Eric Snowc7ec9982017-05-23 23:00:52 -0700851#undef _INIT_DEBUG_PRINT
852
Nick Coghland6009512014-11-20 21:39:37 +1000853void
Eric Snow1abcf672017-05-23 21:46:51 -0700854_Py_InitializeEx_Private(int install_sigs, int install_importlib)
855{
856 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700857 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700858
859 /* TODO: Moar config options! */
860 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
861 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700862 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700863 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700864 /* TODO: Print any exceptions raised by these operations */
865 if (_Py_ReadMainInterpreterConfig(&config))
866 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
867 if (_Py_InitializeMainInterpreter(&config))
868 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700869}
870
871
872void
Nick Coghland6009512014-11-20 21:39:37 +1000873Py_InitializeEx(int install_sigs)
874{
875 _Py_InitializeEx_Private(install_sigs, 1);
876}
877
878void
879Py_Initialize(void)
880{
881 Py_InitializeEx(1);
882}
883
884
885#ifdef COUNT_ALLOCS
886extern void dump_counts(FILE*);
887#endif
888
889/* Flush stdout and stderr */
890
891static int
892file_is_closed(PyObject *fobj)
893{
894 int r;
895 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
896 if (tmp == NULL) {
897 PyErr_Clear();
898 return 0;
899 }
900 r = PyObject_IsTrue(tmp);
901 Py_DECREF(tmp);
902 if (r < 0)
903 PyErr_Clear();
904 return r > 0;
905}
906
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000907static int
Nick Coghland6009512014-11-20 21:39:37 +1000908flush_std_files(void)
909{
910 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
911 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
912 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000913 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000914
915 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700916 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000917 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000918 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000919 status = -1;
920 }
Nick Coghland6009512014-11-20 21:39:37 +1000921 else
922 Py_DECREF(tmp);
923 }
924
925 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700926 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000927 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000928 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000929 status = -1;
930 }
Nick Coghland6009512014-11-20 21:39:37 +1000931 else
932 Py_DECREF(tmp);
933 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000934
935 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000936}
937
938/* Undo the effect of Py_Initialize().
939
940 Beware: if multiple interpreter and/or thread states exist, these
941 are not wiped out; only the current thread and interpreter state
942 are deleted. But since everything else is deleted, those other
943 interpreter and thread states should no longer be used.
944
945 (XXX We should do better, e.g. wipe out all interpreters and
946 threads.)
947
948 Locking: as above.
949
950*/
951
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000952int
953Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000954{
955 PyInterpreterState *interp;
956 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000957 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000958
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600959 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000960 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000961
962 wait_for_thread_shutdown();
963
964 /* The interpreter is still entirely intact at this point, and the
965 * exit funcs may be relying on that. In particular, if some thread
966 * or exit func is still waiting to do an import, the import machinery
967 * expects Py_IsInitialized() to return true. So don't say the
968 * interpreter is uninitialized until after the exit funcs have run.
969 * Note that Threading.py uses an exit func to do a join on all the
970 * threads created thru it, so this also protects pending imports in
971 * the threads created via Threading.
972 */
973 call_py_exitfuncs();
974
975 /* Get current thread state and interpreter pointer */
976 tstate = PyThreadState_GET();
977 interp = tstate->interp;
978
979 /* Remaining threads (e.g. daemon threads) will automatically exit
980 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600981 _PyRuntime.finalizing = tstate;
982 _PyRuntime.initialized = 0;
983 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000984
Victor Stinnere0deff32015-03-24 13:46:18 +0100985 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000986 if (flush_std_files() < 0) {
987 status = -1;
988 }
Nick Coghland6009512014-11-20 21:39:37 +1000989
990 /* Disable signal handling */
991 PyOS_FiniInterrupts();
992
993 /* Collect garbage. This may call finalizers; it's nice to call these
994 * before all modules are destroyed.
995 * XXX If a __del__ or weakref callback is triggered here, and tries to
996 * XXX import a module, bad things can happen, because Python no
997 * XXX longer believes it's initialized.
998 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
999 * XXX is easy to provoke that way. I've also seen, e.g.,
1000 * XXX Exception exceptions.ImportError: 'No module named sha'
1001 * XXX in <function callback at 0x008F5718> ignored
1002 * XXX but I'm unclear on exactly how that one happens. In any case,
1003 * XXX I haven't seen a real-life report of either of these.
1004 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001005 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001006#ifdef COUNT_ALLOCS
1007 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1008 each collection might release some types from the type
1009 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001010 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001011 /* nothing */;
1012#endif
1013 /* Destroy all modules */
1014 PyImport_Cleanup();
1015
Victor Stinnere0deff32015-03-24 13:46:18 +01001016 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 if (flush_std_files() < 0) {
1018 status = -1;
1019 }
Nick Coghland6009512014-11-20 21:39:37 +10001020
1021 /* Collect final garbage. This disposes of cycles created by
1022 * class definitions, for example.
1023 * XXX This is disabled because it caused too many problems. If
1024 * XXX a __del__ or weakref callback triggers here, Python code has
1025 * XXX a hard time running, because even the sys module has been
1026 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1027 * XXX One symptom is a sequence of information-free messages
1028 * XXX coming from threads (if a __del__ or callback is invoked,
1029 * XXX other threads can execute too, and any exception they encounter
1030 * XXX triggers a comedy of errors as subsystem after subsystem
1031 * XXX fails to find what it *expects* to find in sys to help report
1032 * XXX the exception and consequent unexpected failures). I've also
1033 * XXX seen segfaults then, after adding print statements to the
1034 * XXX Python code getting called.
1035 */
1036#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001037 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001038#endif
1039
1040 /* Disable tracemalloc after all Python objects have been destroyed,
1041 so it is possible to use tracemalloc in objects destructor. */
1042 _PyTraceMalloc_Fini();
1043
1044 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1045 _PyImport_Fini();
1046
1047 /* Cleanup typeobject.c's internal caches. */
1048 _PyType_Fini();
1049
1050 /* unload faulthandler module */
1051 _PyFaulthandler_Fini();
1052
1053 /* Debugging stuff */
1054#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001055 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001056#endif
1057 /* dump hash stats */
1058 _PyHash_Fini();
1059
1060 _PY_DEBUG_PRINT_TOTAL_REFS();
1061
1062#ifdef Py_TRACE_REFS
1063 /* Display all objects still alive -- this can invoke arbitrary
1064 * __repr__ overrides, so requires a mostly-intact interpreter.
1065 * Alas, a lot of stuff may still be alive now that will be cleaned
1066 * up later.
1067 */
1068 if (Py_GETENV("PYTHONDUMPREFS"))
1069 _Py_PrintReferences(stderr);
1070#endif /* Py_TRACE_REFS */
1071
1072 /* Clear interpreter state and all thread states. */
1073 PyInterpreterState_Clear(interp);
1074
1075 /* Now we decref the exception classes. After this point nothing
1076 can raise an exception. That's okay, because each Fini() method
1077 below has been checked to make sure no exceptions are ever
1078 raised.
1079 */
1080
1081 _PyExc_Fini();
1082
1083 /* Sundry finalizers */
1084 PyMethod_Fini();
1085 PyFrame_Fini();
1086 PyCFunction_Fini();
1087 PyTuple_Fini();
1088 PyList_Fini();
1089 PySet_Fini();
1090 PyBytes_Fini();
1091 PyByteArray_Fini();
1092 PyLong_Fini();
1093 PyFloat_Fini();
1094 PyDict_Fini();
1095 PySlice_Fini();
1096 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001097 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001098 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001099 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001100
1101 /* Cleanup Unicode implementation */
1102 _PyUnicode_Fini();
1103
1104 /* reset file system default encoding */
1105 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1106 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1107 Py_FileSystemDefaultEncoding = NULL;
1108 }
1109
1110 /* XXX Still allocated:
1111 - various static ad-hoc pointers to interned strings
1112 - int and float free list blocks
1113 - whatever various modules and libraries allocate
1114 */
1115
1116 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1117
1118 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001119 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001120
1121 /* Delete current thread. After this, many C API calls become crashy. */
1122 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001123
Nick Coghland6009512014-11-20 21:39:37 +10001124 PyInterpreterState_Delete(interp);
1125
1126#ifdef Py_TRACE_REFS
1127 /* Display addresses (& refcnts) of all objects still alive.
1128 * An address can be used to find the repr of the object, printed
1129 * above by _Py_PrintReferences.
1130 */
1131 if (Py_GETENV("PYTHONDUMPREFS"))
1132 _Py_PrintReferenceAddresses(stderr);
1133#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001134#ifdef WITH_PYMALLOC
1135 if (_PyMem_PymallocEnabled()) {
1136 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1137 if (opt != NULL && *opt != '\0')
1138 _PyObject_DebugMallocStats(stderr);
1139 }
Nick Coghland6009512014-11-20 21:39:37 +10001140#endif
1141
1142 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001143 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001144 return status;
1145}
1146
1147void
1148Py_Finalize(void)
1149{
1150 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001151}
1152
1153/* Create and initialize a new interpreter and thread, and return the
1154 new thread. This requires that Py_Initialize() has been called
1155 first.
1156
1157 Unsuccessful initialization yields a NULL pointer. Note that *no*
1158 exception information is available even in this case -- the
1159 exception information is held in the thread, and there is no
1160 thread.
1161
1162 Locking: as above.
1163
1164*/
1165
1166PyThreadState *
1167Py_NewInterpreter(void)
1168{
1169 PyInterpreterState *interp;
1170 PyThreadState *tstate, *save_tstate;
1171 PyObject *bimod, *sysmod;
1172
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001173 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001174 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1175
Victor Stinner8a1be612016-03-14 22:07:55 +01001176 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1177 interpreters: disable PyGILState_Check(). */
1178 _PyGILState_check_enabled = 0;
1179
Nick Coghland6009512014-11-20 21:39:37 +10001180 interp = PyInterpreterState_New();
1181 if (interp == NULL)
1182 return NULL;
1183
1184 tstate = PyThreadState_New(interp);
1185 if (tstate == NULL) {
1186 PyInterpreterState_Delete(interp);
1187 return NULL;
1188 }
1189
1190 save_tstate = PyThreadState_Swap(tstate);
1191
Eric Snow1abcf672017-05-23 21:46:51 -07001192 /* Copy the current interpreter config into the new interpreter */
1193 if (save_tstate != NULL) {
1194 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001195 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001196 } else {
1197 /* No current thread state, copy from the main interpreter */
1198 PyInterpreterState *main_interp = PyInterpreterState_Main();
1199 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001200 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001201 }
1202
Nick Coghland6009512014-11-20 21:39:37 +10001203 /* XXX The following is lax in error checking */
1204
Eric Snow86b7afd2017-09-04 17:54:09 -06001205 PyObject *modules = PyDict_New();
1206 if (modules == NULL)
1207 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +10001208
Eric Snow86b7afd2017-09-04 17:54:09 -06001209 sysmod = _PyImport_FindBuiltin("sys", modules);
1210 if (sysmod != NULL) {
1211 interp->sysdict = PyModule_GetDict(sysmod);
1212 if (interp->sysdict == NULL)
1213 goto handle_error;
1214 Py_INCREF(interp->sysdict);
1215 PyDict_SetItemString(interp->sysdict, "modules", modules);
1216 PySys_SetPath(Py_GetPath());
1217 _PySys_EndInit(interp->sysdict);
1218 }
1219
1220 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001221 if (bimod != NULL) {
1222 interp->builtins = PyModule_GetDict(bimod);
1223 if (interp->builtins == NULL)
1224 goto handle_error;
1225 Py_INCREF(interp->builtins);
1226 }
1227
1228 /* initialize builtin exceptions */
1229 _PyExc_Init(bimod);
1230
Nick Coghland6009512014-11-20 21:39:37 +10001231 if (bimod != NULL && sysmod != NULL) {
1232 PyObject *pstderr;
1233
Nick Coghland6009512014-11-20 21:39:37 +10001234 /* Set up a preliminary stderr printer until we have enough
1235 infrastructure for the io module in place. */
1236 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1237 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001238 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001239 _PySys_SetObjectId(&PyId_stderr, pstderr);
1240 PySys_SetObject("__stderr__", pstderr);
1241 Py_DECREF(pstderr);
1242
1243 _PyImportHooks_Init();
1244
Eric Snow1abcf672017-05-23 21:46:51 -07001245 initimport(interp, sysmod);
1246 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001247
1248 if (initfsencoding(interp) < 0)
1249 goto handle_error;
1250
1251 if (initstdio() < 0)
1252 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001253 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001254 initmain(interp);
1255 if (!Py_NoSiteFlag)
1256 initsite();
1257 }
1258
1259 if (!PyErr_Occurred())
1260 return tstate;
1261
1262handle_error:
1263 /* Oops, it didn't work. Undo it all. */
1264
1265 PyErr_PrintEx(0);
1266 PyThreadState_Clear(tstate);
1267 PyThreadState_Swap(save_tstate);
1268 PyThreadState_Delete(tstate);
1269 PyInterpreterState_Delete(interp);
1270
1271 return NULL;
1272}
1273
1274/* Delete an interpreter and its last thread. This requires that the
1275 given thread state is current, that the thread has no remaining
1276 frames, and that it is its interpreter's only remaining thread.
1277 It is a fatal error to violate these constraints.
1278
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001279 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001280 everything, regardless.)
1281
1282 Locking: as above.
1283
1284*/
1285
1286void
1287Py_EndInterpreter(PyThreadState *tstate)
1288{
1289 PyInterpreterState *interp = tstate->interp;
1290
1291 if (tstate != PyThreadState_GET())
1292 Py_FatalError("Py_EndInterpreter: thread is not current");
1293 if (tstate->frame != NULL)
1294 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1295
1296 wait_for_thread_shutdown();
1297
1298 if (tstate != interp->tstate_head || tstate->next != NULL)
1299 Py_FatalError("Py_EndInterpreter: not the last thread");
1300
1301 PyImport_Cleanup();
1302 PyInterpreterState_Clear(interp);
1303 PyThreadState_Swap(NULL);
1304 PyInterpreterState_Delete(interp);
1305}
1306
1307#ifdef MS_WINDOWS
1308static wchar_t *progname = L"python";
1309#else
1310static wchar_t *progname = L"python3";
1311#endif
1312
1313void
1314Py_SetProgramName(wchar_t *pn)
1315{
1316 if (pn && *pn)
1317 progname = pn;
1318}
1319
1320wchar_t *
1321Py_GetProgramName(void)
1322{
1323 return progname;
1324}
1325
1326static wchar_t *default_home = NULL;
1327static wchar_t env_home[MAXPATHLEN+1];
1328
1329void
1330Py_SetPythonHome(wchar_t *home)
1331{
1332 default_home = home;
1333}
1334
1335wchar_t *
1336Py_GetPythonHome(void)
1337{
1338 wchar_t *home = default_home;
1339 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1340 char* chome = Py_GETENV("PYTHONHOME");
1341 if (chome) {
1342 size_t size = Py_ARRAY_LENGTH(env_home);
1343 size_t r = mbstowcs(env_home, chome, size);
1344 if (r != (size_t)-1 && r < size)
1345 home = env_home;
1346 }
1347
1348 }
1349 return home;
1350}
1351
1352/* Create __main__ module */
1353
1354static void
1355initmain(PyInterpreterState *interp)
1356{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001357 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001358 m = PyImport_AddModule("__main__");
1359 if (m == NULL)
1360 Py_FatalError("can't create __main__ module");
1361 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001362 ann_dict = PyDict_New();
1363 if ((ann_dict == NULL) ||
1364 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1365 Py_FatalError("Failed to initialize __main__.__annotations__");
1366 }
1367 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001368 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1369 PyObject *bimod = PyImport_ImportModule("builtins");
1370 if (bimod == NULL) {
1371 Py_FatalError("Failed to retrieve builtins module");
1372 }
1373 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1374 Py_FatalError("Failed to initialize __main__.__builtins__");
1375 }
1376 Py_DECREF(bimod);
1377 }
1378 /* Main is a little special - imp.is_builtin("__main__") will return
1379 * False, but BuiltinImporter is still the most appropriate initial
1380 * setting for its __loader__ attribute. A more suitable value will
1381 * be set if __main__ gets further initialized later in the startup
1382 * process.
1383 */
1384 loader = PyDict_GetItemString(d, "__loader__");
1385 if (loader == NULL || loader == Py_None) {
1386 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1387 "BuiltinImporter");
1388 if (loader == NULL) {
1389 Py_FatalError("Failed to retrieve BuiltinImporter");
1390 }
1391 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1392 Py_FatalError("Failed to initialize __main__.__loader__");
1393 }
1394 Py_DECREF(loader);
1395 }
1396}
1397
1398static int
1399initfsencoding(PyInterpreterState *interp)
1400{
1401 PyObject *codec;
1402
Steve Dowercc16be82016-09-08 10:35:16 -07001403#ifdef MS_WINDOWS
1404 if (Py_LegacyWindowsFSEncodingFlag)
1405 {
1406 Py_FileSystemDefaultEncoding = "mbcs";
1407 Py_FileSystemDefaultEncodeErrors = "replace";
1408 }
1409 else
1410 {
1411 Py_FileSystemDefaultEncoding = "utf-8";
1412 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1413 }
1414#else
Nick Coghland6009512014-11-20 21:39:37 +10001415 if (Py_FileSystemDefaultEncoding == NULL)
1416 {
1417 Py_FileSystemDefaultEncoding = get_locale_encoding();
1418 if (Py_FileSystemDefaultEncoding == NULL)
1419 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1420
1421 Py_HasFileSystemDefaultEncoding = 0;
1422 interp->fscodec_initialized = 1;
1423 return 0;
1424 }
Steve Dowercc16be82016-09-08 10:35:16 -07001425#endif
Nick Coghland6009512014-11-20 21:39:37 +10001426
1427 /* the encoding is mbcs, utf-8 or ascii */
1428 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1429 if (!codec) {
1430 /* Such error can only occurs in critical situations: no more
1431 * memory, import a module of the standard library failed,
1432 * etc. */
1433 return -1;
1434 }
1435 Py_DECREF(codec);
1436 interp->fscodec_initialized = 1;
1437 return 0;
1438}
1439
1440/* Import the site module (not into __main__ though) */
1441
1442static void
1443initsite(void)
1444{
1445 PyObject *m;
1446 m = PyImport_ImportModule("site");
1447 if (m == NULL) {
1448 fprintf(stderr, "Failed to import the site module\n");
1449 PyErr_Print();
1450 Py_Finalize();
1451 exit(1);
1452 }
1453 else {
1454 Py_DECREF(m);
1455 }
1456}
1457
Victor Stinner874dbe82015-09-04 17:29:57 +02001458/* Check if a file descriptor is valid or not.
1459 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1460static int
1461is_valid_fd(int fd)
1462{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001463#ifdef __APPLE__
1464 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1465 and the other side of the pipe is closed, dup(1) succeed, whereas
1466 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1467 such error. */
1468 struct stat st;
1469 return (fstat(fd, &st) == 0);
1470#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001471 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001472 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001473 return 0;
1474 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001475 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1476 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1477 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001478 fd2 = dup(fd);
1479 if (fd2 >= 0)
1480 close(fd2);
1481 _Py_END_SUPPRESS_IPH
1482 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001483#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001484}
1485
1486/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001487static PyObject*
1488create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001489 int fd, int write_mode, const char* name,
1490 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001491{
1492 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1493 const char* mode;
1494 const char* newline;
1495 PyObject *line_buffering;
1496 int buffering, isatty;
1497 _Py_IDENTIFIER(open);
1498 _Py_IDENTIFIER(isatty);
1499 _Py_IDENTIFIER(TextIOWrapper);
1500 _Py_IDENTIFIER(mode);
1501
Victor Stinner874dbe82015-09-04 17:29:57 +02001502 if (!is_valid_fd(fd))
1503 Py_RETURN_NONE;
1504
Nick Coghland6009512014-11-20 21:39:37 +10001505 /* stdin is always opened in buffered mode, first because it shouldn't
1506 make a difference in common use cases, second because TextIOWrapper
1507 depends on the presence of a read1() method which only exists on
1508 buffered streams.
1509 */
1510 if (Py_UnbufferedStdioFlag && write_mode)
1511 buffering = 0;
1512 else
1513 buffering = -1;
1514 if (write_mode)
1515 mode = "wb";
1516 else
1517 mode = "rb";
1518 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1519 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001520 Py_None, Py_None, /* encoding, errors */
1521 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001522 if (buf == NULL)
1523 goto error;
1524
1525 if (buffering) {
1526 _Py_IDENTIFIER(raw);
1527 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1528 if (raw == NULL)
1529 goto error;
1530 }
1531 else {
1532 raw = buf;
1533 Py_INCREF(raw);
1534 }
1535
Steve Dower39294992016-08-30 21:22:36 -07001536#ifdef MS_WINDOWS
1537 /* Windows console IO is always UTF-8 encoded */
1538 if (PyWindowsConsoleIO_Check(raw))
1539 encoding = "utf-8";
1540#endif
1541
Nick Coghland6009512014-11-20 21:39:37 +10001542 text = PyUnicode_FromString(name);
1543 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1544 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001545 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001546 if (res == NULL)
1547 goto error;
1548 isatty = PyObject_IsTrue(res);
1549 Py_DECREF(res);
1550 if (isatty == -1)
1551 goto error;
1552 if (isatty || Py_UnbufferedStdioFlag)
1553 line_buffering = Py_True;
1554 else
1555 line_buffering = Py_False;
1556
1557 Py_CLEAR(raw);
1558 Py_CLEAR(text);
1559
1560#ifdef MS_WINDOWS
1561 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1562 newlines to "\n".
1563 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1564 newline = NULL;
1565#else
1566 /* sys.stdin: split lines at "\n".
1567 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1568 newline = "\n";
1569#endif
1570
1571 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1572 buf, encoding, errors,
1573 newline, line_buffering);
1574 Py_CLEAR(buf);
1575 if (stream == NULL)
1576 goto error;
1577
1578 if (write_mode)
1579 mode = "w";
1580 else
1581 mode = "r";
1582 text = PyUnicode_FromString(mode);
1583 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1584 goto error;
1585 Py_CLEAR(text);
1586 return stream;
1587
1588error:
1589 Py_XDECREF(buf);
1590 Py_XDECREF(stream);
1591 Py_XDECREF(text);
1592 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001593
Victor Stinner874dbe82015-09-04 17:29:57 +02001594 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1595 /* Issue #24891: the file descriptor was closed after the first
1596 is_valid_fd() check was called. Ignore the OSError and set the
1597 stream to None. */
1598 PyErr_Clear();
1599 Py_RETURN_NONE;
1600 }
1601 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001602}
1603
1604/* Initialize sys.stdin, stdout, stderr and builtins.open */
1605static int
1606initstdio(void)
1607{
1608 PyObject *iomod = NULL, *wrapper;
1609 PyObject *bimod = NULL;
1610 PyObject *m;
1611 PyObject *std = NULL;
1612 int status = 0, fd;
1613 PyObject * encoding_attr;
1614 char *pythonioencoding = NULL, *encoding, *errors;
1615
1616 /* Hack to avoid a nasty recursion issue when Python is invoked
1617 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1618 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1619 goto error;
1620 }
1621 Py_DECREF(m);
1622
1623 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1624 goto error;
1625 }
1626 Py_DECREF(m);
1627
1628 if (!(bimod = PyImport_ImportModule("builtins"))) {
1629 goto error;
1630 }
1631
1632 if (!(iomod = PyImport_ImportModule("io"))) {
1633 goto error;
1634 }
1635 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1636 goto error;
1637 }
1638
1639 /* Set builtins.open */
1640 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1641 Py_DECREF(wrapper);
1642 goto error;
1643 }
1644 Py_DECREF(wrapper);
1645
1646 encoding = _Py_StandardStreamEncoding;
1647 errors = _Py_StandardStreamErrors;
1648 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001649 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1650 if (pythonioencoding) {
1651 char *err;
1652 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1653 if (pythonioencoding == NULL) {
1654 PyErr_NoMemory();
1655 goto error;
1656 }
1657 err = strchr(pythonioencoding, ':');
1658 if (err) {
1659 *err = '\0';
1660 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001661 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001662 errors = err;
1663 }
1664 }
1665 if (*pythonioencoding && !encoding) {
1666 encoding = pythonioencoding;
1667 }
1668 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001669 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001670 /* Choose the default error handler based on the current locale */
1671 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001672 }
Nick Coghland6009512014-11-20 21:39:37 +10001673 }
1674
1675 /* Set sys.stdin */
1676 fd = fileno(stdin);
1677 /* Under some conditions stdin, stdout and stderr may not be connected
1678 * and fileno() may point to an invalid file descriptor. For example
1679 * GUI apps don't have valid standard streams by default.
1680 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001681 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1682 if (std == NULL)
1683 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001684 PySys_SetObject("__stdin__", std);
1685 _PySys_SetObjectId(&PyId_stdin, std);
1686 Py_DECREF(std);
1687
1688 /* Set sys.stdout */
1689 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001690 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1691 if (std == NULL)
1692 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001693 PySys_SetObject("__stdout__", std);
1694 _PySys_SetObjectId(&PyId_stdout, std);
1695 Py_DECREF(std);
1696
1697#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1698 /* Set sys.stderr, replaces the preliminary stderr */
1699 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001700 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1701 if (std == NULL)
1702 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001703
1704 /* Same as hack above, pre-import stderr's codec to avoid recursion
1705 when import.c tries to write to stderr in verbose mode. */
1706 encoding_attr = PyObject_GetAttrString(std, "encoding");
1707 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001708 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001709 if (std_encoding != NULL) {
1710 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1711 Py_XDECREF(codec_info);
1712 }
1713 Py_DECREF(encoding_attr);
1714 }
1715 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1716
1717 if (PySys_SetObject("__stderr__", std) < 0) {
1718 Py_DECREF(std);
1719 goto error;
1720 }
1721 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1722 Py_DECREF(std);
1723 goto error;
1724 }
1725 Py_DECREF(std);
1726#endif
1727
1728 if (0) {
1729 error:
1730 status = -1;
1731 }
1732
1733 /* We won't need them anymore. */
1734 if (_Py_StandardStreamEncoding) {
1735 PyMem_RawFree(_Py_StandardStreamEncoding);
1736 _Py_StandardStreamEncoding = NULL;
1737 }
1738 if (_Py_StandardStreamErrors) {
1739 PyMem_RawFree(_Py_StandardStreamErrors);
1740 _Py_StandardStreamErrors = NULL;
1741 }
1742 PyMem_Free(pythonioencoding);
1743 Py_XDECREF(bimod);
1744 Py_XDECREF(iomod);
1745 return status;
1746}
1747
1748
Victor Stinner10dc4842015-03-24 12:01:30 +01001749static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001750_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001751{
Victor Stinner10dc4842015-03-24 12:01:30 +01001752 fputc('\n', stderr);
1753 fflush(stderr);
1754
1755 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001756 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001757}
Victor Stinner791da1c2016-03-14 16:53:12 +01001758
1759/* Print the current exception (if an exception is set) with its traceback,
1760 or display the current Python stack.
1761
1762 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1763 called on catastrophic cases.
1764
1765 Return 1 if the traceback was displayed, 0 otherwise. */
1766
1767static int
1768_Py_FatalError_PrintExc(int fd)
1769{
1770 PyObject *ferr, *res;
1771 PyObject *exception, *v, *tb;
1772 int has_tb;
1773
1774 if (PyThreadState_GET() == NULL) {
1775 /* The GIL is released: trying to acquire it is likely to deadlock,
1776 just give up. */
1777 return 0;
1778 }
1779
1780 PyErr_Fetch(&exception, &v, &tb);
1781 if (exception == NULL) {
1782 /* No current exception */
1783 return 0;
1784 }
1785
1786 ferr = _PySys_GetObjectId(&PyId_stderr);
1787 if (ferr == NULL || ferr == Py_None) {
1788 /* sys.stderr is not set yet or set to None,
1789 no need to try to display the exception */
1790 return 0;
1791 }
1792
1793 PyErr_NormalizeException(&exception, &v, &tb);
1794 if (tb == NULL) {
1795 tb = Py_None;
1796 Py_INCREF(tb);
1797 }
1798 PyException_SetTraceback(v, tb);
1799 if (exception == NULL) {
1800 /* PyErr_NormalizeException() failed */
1801 return 0;
1802 }
1803
1804 has_tb = (tb != Py_None);
1805 PyErr_Display(exception, v, tb);
1806 Py_XDECREF(exception);
1807 Py_XDECREF(v);
1808 Py_XDECREF(tb);
1809
1810 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001811 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001812 if (res == NULL)
1813 PyErr_Clear();
1814 else
1815 Py_DECREF(res);
1816
1817 return has_tb;
1818}
1819
Nick Coghland6009512014-11-20 21:39:37 +10001820/* Print fatal error message and abort */
1821
1822void
1823Py_FatalError(const char *msg)
1824{
1825 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001826 static int reentrant = 0;
1827#ifdef MS_WINDOWS
1828 size_t len;
1829 WCHAR* buffer;
1830 size_t i;
1831#endif
1832
1833 if (reentrant) {
1834 /* Py_FatalError() caused a second fatal error.
1835 Example: flush_std_files() raises a recursion error. */
1836 goto exit;
1837 }
1838 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001839
1840 fprintf(stderr, "Fatal Python error: %s\n", msg);
1841 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001842
Victor Stinnere0deff32015-03-24 13:46:18 +01001843 /* Print the exception (if an exception is set) with its traceback,
1844 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001845 if (!_Py_FatalError_PrintExc(fd))
1846 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001847
Victor Stinner2025d782016-03-16 23:19:15 +01001848 /* The main purpose of faulthandler is to display the traceback. We already
1849 * did our best to display it. So faulthandler can now be disabled.
1850 * (Don't trigger it on abort().) */
1851 _PyFaulthandler_Fini();
1852
Victor Stinner791da1c2016-03-14 16:53:12 +01001853 /* Check if the current Python thread hold the GIL */
1854 if (PyThreadState_GET() != NULL) {
1855 /* Flush sys.stdout and sys.stderr */
1856 flush_std_files();
1857 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001858
Nick Coghland6009512014-11-20 21:39:37 +10001859#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001860 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001861
Victor Stinner53345a42015-03-25 01:55:14 +01001862 /* Convert the message to wchar_t. This uses a simple one-to-one
1863 conversion, assuming that the this error message actually uses ASCII
1864 only. If this ceases to be true, we will have to convert. */
1865 buffer = alloca( (len+1) * (sizeof *buffer));
1866 for( i=0; i<=len; ++i)
1867 buffer[i] = msg[i];
1868 OutputDebugStringW(L"Fatal Python error: ");
1869 OutputDebugStringW(buffer);
1870 OutputDebugStringW(L"\n");
1871#endif /* MS_WINDOWS */
1872
1873exit:
1874#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001875 DebugBreak();
1876#endif
Nick Coghland6009512014-11-20 21:39:37 +10001877 abort();
1878}
1879
1880/* Clean up and exit */
1881
Victor Stinnerd7292b52016-06-17 12:29:00 +02001882# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001883
Nick Coghland6009512014-11-20 21:39:37 +10001884/* For the atexit module. */
1885void _Py_PyAtExit(void (*func)(void))
1886{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001887 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001888}
1889
1890static void
1891call_py_exitfuncs(void)
1892{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001893 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001894 return;
1895
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001896 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001897 PyErr_Clear();
1898}
1899
1900/* Wait until threading._shutdown completes, provided
1901 the threading module was imported in the first place.
1902 The shutdown routine will wait until all non-daemon
1903 "threading" threads have completed. */
1904static void
1905wait_for_thread_shutdown(void)
1906{
Nick Coghland6009512014-11-20 21:39:37 +10001907 _Py_IDENTIFIER(_shutdown);
1908 PyObject *result;
Eric Snow86b7afd2017-09-04 17:54:09 -06001909 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001910 if (threading == NULL) {
1911 /* threading not imported */
1912 PyErr_Clear();
1913 return;
1914 }
Eric Snow86b7afd2017-09-04 17:54:09 -06001915 Py_INCREF(threading);
Victor Stinner3466bde2016-09-05 18:16:01 -07001916 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001917 if (result == NULL) {
1918 PyErr_WriteUnraisable(threading);
1919 }
1920 else {
1921 Py_DECREF(result);
1922 }
1923 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001924}
1925
1926#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001927int Py_AtExit(void (*func)(void))
1928{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001929 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001930 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001931 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001932 return 0;
1933}
1934
1935static void
1936call_ll_exitfuncs(void)
1937{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001938 while (_PyRuntime.nexitfuncs > 0)
1939 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001940
1941 fflush(stdout);
1942 fflush(stderr);
1943}
1944
1945void
1946Py_Exit(int sts)
1947{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001948 if (Py_FinalizeEx() < 0) {
1949 sts = 120;
1950 }
Nick Coghland6009512014-11-20 21:39:37 +10001951
1952 exit(sts);
1953}
1954
1955static void
1956initsigs(void)
1957{
1958#ifdef SIGPIPE
1959 PyOS_setsig(SIGPIPE, SIG_IGN);
1960#endif
1961#ifdef SIGXFZ
1962 PyOS_setsig(SIGXFZ, SIG_IGN);
1963#endif
1964#ifdef SIGXFSZ
1965 PyOS_setsig(SIGXFSZ, SIG_IGN);
1966#endif
1967 PyOS_InitInterrupts(); /* May imply initsignal() */
1968 if (PyErr_Occurred()) {
1969 Py_FatalError("Py_Initialize: can't import signal");
1970 }
1971}
1972
1973
1974/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1975 *
1976 * All of the code in this function must only use async-signal-safe functions,
1977 * listed at `man 7 signal` or
1978 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1979 */
1980void
1981_Py_RestoreSignals(void)
1982{
1983#ifdef SIGPIPE
1984 PyOS_setsig(SIGPIPE, SIG_DFL);
1985#endif
1986#ifdef SIGXFZ
1987 PyOS_setsig(SIGXFZ, SIG_DFL);
1988#endif
1989#ifdef SIGXFSZ
1990 PyOS_setsig(SIGXFSZ, SIG_DFL);
1991#endif
1992}
1993
1994
1995/*
1996 * The file descriptor fd is considered ``interactive'' if either
1997 * a) isatty(fd) is TRUE, or
1998 * b) the -i flag was given, and the filename associated with
1999 * the descriptor is NULL or "<stdin>" or "???".
2000 */
2001int
2002Py_FdIsInteractive(FILE *fp, const char *filename)
2003{
2004 if (isatty((int)fileno(fp)))
2005 return 1;
2006 if (!Py_InteractiveFlag)
2007 return 0;
2008 return (filename == NULL) ||
2009 (strcmp(filename, "<stdin>") == 0) ||
2010 (strcmp(filename, "???") == 0);
2011}
2012
2013
Nick Coghland6009512014-11-20 21:39:37 +10002014/* Wrappers around sigaction() or signal(). */
2015
2016PyOS_sighandler_t
2017PyOS_getsig(int sig)
2018{
2019#ifdef HAVE_SIGACTION
2020 struct sigaction context;
2021 if (sigaction(sig, NULL, &context) == -1)
2022 return SIG_ERR;
2023 return context.sa_handler;
2024#else
2025 PyOS_sighandler_t handler;
2026/* Special signal handling for the secure CRT in Visual Studio 2005 */
2027#if defined(_MSC_VER) && _MSC_VER >= 1400
2028 switch (sig) {
2029 /* Only these signals are valid */
2030 case SIGINT:
2031 case SIGILL:
2032 case SIGFPE:
2033 case SIGSEGV:
2034 case SIGTERM:
2035 case SIGBREAK:
2036 case SIGABRT:
2037 break;
2038 /* Don't call signal() with other values or it will assert */
2039 default:
2040 return SIG_ERR;
2041 }
2042#endif /* _MSC_VER && _MSC_VER >= 1400 */
2043 handler = signal(sig, SIG_IGN);
2044 if (handler != SIG_ERR)
2045 signal(sig, handler);
2046 return handler;
2047#endif
2048}
2049
2050/*
2051 * All of the code in this function must only use async-signal-safe functions,
2052 * listed at `man 7 signal` or
2053 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2054 */
2055PyOS_sighandler_t
2056PyOS_setsig(int sig, PyOS_sighandler_t handler)
2057{
2058#ifdef HAVE_SIGACTION
2059 /* Some code in Modules/signalmodule.c depends on sigaction() being
2060 * used here if HAVE_SIGACTION is defined. Fix that if this code
2061 * changes to invalidate that assumption.
2062 */
2063 struct sigaction context, ocontext;
2064 context.sa_handler = handler;
2065 sigemptyset(&context.sa_mask);
2066 context.sa_flags = 0;
2067 if (sigaction(sig, &context, &ocontext) == -1)
2068 return SIG_ERR;
2069 return ocontext.sa_handler;
2070#else
2071 PyOS_sighandler_t oldhandler;
2072 oldhandler = signal(sig, handler);
2073#ifdef HAVE_SIGINTERRUPT
2074 siginterrupt(sig, 1);
2075#endif
2076 return oldhandler;
2077#endif
2078}
2079
2080#ifdef __cplusplus
2081}
2082#endif