blob: 5c8cf5b9bd5fc07f2ef6d942807379931cda9c28 [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);
45
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50extern wchar_t *Py_GetPath(void);
51
52extern grammar _PyParser_Grammar; /* From graminit.c */
53
54/* Forward */
55static void initmain(PyInterpreterState *interp);
56static int initfsencoding(PyInterpreterState *interp);
57static void initsite(void);
58static int initstdio(void);
59static void initsigs(void);
60static void call_py_exitfuncs(void);
61static void wait_for_thread_shutdown(void);
62static void call_ll_exitfuncs(void);
63extern int _PyUnicode_Init(void);
64extern int _PyStructSequence_Init(void);
65extern void _PyUnicode_Fini(void);
66extern int _PyLong_Init(void);
67extern void PyLong_Fini(void);
68extern int _PyFaulthandler_Init(void);
69extern void _PyFaulthandler_Fini(void);
70extern void _PyHash_Fini(void);
71extern int _PyTraceMalloc_Init(void);
72extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070073extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100074
Nick Coghland6009512014-11-20 21:39:37 +100075extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100077
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078_PyRuntimeState _PyRuntime = {0, 0};
79
80void
81_PyRuntime_Initialize(void)
82{
83 /* XXX We only initialize once in the process, which aligns with
84 the static initialization of the former globals now found in
85 _PyRuntime. However, _PyRuntime *should* be initialized with
86 every Py_Initialize() call, but doing so breaks the runtime.
87 This is because the runtime state is not properly finalized
88 currently. */
89 static int initialized = 0;
90 if (initialized)
91 return;
92 initialized = 1;
93 _PyRuntimeState_Init(&_PyRuntime);
94}
95
96void
97_PyRuntime_Finalize(void)
98{
99 _PyRuntimeState_Fini(&_PyRuntime);
100}
101
102int
103_Py_IsFinalizing(void)
104{
105 return _PyRuntime.finalizing != NULL;
106}
107
Nick Coghland6009512014-11-20 21:39:37 +1000108/* Global configuration variable declarations are in pydebug.h */
109/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
110int Py_DebugFlag; /* Needed by parser.c */
111int Py_VerboseFlag; /* Needed by import.c */
112int Py_QuietFlag; /* Needed by sysmodule.c */
113int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
114int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
115int Py_OptimizeFlag = 0; /* Needed by compile.c */
116int Py_NoSiteFlag; /* Suppress 'import site' */
117int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
118int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
119int Py_FrozenFlag; /* Needed by getpath.c */
120int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000122int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
123int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
124int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
125int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700126#ifdef MS_WINDOWS
127int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700128int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700129#endif
Nick Coghland6009512014-11-20 21:39:37 +1000130
Nick Coghland6009512014-11-20 21:39:37 +1000131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
139{
140 return PyImport_ImportModule("warnings");
141}
142
Eric Snowc7ec9982017-05-23 23:00:52 -0700143
Eric Snow1abcf672017-05-23 21:46:51 -0700144/* APIs to access the initialization flags
145 *
146 * Can be called prior to Py_Initialize.
147 */
Nick Coghland6009512014-11-20 21:39:37 +1000148
Eric Snow1abcf672017-05-23 21:46:51 -0700149int
150_Py_IsCoreInitialized(void)
151{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600152 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700153}
Nick Coghland6009512014-11-20 21:39:37 +1000154
155int
156Py_IsInitialized(void)
157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000159}
160
161/* Helper to allow an embedding application to override the normal
162 * mechanism that attempts to figure out an appropriate IO encoding
163 */
164
165static char *_Py_StandardStreamEncoding = NULL;
166static char *_Py_StandardStreamErrors = NULL;
167
168int
169Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
170{
171 if (Py_IsInitialized()) {
172 /* This is too late to have any effect */
173 return -1;
174 }
175 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
176 * initialised yet.
177 *
178 * However, the raw memory allocators are initialised appropriately
179 * as C static variables, so _PyMem_RawStrdup is OK even though
180 * Py_Initialize hasn't been called yet.
181 */
182 if (encoding) {
183 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
184 if (!_Py_StandardStreamEncoding) {
185 return -2;
186 }
187 }
188 if (errors) {
189 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
190 if (!_Py_StandardStreamErrors) {
191 if (_Py_StandardStreamEncoding) {
192 PyMem_RawFree(_Py_StandardStreamEncoding);
193 }
194 return -3;
195 }
196 }
Steve Dower39294992016-08-30 21:22:36 -0700197#ifdef MS_WINDOWS
198 if (_Py_StandardStreamEncoding) {
199 /* Overriding the stream encoding implies legacy streams */
200 Py_LegacyWindowsStdioFlag = 1;
201 }
202#endif
Nick Coghland6009512014-11-20 21:39:37 +1000203 return 0;
204}
205
Nick Coghlan6ea41862017-06-11 13:16:15 +1000206
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000207/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
208 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000209 initializations fail, a fatal error is issued and the function does
210 not return. On return, the first thread and interpreter state have
211 been created.
212
213 Locking: you must hold the interpreter lock while calling this.
214 (If the lock has not yet been initialized, that's equivalent to
215 having the lock, but you cannot use multiple threads.)
216
217*/
218
219static int
220add_flag(int flag, const char *envs)
221{
222 int env = atoi(envs);
223 if (flag < env)
224 flag = env;
225 if (flag < 1)
226 flag = 1;
227 return flag;
228}
229
230static char*
231get_codec_name(const char *encoding)
232{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200233 const char *name_utf8;
234 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000235 PyObject *codec, *name = NULL;
236
237 codec = _PyCodec_Lookup(encoding);
238 if (!codec)
239 goto error;
240
241 name = _PyObject_GetAttrId(codec, &PyId_name);
242 Py_CLEAR(codec);
243 if (!name)
244 goto error;
245
Serhiy Storchaka06515832016-11-20 09:13:07 +0200246 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000247 if (name_utf8 == NULL)
248 goto error;
249 name_str = _PyMem_RawStrdup(name_utf8);
250 Py_DECREF(name);
251 if (name_str == NULL) {
252 PyErr_NoMemory();
253 return NULL;
254 }
255 return name_str;
256
257error:
258 Py_XDECREF(codec);
259 Py_XDECREF(name);
260 return NULL;
261}
262
263static char*
264get_locale_encoding(void)
265{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700266#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000267 char* codeset = nl_langinfo(CODESET);
268 if (!codeset || codeset[0] == '\0') {
269 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
270 return NULL;
271 }
272 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200273#elif defined(__ANDROID__)
274 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000275#else
276 PyErr_SetNone(PyExc_NotImplementedError);
277 return NULL;
278#endif
279}
280
281static void
Eric Snow1abcf672017-05-23 21:46:51 -0700282initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000283{
284 PyObject *importlib;
285 PyObject *impmod;
Eric Snow93c92f72017-09-13 23:46:04 -0700286 PyObject *sys_modules;
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 Snow93c92f72017-09-13 23:46:04 -0700317 sys_modules = PyImport_GetModuleDict();
318 if (Py_VerboseFlag) {
319 PySys_FormatStderr("import sys # builtin\n");
320 }
321 if (PyDict_SetItemString(sys_modules, "_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 Snowd393c1b2017-09-14 12:18:12 -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");
Eric Snowd393c1b2017-09-14 12:18:12 -0600681 interp->modules = modules;
682
683 sysmod = _PySys_BeginInit();
684 if (sysmod == NULL)
685 Py_FatalError("Py_InitializeCore: can't initialize sys");
686 interp->sysdict = PyModule_GetDict(sysmod);
687 if (interp->sysdict == NULL)
688 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
689 Py_INCREF(interp->sysdict);
690 PyDict_SetItemString(interp->sysdict, "modules", modules);
691 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000692
693 /* Init Unicode implementation; relies on the codec registry */
694 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700695 Py_FatalError("Py_InitializeCore: can't initialize unicode");
696
Nick Coghland6009512014-11-20 21:39:37 +1000697 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700698 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000699
700 bimod = _PyBuiltin_Init();
701 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700702 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600703 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000704 interp->builtins = PyModule_GetDict(bimod);
705 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700706 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000707 Py_INCREF(interp->builtins);
708
709 /* initialize builtin exceptions */
710 _PyExc_Init(bimod);
711
Nick Coghland6009512014-11-20 21:39:37 +1000712 /* Set up a preliminary stderr printer until we have enough
713 infrastructure for the io module in place. */
714 pstderr = PyFile_NewStdPrinter(fileno(stderr));
715 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700716 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000717 _PySys_SetObjectId(&PyId_stderr, pstderr);
718 PySys_SetObject("__stderr__", pstderr);
719 Py_DECREF(pstderr);
720
721 _PyImport_Init();
722
723 _PyImportHooks_Init();
724
725 /* Initialize _warnings. */
726 _PyWarnings_Init();
727
Eric Snow1abcf672017-05-23 21:46:51 -0700728 /* This call sets up builtin and frozen import support */
729 if (!interp->core_config._disable_importlib) {
730 initimport(interp, sysmod);
731 }
732
733 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600734 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700735}
736
Eric Snowc7ec9982017-05-23 23:00:52 -0700737/* Read configuration settings from standard locations
738 *
739 * This function doesn't make any changes to the interpreter state - it
740 * merely populates any missing configuration settings. This allows an
741 * embedding application to completely override a config option by
742 * setting it before calling this function, or else modify the default
743 * setting before passing the fully populated config to Py_EndInitialization.
744 *
745 * More advanced selective initialization tricks are possible by calling
746 * this function multiple times with various preconfigured settings.
747 */
748
749int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
750{
751 /* Signal handlers are installed by default */
752 if (config->install_signal_handlers < 0) {
753 config->install_signal_handlers = 1;
754 }
755
756 return 0;
757}
758
759/* Update interpreter state based on supplied configuration settings
760 *
761 * After calling this function, most of the restrictions on the interpreter
762 * are lifted. The only remaining incomplete settings are those related
763 * to the main module (sys.argv[0], __main__ metadata)
764 *
765 * Calling this when the interpreter is not initializing, is already
766 * initialized or without a valid current thread state is a fatal error.
767 * Other errors should be reported as normal Python exceptions with a
768 * non-zero return code.
769 */
770int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700771{
772 PyInterpreterState *interp;
773 PyThreadState *tstate;
774
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600775 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700776 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
777 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600778 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700779 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
780 }
781
Eric Snow1abcf672017-05-23 21:46:51 -0700782 /* Get current thread state and interpreter pointer */
783 tstate = PyThreadState_GET();
784 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700785 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700786 interp = tstate->interp;
787 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700788 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700789
790 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700791 interp->config = *config;
792
Eric Snow1abcf672017-05-23 21:46:51 -0700793 if (interp->core_config._disable_importlib) {
794 /* Special mode for freeze_importlib: run with no import system
795 *
796 * This means anything which needs support from extension modules
797 * or pure Python code in the standard library won't work.
798 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700800 return 0;
801 }
802 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000803
Victor Stinner13019fd2015-04-03 13:10:54 +0200804 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700805 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200806
Eric Snow1abcf672017-05-23 21:46:51 -0700807 /* Finish setting up the sys module and import system */
808 /* GetPath may initialize state that _PySys_EndInit locks
809 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700810 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700811 PySys_SetPath(Py_GetPath());
812 if (_PySys_EndInit(interp->sysdict) < 0)
813 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700814 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000815
816 /* initialize the faulthandler module */
817 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700818 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000819
Nick Coghland6009512014-11-20 21:39:37 +1000820 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700821 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000822
Eric Snowc7ec9982017-05-23 23:00:52 -0700823 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000824 initsigs(); /* Signal handling stuff, including initintr() */
825
826 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700827 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000828
829 initmain(interp); /* Module __main__ */
830 if (initstdio() < 0)
831 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000833
834 /* Initialize warnings. */
835 if (PySys_HasWarnOptions()) {
836 PyObject *warnings_module = PyImport_ImportModule("warnings");
837 if (warnings_module == NULL) {
838 fprintf(stderr, "'import warnings' failed; traceback:\n");
839 PyErr_Print();
840 }
841 Py_XDECREF(warnings_module);
842 }
843
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600844 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700845
Nick Coghland6009512014-11-20 21:39:37 +1000846 if (!Py_NoSiteFlag)
847 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700848
Eric Snowc7ec9982017-05-23 23:00:52 -0700849 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000850}
851
Eric Snowc7ec9982017-05-23 23:00:52 -0700852#undef _INIT_DEBUG_PRINT
853
Nick Coghland6009512014-11-20 21:39:37 +1000854void
Eric Snow1abcf672017-05-23 21:46:51 -0700855_Py_InitializeEx_Private(int install_sigs, int install_importlib)
856{
857 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700858 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700859
860 /* TODO: Moar config options! */
861 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
862 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700863 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700864 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700865 /* TODO: Print any exceptions raised by these operations */
866 if (_Py_ReadMainInterpreterConfig(&config))
867 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
868 if (_Py_InitializeMainInterpreter(&config))
869 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700870}
871
872
873void
Nick Coghland6009512014-11-20 21:39:37 +1000874Py_InitializeEx(int install_sigs)
875{
876 _Py_InitializeEx_Private(install_sigs, 1);
877}
878
879void
880Py_Initialize(void)
881{
882 Py_InitializeEx(1);
883}
884
885
886#ifdef COUNT_ALLOCS
887extern void dump_counts(FILE*);
888#endif
889
890/* Flush stdout and stderr */
891
892static int
893file_is_closed(PyObject *fobj)
894{
895 int r;
896 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
897 if (tmp == NULL) {
898 PyErr_Clear();
899 return 0;
900 }
901 r = PyObject_IsTrue(tmp);
902 Py_DECREF(tmp);
903 if (r < 0)
904 PyErr_Clear();
905 return r > 0;
906}
907
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000908static int
Nick Coghland6009512014-11-20 21:39:37 +1000909flush_std_files(void)
910{
911 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
912 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
913 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000914 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000915
916 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700917 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000918 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000919 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000920 status = -1;
921 }
Nick Coghland6009512014-11-20 21:39:37 +1000922 else
923 Py_DECREF(tmp);
924 }
925
926 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700927 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000928 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000929 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000930 status = -1;
931 }
Nick Coghland6009512014-11-20 21:39:37 +1000932 else
933 Py_DECREF(tmp);
934 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000935
936 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000937}
938
939/* Undo the effect of Py_Initialize().
940
941 Beware: if multiple interpreter and/or thread states exist, these
942 are not wiped out; only the current thread and interpreter state
943 are deleted. But since everything else is deleted, those other
944 interpreter and thread states should no longer be used.
945
946 (XXX We should do better, e.g. wipe out all interpreters and
947 threads.)
948
949 Locking: as above.
950
951*/
952
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000953int
954Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000955{
956 PyInterpreterState *interp;
957 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000958 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000959
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600960 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000961 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000962
963 wait_for_thread_shutdown();
964
965 /* The interpreter is still entirely intact at this point, and the
966 * exit funcs may be relying on that. In particular, if some thread
967 * or exit func is still waiting to do an import, the import machinery
968 * expects Py_IsInitialized() to return true. So don't say the
969 * interpreter is uninitialized until after the exit funcs have run.
970 * Note that Threading.py uses an exit func to do a join on all the
971 * threads created thru it, so this also protects pending imports in
972 * the threads created via Threading.
973 */
974 call_py_exitfuncs();
975
976 /* Get current thread state and interpreter pointer */
977 tstate = PyThreadState_GET();
978 interp = tstate->interp;
979
980 /* Remaining threads (e.g. daemon threads) will automatically exit
981 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600982 _PyRuntime.finalizing = tstate;
983 _PyRuntime.initialized = 0;
984 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000985
Victor Stinnere0deff32015-03-24 13:46:18 +0100986 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000987 if (flush_std_files() < 0) {
988 status = -1;
989 }
Nick Coghland6009512014-11-20 21:39:37 +1000990
991 /* Disable signal handling */
992 PyOS_FiniInterrupts();
993
994 /* Collect garbage. This may call finalizers; it's nice to call these
995 * before all modules are destroyed.
996 * XXX If a __del__ or weakref callback is triggered here, and tries to
997 * XXX import a module, bad things can happen, because Python no
998 * XXX longer believes it's initialized.
999 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1000 * XXX is easy to provoke that way. I've also seen, e.g.,
1001 * XXX Exception exceptions.ImportError: 'No module named sha'
1002 * XXX in <function callback at 0x008F5718> ignored
1003 * XXX but I'm unclear on exactly how that one happens. In any case,
1004 * XXX I haven't seen a real-life report of either of these.
1005 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001006 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001007#ifdef COUNT_ALLOCS
1008 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1009 each collection might release some types from the type
1010 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001011 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001012 /* nothing */;
1013#endif
Eric Snowdae02762017-09-14 00:35:58 -07001014
1015#ifdef Py_REF_DEBUG
1016 PyObject *showrefcount = _PyDebug_XOptionShowRefCount();
1017#endif
1018
Nick Coghland6009512014-11-20 21:39:37 +10001019 /* Destroy all modules */
1020 PyImport_Cleanup();
1021
Victor Stinnere0deff32015-03-24 13:46:18 +01001022 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001023 if (flush_std_files() < 0) {
1024 status = -1;
1025 }
Nick Coghland6009512014-11-20 21:39:37 +10001026
1027 /* Collect final garbage. This disposes of cycles created by
1028 * class definitions, for example.
1029 * XXX This is disabled because it caused too many problems. If
1030 * XXX a __del__ or weakref callback triggers here, Python code has
1031 * XXX a hard time running, because even the sys module has been
1032 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1033 * XXX One symptom is a sequence of information-free messages
1034 * XXX coming from threads (if a __del__ or callback is invoked,
1035 * XXX other threads can execute too, and any exception they encounter
1036 * XXX triggers a comedy of errors as subsystem after subsystem
1037 * XXX fails to find what it *expects* to find in sys to help report
1038 * XXX the exception and consequent unexpected failures). I've also
1039 * XXX seen segfaults then, after adding print statements to the
1040 * XXX Python code getting called.
1041 */
1042#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001043 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001044#endif
1045
1046 /* Disable tracemalloc after all Python objects have been destroyed,
1047 so it is possible to use tracemalloc in objects destructor. */
1048 _PyTraceMalloc_Fini();
1049
1050 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1051 _PyImport_Fini();
1052
1053 /* Cleanup typeobject.c's internal caches. */
1054 _PyType_Fini();
1055
1056 /* unload faulthandler module */
1057 _PyFaulthandler_Fini();
1058
1059 /* Debugging stuff */
1060#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001061 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001062#endif
1063 /* dump hash stats */
1064 _PyHash_Fini();
1065
Eric Snowdae02762017-09-14 00:35:58 -07001066#ifdef Py_REF_DEBUG
1067 if (showrefcount == Py_True)
1068 _PyDebug_PrintTotalRefs();
1069#endif
Nick Coghland6009512014-11-20 21:39:37 +10001070
1071#ifdef Py_TRACE_REFS
1072 /* Display all objects still alive -- this can invoke arbitrary
1073 * __repr__ overrides, so requires a mostly-intact interpreter.
1074 * Alas, a lot of stuff may still be alive now that will be cleaned
1075 * up later.
1076 */
1077 if (Py_GETENV("PYTHONDUMPREFS"))
1078 _Py_PrintReferences(stderr);
1079#endif /* Py_TRACE_REFS */
1080
1081 /* Clear interpreter state and all thread states. */
1082 PyInterpreterState_Clear(interp);
1083
1084 /* Now we decref the exception classes. After this point nothing
1085 can raise an exception. That's okay, because each Fini() method
1086 below has been checked to make sure no exceptions are ever
1087 raised.
1088 */
1089
1090 _PyExc_Fini();
1091
1092 /* Sundry finalizers */
1093 PyMethod_Fini();
1094 PyFrame_Fini();
1095 PyCFunction_Fini();
1096 PyTuple_Fini();
1097 PyList_Fini();
1098 PySet_Fini();
1099 PyBytes_Fini();
1100 PyByteArray_Fini();
1101 PyLong_Fini();
1102 PyFloat_Fini();
1103 PyDict_Fini();
1104 PySlice_Fini();
1105 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001106 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001107 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001108 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001109
1110 /* Cleanup Unicode implementation */
1111 _PyUnicode_Fini();
1112
1113 /* reset file system default encoding */
1114 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1115 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1116 Py_FileSystemDefaultEncoding = NULL;
1117 }
1118
1119 /* XXX Still allocated:
1120 - various static ad-hoc pointers to interned strings
1121 - int and float free list blocks
1122 - whatever various modules and libraries allocate
1123 */
1124
1125 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1126
1127 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001128 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001129
1130 /* Delete current thread. After this, many C API calls become crashy. */
1131 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001132
Nick Coghland6009512014-11-20 21:39:37 +10001133 PyInterpreterState_Delete(interp);
1134
1135#ifdef Py_TRACE_REFS
1136 /* Display addresses (& refcnts) of all objects still alive.
1137 * An address can be used to find the repr of the object, printed
1138 * above by _Py_PrintReferences.
1139 */
1140 if (Py_GETENV("PYTHONDUMPREFS"))
1141 _Py_PrintReferenceAddresses(stderr);
1142#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001143#ifdef WITH_PYMALLOC
1144 if (_PyMem_PymallocEnabled()) {
1145 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1146 if (opt != NULL && *opt != '\0')
1147 _PyObject_DebugMallocStats(stderr);
1148 }
Nick Coghland6009512014-11-20 21:39:37 +10001149#endif
1150
1151 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001152 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001153 return status;
1154}
1155
1156void
1157Py_Finalize(void)
1158{
1159 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001160}
1161
1162/* Create and initialize a new interpreter and thread, and return the
1163 new thread. This requires that Py_Initialize() has been called
1164 first.
1165
1166 Unsuccessful initialization yields a NULL pointer. Note that *no*
1167 exception information is available even in this case -- the
1168 exception information is held in the thread, and there is no
1169 thread.
1170
1171 Locking: as above.
1172
1173*/
1174
1175PyThreadState *
1176Py_NewInterpreter(void)
1177{
1178 PyInterpreterState *interp;
1179 PyThreadState *tstate, *save_tstate;
1180 PyObject *bimod, *sysmod;
1181
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001182 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001183 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1184
Victor Stinner8a1be612016-03-14 22:07:55 +01001185 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1186 interpreters: disable PyGILState_Check(). */
1187 _PyGILState_check_enabled = 0;
1188
Nick Coghland6009512014-11-20 21:39:37 +10001189 interp = PyInterpreterState_New();
1190 if (interp == NULL)
1191 return NULL;
1192
1193 tstate = PyThreadState_New(interp);
1194 if (tstate == NULL) {
1195 PyInterpreterState_Delete(interp);
1196 return NULL;
1197 }
1198
1199 save_tstate = PyThreadState_Swap(tstate);
1200
Eric Snow1abcf672017-05-23 21:46:51 -07001201 /* Copy the current interpreter config into the new interpreter */
1202 if (save_tstate != NULL) {
1203 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001204 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001205 } else {
1206 /* No current thread state, copy from the main interpreter */
1207 PyInterpreterState *main_interp = PyInterpreterState_Main();
1208 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001209 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001210 }
1211
Nick Coghland6009512014-11-20 21:39:37 +10001212 /* XXX The following is lax in error checking */
1213
Eric Snowd393c1b2017-09-14 12:18:12 -06001214 PyObject *modules = PyDict_New();
1215 if (modules == NULL)
1216 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
1217 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001218
Eric Snowd393c1b2017-09-14 12:18:12 -06001219 sysmod = _PyImport_FindBuiltin("sys", modules);
1220 if (sysmod != NULL) {
1221 interp->sysdict = PyModule_GetDict(sysmod);
1222 if (interp->sysdict == NULL)
1223 goto handle_error;
1224 Py_INCREF(interp->sysdict);
1225 PyDict_SetItemString(interp->sysdict, "modules", modules);
1226 PySys_SetPath(Py_GetPath());
1227 _PySys_EndInit(interp->sysdict);
1228 }
1229
1230 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001231 if (bimod != NULL) {
1232 interp->builtins = PyModule_GetDict(bimod);
1233 if (interp->builtins == NULL)
1234 goto handle_error;
1235 Py_INCREF(interp->builtins);
1236 }
1237
1238 /* initialize builtin exceptions */
1239 _PyExc_Init(bimod);
1240
Nick Coghland6009512014-11-20 21:39:37 +10001241 if (bimod != NULL && sysmod != NULL) {
1242 PyObject *pstderr;
1243
Nick Coghland6009512014-11-20 21:39:37 +10001244 /* Set up a preliminary stderr printer until we have enough
1245 infrastructure for the io module in place. */
1246 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1247 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001248 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001249 _PySys_SetObjectId(&PyId_stderr, pstderr);
1250 PySys_SetObject("__stderr__", pstderr);
1251 Py_DECREF(pstderr);
1252
1253 _PyImportHooks_Init();
1254
Eric Snow1abcf672017-05-23 21:46:51 -07001255 initimport(interp, sysmod);
1256 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001257
1258 if (initfsencoding(interp) < 0)
1259 goto handle_error;
1260
1261 if (initstdio() < 0)
1262 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001263 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001264 initmain(interp);
1265 if (!Py_NoSiteFlag)
1266 initsite();
1267 }
1268
1269 if (!PyErr_Occurred())
1270 return tstate;
1271
1272handle_error:
1273 /* Oops, it didn't work. Undo it all. */
1274
1275 PyErr_PrintEx(0);
1276 PyThreadState_Clear(tstate);
1277 PyThreadState_Swap(save_tstate);
1278 PyThreadState_Delete(tstate);
1279 PyInterpreterState_Delete(interp);
1280
1281 return NULL;
1282}
1283
1284/* Delete an interpreter and its last thread. This requires that the
1285 given thread state is current, that the thread has no remaining
1286 frames, and that it is its interpreter's only remaining thread.
1287 It is a fatal error to violate these constraints.
1288
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001289 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001290 everything, regardless.)
1291
1292 Locking: as above.
1293
1294*/
1295
1296void
1297Py_EndInterpreter(PyThreadState *tstate)
1298{
1299 PyInterpreterState *interp = tstate->interp;
1300
1301 if (tstate != PyThreadState_GET())
1302 Py_FatalError("Py_EndInterpreter: thread is not current");
1303 if (tstate->frame != NULL)
1304 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1305
1306 wait_for_thread_shutdown();
1307
1308 if (tstate != interp->tstate_head || tstate->next != NULL)
1309 Py_FatalError("Py_EndInterpreter: not the last thread");
1310
1311 PyImport_Cleanup();
1312 PyInterpreterState_Clear(interp);
1313 PyThreadState_Swap(NULL);
1314 PyInterpreterState_Delete(interp);
1315}
1316
1317#ifdef MS_WINDOWS
1318static wchar_t *progname = L"python";
1319#else
1320static wchar_t *progname = L"python3";
1321#endif
1322
1323void
1324Py_SetProgramName(wchar_t *pn)
1325{
1326 if (pn && *pn)
1327 progname = pn;
1328}
1329
1330wchar_t *
1331Py_GetProgramName(void)
1332{
1333 return progname;
1334}
1335
1336static wchar_t *default_home = NULL;
1337static wchar_t env_home[MAXPATHLEN+1];
1338
1339void
1340Py_SetPythonHome(wchar_t *home)
1341{
1342 default_home = home;
1343}
1344
1345wchar_t *
1346Py_GetPythonHome(void)
1347{
1348 wchar_t *home = default_home;
1349 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1350 char* chome = Py_GETENV("PYTHONHOME");
1351 if (chome) {
1352 size_t size = Py_ARRAY_LENGTH(env_home);
1353 size_t r = mbstowcs(env_home, chome, size);
1354 if (r != (size_t)-1 && r < size)
1355 home = env_home;
1356 }
1357
1358 }
1359 return home;
1360}
1361
1362/* Create __main__ module */
1363
1364static void
1365initmain(PyInterpreterState *interp)
1366{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001367 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001368 m = PyImport_AddModule("__main__");
1369 if (m == NULL)
1370 Py_FatalError("can't create __main__ module");
1371 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001372 ann_dict = PyDict_New();
1373 if ((ann_dict == NULL) ||
1374 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1375 Py_FatalError("Failed to initialize __main__.__annotations__");
1376 }
1377 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001378 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1379 PyObject *bimod = PyImport_ImportModule("builtins");
1380 if (bimod == NULL) {
1381 Py_FatalError("Failed to retrieve builtins module");
1382 }
1383 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1384 Py_FatalError("Failed to initialize __main__.__builtins__");
1385 }
1386 Py_DECREF(bimod);
1387 }
1388 /* Main is a little special - imp.is_builtin("__main__") will return
1389 * False, but BuiltinImporter is still the most appropriate initial
1390 * setting for its __loader__ attribute. A more suitable value will
1391 * be set if __main__ gets further initialized later in the startup
1392 * process.
1393 */
1394 loader = PyDict_GetItemString(d, "__loader__");
1395 if (loader == NULL || loader == Py_None) {
1396 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1397 "BuiltinImporter");
1398 if (loader == NULL) {
1399 Py_FatalError("Failed to retrieve BuiltinImporter");
1400 }
1401 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1402 Py_FatalError("Failed to initialize __main__.__loader__");
1403 }
1404 Py_DECREF(loader);
1405 }
1406}
1407
1408static int
1409initfsencoding(PyInterpreterState *interp)
1410{
1411 PyObject *codec;
1412
Steve Dowercc16be82016-09-08 10:35:16 -07001413#ifdef MS_WINDOWS
1414 if (Py_LegacyWindowsFSEncodingFlag)
1415 {
1416 Py_FileSystemDefaultEncoding = "mbcs";
1417 Py_FileSystemDefaultEncodeErrors = "replace";
1418 }
1419 else
1420 {
1421 Py_FileSystemDefaultEncoding = "utf-8";
1422 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1423 }
1424#else
Nick Coghland6009512014-11-20 21:39:37 +10001425 if (Py_FileSystemDefaultEncoding == NULL)
1426 {
1427 Py_FileSystemDefaultEncoding = get_locale_encoding();
1428 if (Py_FileSystemDefaultEncoding == NULL)
1429 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1430
1431 Py_HasFileSystemDefaultEncoding = 0;
1432 interp->fscodec_initialized = 1;
1433 return 0;
1434 }
Steve Dowercc16be82016-09-08 10:35:16 -07001435#endif
Nick Coghland6009512014-11-20 21:39:37 +10001436
1437 /* the encoding is mbcs, utf-8 or ascii */
1438 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1439 if (!codec) {
1440 /* Such error can only occurs in critical situations: no more
1441 * memory, import a module of the standard library failed,
1442 * etc. */
1443 return -1;
1444 }
1445 Py_DECREF(codec);
1446 interp->fscodec_initialized = 1;
1447 return 0;
1448}
1449
1450/* Import the site module (not into __main__ though) */
1451
1452static void
1453initsite(void)
1454{
1455 PyObject *m;
1456 m = PyImport_ImportModule("site");
1457 if (m == NULL) {
1458 fprintf(stderr, "Failed to import the site module\n");
1459 PyErr_Print();
1460 Py_Finalize();
1461 exit(1);
1462 }
1463 else {
1464 Py_DECREF(m);
1465 }
1466}
1467
Victor Stinner874dbe82015-09-04 17:29:57 +02001468/* Check if a file descriptor is valid or not.
1469 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1470static int
1471is_valid_fd(int fd)
1472{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001473#ifdef __APPLE__
1474 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1475 and the other side of the pipe is closed, dup(1) succeed, whereas
1476 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1477 such error. */
1478 struct stat st;
1479 return (fstat(fd, &st) == 0);
1480#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001481 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001482 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001483 return 0;
1484 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001485 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1486 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1487 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001488 fd2 = dup(fd);
1489 if (fd2 >= 0)
1490 close(fd2);
1491 _Py_END_SUPPRESS_IPH
1492 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001493#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001494}
1495
1496/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001497static PyObject*
1498create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001499 int fd, int write_mode, const char* name,
1500 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001501{
1502 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1503 const char* mode;
1504 const char* newline;
1505 PyObject *line_buffering;
1506 int buffering, isatty;
1507 _Py_IDENTIFIER(open);
1508 _Py_IDENTIFIER(isatty);
1509 _Py_IDENTIFIER(TextIOWrapper);
1510 _Py_IDENTIFIER(mode);
1511
Victor Stinner874dbe82015-09-04 17:29:57 +02001512 if (!is_valid_fd(fd))
1513 Py_RETURN_NONE;
1514
Nick Coghland6009512014-11-20 21:39:37 +10001515 /* stdin is always opened in buffered mode, first because it shouldn't
1516 make a difference in common use cases, second because TextIOWrapper
1517 depends on the presence of a read1() method which only exists on
1518 buffered streams.
1519 */
1520 if (Py_UnbufferedStdioFlag && write_mode)
1521 buffering = 0;
1522 else
1523 buffering = -1;
1524 if (write_mode)
1525 mode = "wb";
1526 else
1527 mode = "rb";
1528 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1529 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001530 Py_None, Py_None, /* encoding, errors */
1531 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001532 if (buf == NULL)
1533 goto error;
1534
1535 if (buffering) {
1536 _Py_IDENTIFIER(raw);
1537 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1538 if (raw == NULL)
1539 goto error;
1540 }
1541 else {
1542 raw = buf;
1543 Py_INCREF(raw);
1544 }
1545
Steve Dower39294992016-08-30 21:22:36 -07001546#ifdef MS_WINDOWS
1547 /* Windows console IO is always UTF-8 encoded */
1548 if (PyWindowsConsoleIO_Check(raw))
1549 encoding = "utf-8";
1550#endif
1551
Nick Coghland6009512014-11-20 21:39:37 +10001552 text = PyUnicode_FromString(name);
1553 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1554 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001555 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001556 if (res == NULL)
1557 goto error;
1558 isatty = PyObject_IsTrue(res);
1559 Py_DECREF(res);
1560 if (isatty == -1)
1561 goto error;
1562 if (isatty || Py_UnbufferedStdioFlag)
1563 line_buffering = Py_True;
1564 else
1565 line_buffering = Py_False;
1566
1567 Py_CLEAR(raw);
1568 Py_CLEAR(text);
1569
1570#ifdef MS_WINDOWS
1571 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1572 newlines to "\n".
1573 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1574 newline = NULL;
1575#else
1576 /* sys.stdin: split lines at "\n".
1577 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1578 newline = "\n";
1579#endif
1580
1581 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1582 buf, encoding, errors,
1583 newline, line_buffering);
1584 Py_CLEAR(buf);
1585 if (stream == NULL)
1586 goto error;
1587
1588 if (write_mode)
1589 mode = "w";
1590 else
1591 mode = "r";
1592 text = PyUnicode_FromString(mode);
1593 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1594 goto error;
1595 Py_CLEAR(text);
1596 return stream;
1597
1598error:
1599 Py_XDECREF(buf);
1600 Py_XDECREF(stream);
1601 Py_XDECREF(text);
1602 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001603
Victor Stinner874dbe82015-09-04 17:29:57 +02001604 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1605 /* Issue #24891: the file descriptor was closed after the first
1606 is_valid_fd() check was called. Ignore the OSError and set the
1607 stream to None. */
1608 PyErr_Clear();
1609 Py_RETURN_NONE;
1610 }
1611 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001612}
1613
1614/* Initialize sys.stdin, stdout, stderr and builtins.open */
1615static int
1616initstdio(void)
1617{
1618 PyObject *iomod = NULL, *wrapper;
1619 PyObject *bimod = NULL;
1620 PyObject *m;
1621 PyObject *std = NULL;
1622 int status = 0, fd;
1623 PyObject * encoding_attr;
1624 char *pythonioencoding = NULL, *encoding, *errors;
1625
1626 /* Hack to avoid a nasty recursion issue when Python is invoked
1627 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1628 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1629 goto error;
1630 }
1631 Py_DECREF(m);
1632
1633 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1634 goto error;
1635 }
1636 Py_DECREF(m);
1637
1638 if (!(bimod = PyImport_ImportModule("builtins"))) {
1639 goto error;
1640 }
1641
1642 if (!(iomod = PyImport_ImportModule("io"))) {
1643 goto error;
1644 }
1645 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1646 goto error;
1647 }
1648
1649 /* Set builtins.open */
1650 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1651 Py_DECREF(wrapper);
1652 goto error;
1653 }
1654 Py_DECREF(wrapper);
1655
1656 encoding = _Py_StandardStreamEncoding;
1657 errors = _Py_StandardStreamErrors;
1658 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001659 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1660 if (pythonioencoding) {
1661 char *err;
1662 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1663 if (pythonioencoding == NULL) {
1664 PyErr_NoMemory();
1665 goto error;
1666 }
1667 err = strchr(pythonioencoding, ':');
1668 if (err) {
1669 *err = '\0';
1670 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001671 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001672 errors = err;
1673 }
1674 }
1675 if (*pythonioencoding && !encoding) {
1676 encoding = pythonioencoding;
1677 }
1678 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001679 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001680 /* Choose the default error handler based on the current locale */
1681 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001682 }
Nick Coghland6009512014-11-20 21:39:37 +10001683 }
1684
1685 /* Set sys.stdin */
1686 fd = fileno(stdin);
1687 /* Under some conditions stdin, stdout and stderr may not be connected
1688 * and fileno() may point to an invalid file descriptor. For example
1689 * GUI apps don't have valid standard streams by default.
1690 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001691 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1692 if (std == NULL)
1693 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001694 PySys_SetObject("__stdin__", std);
1695 _PySys_SetObjectId(&PyId_stdin, std);
1696 Py_DECREF(std);
1697
1698 /* Set sys.stdout */
1699 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001700 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1701 if (std == NULL)
1702 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001703 PySys_SetObject("__stdout__", std);
1704 _PySys_SetObjectId(&PyId_stdout, std);
1705 Py_DECREF(std);
1706
1707#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1708 /* Set sys.stderr, replaces the preliminary stderr */
1709 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001710 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1711 if (std == NULL)
1712 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001713
1714 /* Same as hack above, pre-import stderr's codec to avoid recursion
1715 when import.c tries to write to stderr in verbose mode. */
1716 encoding_attr = PyObject_GetAttrString(std, "encoding");
1717 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001718 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001719 if (std_encoding != NULL) {
1720 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1721 Py_XDECREF(codec_info);
1722 }
1723 Py_DECREF(encoding_attr);
1724 }
1725 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1726
1727 if (PySys_SetObject("__stderr__", std) < 0) {
1728 Py_DECREF(std);
1729 goto error;
1730 }
1731 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1732 Py_DECREF(std);
1733 goto error;
1734 }
1735 Py_DECREF(std);
1736#endif
1737
1738 if (0) {
1739 error:
1740 status = -1;
1741 }
1742
1743 /* We won't need them anymore. */
1744 if (_Py_StandardStreamEncoding) {
1745 PyMem_RawFree(_Py_StandardStreamEncoding);
1746 _Py_StandardStreamEncoding = NULL;
1747 }
1748 if (_Py_StandardStreamErrors) {
1749 PyMem_RawFree(_Py_StandardStreamErrors);
1750 _Py_StandardStreamErrors = NULL;
1751 }
1752 PyMem_Free(pythonioencoding);
1753 Py_XDECREF(bimod);
1754 Py_XDECREF(iomod);
1755 return status;
1756}
1757
1758
Victor Stinner10dc4842015-03-24 12:01:30 +01001759static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001760_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001761{
Victor Stinner10dc4842015-03-24 12:01:30 +01001762 fputc('\n', stderr);
1763 fflush(stderr);
1764
1765 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001766 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001767}
Victor Stinner791da1c2016-03-14 16:53:12 +01001768
1769/* Print the current exception (if an exception is set) with its traceback,
1770 or display the current Python stack.
1771
1772 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1773 called on catastrophic cases.
1774
1775 Return 1 if the traceback was displayed, 0 otherwise. */
1776
1777static int
1778_Py_FatalError_PrintExc(int fd)
1779{
1780 PyObject *ferr, *res;
1781 PyObject *exception, *v, *tb;
1782 int has_tb;
1783
1784 if (PyThreadState_GET() == NULL) {
1785 /* The GIL is released: trying to acquire it is likely to deadlock,
1786 just give up. */
1787 return 0;
1788 }
1789
1790 PyErr_Fetch(&exception, &v, &tb);
1791 if (exception == NULL) {
1792 /* No current exception */
1793 return 0;
1794 }
1795
1796 ferr = _PySys_GetObjectId(&PyId_stderr);
1797 if (ferr == NULL || ferr == Py_None) {
1798 /* sys.stderr is not set yet or set to None,
1799 no need to try to display the exception */
1800 return 0;
1801 }
1802
1803 PyErr_NormalizeException(&exception, &v, &tb);
1804 if (tb == NULL) {
1805 tb = Py_None;
1806 Py_INCREF(tb);
1807 }
1808 PyException_SetTraceback(v, tb);
1809 if (exception == NULL) {
1810 /* PyErr_NormalizeException() failed */
1811 return 0;
1812 }
1813
1814 has_tb = (tb != Py_None);
1815 PyErr_Display(exception, v, tb);
1816 Py_XDECREF(exception);
1817 Py_XDECREF(v);
1818 Py_XDECREF(tb);
1819
1820 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001821 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001822 if (res == NULL)
1823 PyErr_Clear();
1824 else
1825 Py_DECREF(res);
1826
1827 return has_tb;
1828}
1829
Nick Coghland6009512014-11-20 21:39:37 +10001830/* Print fatal error message and abort */
1831
1832void
1833Py_FatalError(const char *msg)
1834{
1835 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001836 static int reentrant = 0;
1837#ifdef MS_WINDOWS
1838 size_t len;
1839 WCHAR* buffer;
1840 size_t i;
1841#endif
1842
1843 if (reentrant) {
1844 /* Py_FatalError() caused a second fatal error.
1845 Example: flush_std_files() raises a recursion error. */
1846 goto exit;
1847 }
1848 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001849
1850 fprintf(stderr, "Fatal Python error: %s\n", msg);
1851 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001852
Victor Stinnere0deff32015-03-24 13:46:18 +01001853 /* Print the exception (if an exception is set) with its traceback,
1854 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001855 if (!_Py_FatalError_PrintExc(fd))
1856 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001857
Victor Stinner2025d782016-03-16 23:19:15 +01001858 /* The main purpose of faulthandler is to display the traceback. We already
1859 * did our best to display it. So faulthandler can now be disabled.
1860 * (Don't trigger it on abort().) */
1861 _PyFaulthandler_Fini();
1862
Victor Stinner791da1c2016-03-14 16:53:12 +01001863 /* Check if the current Python thread hold the GIL */
1864 if (PyThreadState_GET() != NULL) {
1865 /* Flush sys.stdout and sys.stderr */
1866 flush_std_files();
1867 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001868
Nick Coghland6009512014-11-20 21:39:37 +10001869#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001870 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001871
Victor Stinner53345a42015-03-25 01:55:14 +01001872 /* Convert the message to wchar_t. This uses a simple one-to-one
1873 conversion, assuming that the this error message actually uses ASCII
1874 only. If this ceases to be true, we will have to convert. */
1875 buffer = alloca( (len+1) * (sizeof *buffer));
1876 for( i=0; i<=len; ++i)
1877 buffer[i] = msg[i];
1878 OutputDebugStringW(L"Fatal Python error: ");
1879 OutputDebugStringW(buffer);
1880 OutputDebugStringW(L"\n");
1881#endif /* MS_WINDOWS */
1882
1883exit:
1884#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001885 DebugBreak();
1886#endif
Nick Coghland6009512014-11-20 21:39:37 +10001887 abort();
1888}
1889
1890/* Clean up and exit */
1891
Victor Stinnerd7292b52016-06-17 12:29:00 +02001892# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001893
Nick Coghland6009512014-11-20 21:39:37 +10001894/* For the atexit module. */
1895void _Py_PyAtExit(void (*func)(void))
1896{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001897 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001898}
1899
1900static void
1901call_py_exitfuncs(void)
1902{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001903 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001904 return;
1905
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001906 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001907 PyErr_Clear();
1908}
1909
1910/* Wait until threading._shutdown completes, provided
1911 the threading module was imported in the first place.
1912 The shutdown routine will wait until all non-daemon
1913 "threading" threads have completed. */
1914static void
1915wait_for_thread_shutdown(void)
1916{
Nick Coghland6009512014-11-20 21:39:37 +10001917 _Py_IDENTIFIER(_shutdown);
1918 PyObject *result;
Eric Snowd393c1b2017-09-14 12:18:12 -06001919 PyObject *modules = PyImport_GetModuleDict();
1920 PyObject *threading = PyMapping_GetItemString(modules, "threading");
Nick Coghland6009512014-11-20 21:39:37 +10001921 if (threading == NULL) {
1922 /* threading not imported */
1923 PyErr_Clear();
1924 return;
1925 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001926 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001927 if (result == NULL) {
1928 PyErr_WriteUnraisable(threading);
1929 }
1930 else {
1931 Py_DECREF(result);
1932 }
1933 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001934}
1935
1936#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001937int Py_AtExit(void (*func)(void))
1938{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001939 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001940 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001941 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001942 return 0;
1943}
1944
1945static void
1946call_ll_exitfuncs(void)
1947{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001948 while (_PyRuntime.nexitfuncs > 0)
1949 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001950
1951 fflush(stdout);
1952 fflush(stderr);
1953}
1954
1955void
1956Py_Exit(int sts)
1957{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001958 if (Py_FinalizeEx() < 0) {
1959 sts = 120;
1960 }
Nick Coghland6009512014-11-20 21:39:37 +10001961
1962 exit(sts);
1963}
1964
1965static void
1966initsigs(void)
1967{
1968#ifdef SIGPIPE
1969 PyOS_setsig(SIGPIPE, SIG_IGN);
1970#endif
1971#ifdef SIGXFZ
1972 PyOS_setsig(SIGXFZ, SIG_IGN);
1973#endif
1974#ifdef SIGXFSZ
1975 PyOS_setsig(SIGXFSZ, SIG_IGN);
1976#endif
1977 PyOS_InitInterrupts(); /* May imply initsignal() */
1978 if (PyErr_Occurred()) {
1979 Py_FatalError("Py_Initialize: can't import signal");
1980 }
1981}
1982
1983
1984/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1985 *
1986 * All of the code in this function must only use async-signal-safe functions,
1987 * listed at `man 7 signal` or
1988 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1989 */
1990void
1991_Py_RestoreSignals(void)
1992{
1993#ifdef SIGPIPE
1994 PyOS_setsig(SIGPIPE, SIG_DFL);
1995#endif
1996#ifdef SIGXFZ
1997 PyOS_setsig(SIGXFZ, SIG_DFL);
1998#endif
1999#ifdef SIGXFSZ
2000 PyOS_setsig(SIGXFSZ, SIG_DFL);
2001#endif
2002}
2003
2004
2005/*
2006 * The file descriptor fd is considered ``interactive'' if either
2007 * a) isatty(fd) is TRUE, or
2008 * b) the -i flag was given, and the filename associated with
2009 * the descriptor is NULL or "<stdin>" or "???".
2010 */
2011int
2012Py_FdIsInteractive(FILE *fp, const char *filename)
2013{
2014 if (isatty((int)fileno(fp)))
2015 return 1;
2016 if (!Py_InteractiveFlag)
2017 return 0;
2018 return (filename == NULL) ||
2019 (strcmp(filename, "<stdin>") == 0) ||
2020 (strcmp(filename, "???") == 0);
2021}
2022
2023
Nick Coghland6009512014-11-20 21:39:37 +10002024/* Wrappers around sigaction() or signal(). */
2025
2026PyOS_sighandler_t
2027PyOS_getsig(int sig)
2028{
2029#ifdef HAVE_SIGACTION
2030 struct sigaction context;
2031 if (sigaction(sig, NULL, &context) == -1)
2032 return SIG_ERR;
2033 return context.sa_handler;
2034#else
2035 PyOS_sighandler_t handler;
2036/* Special signal handling for the secure CRT in Visual Studio 2005 */
2037#if defined(_MSC_VER) && _MSC_VER >= 1400
2038 switch (sig) {
2039 /* Only these signals are valid */
2040 case SIGINT:
2041 case SIGILL:
2042 case SIGFPE:
2043 case SIGSEGV:
2044 case SIGTERM:
2045 case SIGBREAK:
2046 case SIGABRT:
2047 break;
2048 /* Don't call signal() with other values or it will assert */
2049 default:
2050 return SIG_ERR;
2051 }
2052#endif /* _MSC_VER && _MSC_VER >= 1400 */
2053 handler = signal(sig, SIG_IGN);
2054 if (handler != SIG_ERR)
2055 signal(sig, handler);
2056 return handler;
2057#endif
2058}
2059
2060/*
2061 * All of the code in this function must only use async-signal-safe functions,
2062 * listed at `man 7 signal` or
2063 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2064 */
2065PyOS_sighandler_t
2066PyOS_setsig(int sig, PyOS_sighandler_t handler)
2067{
2068#ifdef HAVE_SIGACTION
2069 /* Some code in Modules/signalmodule.c depends on sigaction() being
2070 * used here if HAVE_SIGACTION is defined. Fix that if this code
2071 * changes to invalidate that assumption.
2072 */
2073 struct sigaction context, ocontext;
2074 context.sa_handler = handler;
2075 sigemptyset(&context.sa_mask);
2076 context.sa_flags = 0;
2077 if (sigaction(sig, &context, &ocontext) == -1)
2078 return SIG_ERR;
2079 return ocontext.sa_handler;
2080#else
2081 PyOS_sighandler_t oldhandler;
2082 oldhandler = signal(sig, handler);
2083#ifdef HAVE_SIGINTERRUPT
2084 siginterrupt(sig, 1);
2085#endif
2086 return oldhandler;
2087#endif
2088}
2089
2090#ifdef __cplusplus
2091}
2092#endif