blob: 7798dfe9c2cbbfad154a6ce2ed7146bf91eacdba [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 */
7#include "grammar.h"
8#include "node.h"
9#include "token.h"
10#include "parsetok.h"
11#include "errcode.h"
12#include "code.h"
13#include "symtable.h"
14#include "ast.h"
15#include "marshal.h"
16#include "osdefs.h"
17#include <locale.h>
18
19#ifdef HAVE_SIGNAL_H
20#include <signal.h>
21#endif
22
23#ifdef MS_WINDOWS
24#include "malloc.h" /* for alloca */
25#endif
26
27#ifdef HAVE_LANGINFO_H
28#include <langinfo.h>
29#endif
30
31#ifdef MS_WINDOWS
32#undef BYTE
33#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070034
35extern PyTypeObject PyWindowsConsoleIO_Type;
36#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100037#endif
38
39_Py_IDENTIFIER(flush);
40_Py_IDENTIFIER(name);
41_Py_IDENTIFIER(stdin);
42_Py_IDENTIFIER(stdout);
43_Py_IDENTIFIER(stderr);
Eric Snow86b7afd2017-09-04 17:54:09 -060044_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100045
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
78/* Global configuration variable declarations are in pydebug.h */
79/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
80int Py_DebugFlag; /* Needed by parser.c */
81int Py_VerboseFlag; /* Needed by import.c */
82int Py_QuietFlag; /* Needed by sysmodule.c */
83int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
84int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
85int Py_OptimizeFlag = 0; /* Needed by compile.c */
86int Py_NoSiteFlag; /* Suppress 'import site' */
87int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
88int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
89int Py_FrozenFlag; /* Needed by getpath.c */
90int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080091int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
93int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
94int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
95int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070096#ifdef MS_WINDOWS
97int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070098int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -070099#endif
Nick Coghland6009512014-11-20 21:39:37 +1000100
Eric Snow05351c12017-09-05 21:43:08 -0700101PyThreadState *_Py_Finalizing = NULL;
102
Nick Coghland6009512014-11-20 21:39:37 +1000103/* Hack to force loading of object files */
104int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
105 PyOS_mystrnicmp; /* Python/pystrcmp.o */
106
107/* PyModule_GetWarningsModule is no longer necessary as of 2.6
108since _warnings is builtin. This API should not be used. */
109PyObject *
110PyModule_GetWarningsModule(void)
111{
112 return PyImport_ImportModule("warnings");
113}
114
Eric Snowc7ec9982017-05-23 23:00:52 -0700115
Eric Snow1abcf672017-05-23 21:46:51 -0700116/* APIs to access the initialization flags
117 *
118 * Can be called prior to Py_Initialize.
119 */
Eric Snow05351c12017-09-05 21:43:08 -0700120int _Py_CoreInitialized = 0;
121int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000122
Eric Snow1abcf672017-05-23 21:46:51 -0700123int
124_Py_IsCoreInitialized(void)
125{
Eric Snow05351c12017-09-05 21:43:08 -0700126 return _Py_CoreInitialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700127}
Nick Coghland6009512014-11-20 21:39:37 +1000128
129int
130Py_IsInitialized(void)
131{
Eric Snow05351c12017-09-05 21:43:08 -0700132 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000133}
134
135/* Helper to allow an embedding application to override the normal
136 * mechanism that attempts to figure out an appropriate IO encoding
137 */
138
139static char *_Py_StandardStreamEncoding = NULL;
140static char *_Py_StandardStreamErrors = NULL;
141
142int
143Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
144{
145 if (Py_IsInitialized()) {
146 /* This is too late to have any effect */
147 return -1;
148 }
149 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
150 * initialised yet.
151 *
152 * However, the raw memory allocators are initialised appropriately
153 * as C static variables, so _PyMem_RawStrdup is OK even though
154 * Py_Initialize hasn't been called yet.
155 */
156 if (encoding) {
157 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
158 if (!_Py_StandardStreamEncoding) {
159 return -2;
160 }
161 }
162 if (errors) {
163 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
164 if (!_Py_StandardStreamErrors) {
165 if (_Py_StandardStreamEncoding) {
166 PyMem_RawFree(_Py_StandardStreamEncoding);
167 }
168 return -3;
169 }
170 }
Steve Dower39294992016-08-30 21:22:36 -0700171#ifdef MS_WINDOWS
172 if (_Py_StandardStreamEncoding) {
173 /* Overriding the stream encoding implies legacy streams */
174 Py_LegacyWindowsStdioFlag = 1;
175 }
176#endif
Nick Coghland6009512014-11-20 21:39:37 +1000177 return 0;
178}
179
Nick Coghlan6ea41862017-06-11 13:16:15 +1000180
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000181/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
182 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000183 initializations fail, a fatal error is issued and the function does
184 not return. On return, the first thread and interpreter state have
185 been created.
186
187 Locking: you must hold the interpreter lock while calling this.
188 (If the lock has not yet been initialized, that's equivalent to
189 having the lock, but you cannot use multiple threads.)
190
191*/
192
193static int
194add_flag(int flag, const char *envs)
195{
196 int env = atoi(envs);
197 if (flag < env)
198 flag = env;
199 if (flag < 1)
200 flag = 1;
201 return flag;
202}
203
204static char*
205get_codec_name(const char *encoding)
206{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200207 const char *name_utf8;
208 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000209 PyObject *codec, *name = NULL;
210
211 codec = _PyCodec_Lookup(encoding);
212 if (!codec)
213 goto error;
214
215 name = _PyObject_GetAttrId(codec, &PyId_name);
216 Py_CLEAR(codec);
217 if (!name)
218 goto error;
219
Serhiy Storchaka06515832016-11-20 09:13:07 +0200220 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000221 if (name_utf8 == NULL)
222 goto error;
223 name_str = _PyMem_RawStrdup(name_utf8);
224 Py_DECREF(name);
225 if (name_str == NULL) {
226 PyErr_NoMemory();
227 return NULL;
228 }
229 return name_str;
230
231error:
232 Py_XDECREF(codec);
233 Py_XDECREF(name);
234 return NULL;
235}
236
237static char*
238get_locale_encoding(void)
239{
240#ifdef MS_WINDOWS
241 char codepage[100];
242 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
243 return get_codec_name(codepage);
244#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
245 char* codeset = nl_langinfo(CODESET);
246 if (!codeset || codeset[0] == '\0') {
247 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
248 return NULL;
249 }
250 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200251#elif defined(__ANDROID__)
252 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000253#else
254 PyErr_SetNone(PyExc_NotImplementedError);
255 return NULL;
256#endif
257}
258
259static void
Eric Snow1abcf672017-05-23 21:46:51 -0700260initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000261{
262 PyObject *importlib;
263 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000264 PyObject *value;
265
266 /* Import _importlib through its frozen version, _frozen_importlib. */
267 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
268 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
269 }
270 else if (Py_VerboseFlag) {
271 PySys_FormatStderr("import _frozen_importlib # frozen\n");
272 }
273 importlib = PyImport_AddModule("_frozen_importlib");
274 if (importlib == NULL) {
275 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
276 "sys.modules");
277 }
278 interp->importlib = importlib;
279 Py_INCREF(interp->importlib);
280
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300281 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
282 if (interp->import_func == NULL)
283 Py_FatalError("Py_Initialize: __import__ not found");
284 Py_INCREF(interp->import_func);
285
Victor Stinnercd6e6942015-09-18 09:11:57 +0200286 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000287 impmod = PyInit_imp();
288 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200289 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000290 }
291 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200292 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000293 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600294 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000295 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
296 }
297
Victor Stinnercd6e6942015-09-18 09:11:57 +0200298 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000299 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200300 if (value != NULL) {
301 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700302 value = PyObject_CallMethod(importlib,
303 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200304 }
Nick Coghland6009512014-11-20 21:39:37 +1000305 if (value == NULL) {
306 PyErr_Print();
307 Py_FatalError("Py_Initialize: importlib install failed");
308 }
309 Py_DECREF(value);
310 Py_DECREF(impmod);
311
312 _PyImportZip_Init();
313}
314
Eric Snow1abcf672017-05-23 21:46:51 -0700315static void
316initexternalimport(PyInterpreterState *interp)
317{
318 PyObject *value;
319 value = PyObject_CallMethod(interp->importlib,
320 "_install_external_importers", "");
321 if (value == NULL) {
322 PyErr_Print();
323 Py_FatalError("Py_EndInitialization: external importer setup failed");
324 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200325 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700326}
Nick Coghland6009512014-11-20 21:39:37 +1000327
Nick Coghlan6ea41862017-06-11 13:16:15 +1000328/* Helper functions to better handle the legacy C locale
329 *
330 * The legacy C locale assumes ASCII as the default text encoding, which
331 * causes problems not only for the CPython runtime, but also other
332 * components like GNU readline.
333 *
334 * Accordingly, when the CLI detects it, it attempts to coerce it to a
335 * more capable UTF-8 based alternative as follows:
336 *
337 * if (_Py_LegacyLocaleDetected()) {
338 * _Py_CoerceLegacyLocale();
339 * }
340 *
341 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
342 *
343 * Locale coercion also impacts the default error handler for the standard
344 * streams: while the usual default is "strict", the default for the legacy
345 * C locale and for any of the coercion target locales is "surrogateescape".
346 */
347
348int
349_Py_LegacyLocaleDetected(void)
350{
351#ifndef MS_WINDOWS
352 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000353 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
354 * the POSIX locale as a simple alias for the C locale, so
355 * we may also want to check for that explicitly.
356 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
358 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
359#else
360 /* Windows uses code pages instead of locales, so no locale is legacy */
361 return 0;
362#endif
363}
364
Nick Coghlaneb817952017-06-18 12:29:42 +1000365static const char *_C_LOCALE_WARNING =
366 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
367 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
368 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
369 "locales is recommended.\n";
370
371static int
372_legacy_locale_warnings_enabled(void)
373{
374 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
375 return (coerce_c_locale != NULL &&
376 strncmp(coerce_c_locale, "warn", 5) == 0);
377}
378
379static void
380_emit_stderr_warning_for_legacy_locale(void)
381{
382 if (_legacy_locale_warnings_enabled()) {
383 if (_Py_LegacyLocaleDetected()) {
384 fprintf(stderr, "%s", _C_LOCALE_WARNING);
385 }
386 }
387}
388
Nick Coghlan6ea41862017-06-11 13:16:15 +1000389typedef struct _CandidateLocale {
390 const char *locale_name; /* The locale to try as a coercion target */
391} _LocaleCoercionTarget;
392
393static _LocaleCoercionTarget _TARGET_LOCALES[] = {
394 {"C.UTF-8"},
395 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000396 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000397 {NULL}
398};
399
400static char *
401get_default_standard_stream_error_handler(void)
402{
403 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
404 if (ctype_loc != NULL) {
405 /* "surrogateescape" is the default in the legacy C locale */
406 if (strcmp(ctype_loc, "C") == 0) {
407 return "surrogateescape";
408 }
409
410#ifdef PY_COERCE_C_LOCALE
411 /* "surrogateescape" is the default in locale coercion target locales */
412 const _LocaleCoercionTarget *target = NULL;
413 for (target = _TARGET_LOCALES; target->locale_name; target++) {
414 if (strcmp(ctype_loc, target->locale_name) == 0) {
415 return "surrogateescape";
416 }
417 }
418#endif
419 }
420
421 /* Otherwise return NULL to request the typical default error handler */
422 return NULL;
423}
424
425#ifdef PY_COERCE_C_LOCALE
426static const char *_C_LOCALE_COERCION_WARNING =
427 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
428 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
429
430static void
431_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
432{
433 const char *newloc = target->locale_name;
434
435 /* Reset locale back to currently configured defaults */
436 setlocale(LC_ALL, "");
437
438 /* Set the relevant locale environment variable */
439 if (setenv("LC_CTYPE", newloc, 1)) {
440 fprintf(stderr,
441 "Error setting LC_CTYPE, skipping C locale coercion\n");
442 return;
443 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000444 if (_legacy_locale_warnings_enabled()) {
445 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
446 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000447
448 /* Reconfigure with the overridden environment variables */
449 setlocale(LC_ALL, "");
450}
451#endif
452
453void
454_Py_CoerceLegacyLocale(void)
455{
456#ifdef PY_COERCE_C_LOCALE
457 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
458 * the locale settings *before* we try to do anything with the command
459 * line arguments. For cross-platform debugging purposes, we also need
460 * to give end users a way to force even scripts that are otherwise
461 * isolated from their environment to use the legacy ASCII-centric C
462 * locale.
463 *
464 * Ignoring -E and -I is safe from a security perspective, as we only use
465 * the setting to turn *off* the implicit locale coercion, and anyone with
466 * access to the process environment already has the ability to set
467 * `LC_ALL=C` to override the C level locale settings anyway.
468 */
469 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
470 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
471 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
472 const char *locale_override = getenv("LC_ALL");
473 if (locale_override == NULL || *locale_override == '\0') {
474 /* LC_ALL is also not set (or is set to an empty string) */
475 const _LocaleCoercionTarget *target = NULL;
476 for (target = _TARGET_LOCALES; target->locale_name; target++) {
477 const char *new_locale = setlocale(LC_CTYPE,
478 target->locale_name);
479 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000480#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
481 /* Also ensure that nl_langinfo works in this locale */
482 char *codeset = nl_langinfo(CODESET);
483 if (!codeset || *codeset == '\0') {
484 /* CODESET is not set or empty, so skip coercion */
485 new_locale = NULL;
486 setlocale(LC_CTYPE, "");
487 continue;
488 }
489#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000490 /* Successfully configured locale, so make it the default */
491 _coerce_default_locale_settings(target);
492 return;
493 }
494 }
495 }
496 }
497 /* No C locale warning here, as Py_Initialize will emit one later */
498#endif
499}
500
501
Eric Snow1abcf672017-05-23 21:46:51 -0700502/* Global initializations. Can be undone by Py_Finalize(). Don't
503 call this twice without an intervening Py_Finalize() call.
504
505 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
506 must have a corresponding call to Py_Finalize.
507
508 Locking: you must hold the interpreter lock while calling these APIs.
509 (If the lock has not yet been initialized, that's equivalent to
510 having the lock, but you cannot use multiple threads.)
511
512*/
513
514/* Begin interpreter initialization
515 *
516 * On return, the first thread and interpreter state have been created,
517 * but the compiler, signal handling, multithreading and
518 * multiple interpreter support, and codec infrastructure are not yet
519 * available.
520 *
521 * The import system will support builtin and frozen modules only.
522 * The only supported io is writing to sys.stderr
523 *
524 * If any operation invoked by this function fails, a fatal error is
525 * issued and the function does not return.
526 *
527 * Any code invoked from this function should *not* assume it has access
528 * to the Python C API (unless the API is explicitly listed as being
529 * safe to call without calling Py_Initialize first)
530 */
531
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200532/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700533 * Py_ReadConfig and Py_EndInitialization
534 */
535
536void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000537{
538 PyInterpreterState *interp;
539 PyThreadState *tstate;
540 PyObject *bimod, *sysmod, *pstderr;
541 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700542 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700543 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000544
Eric Snow1abcf672017-05-23 21:46:51 -0700545 if (config != NULL) {
546 core_config = *config;
547 }
548
Eric Snow05351c12017-09-05 21:43:08 -0700549 if (_Py_Initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700550 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
551 }
Eric Snow05351c12017-09-05 21:43:08 -0700552 if (_Py_CoreInitialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700553 Py_FatalError("Py_InitializeCore: runtime core already initialized");
554 }
555
556 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
557 * threads behave a little more gracefully at interpreter shutdown.
558 * We clobber it here so the new interpreter can start with a clean
559 * slate.
560 *
561 * However, this may still lead to misbehaviour if there are daemon
562 * threads still hanging around from a previous Py_Initialize/Finalize
563 * pair :(
564 */
Eric Snow05351c12017-09-05 21:43:08 -0700565 _Py_Finalizing = NULL;
Nick Coghland6009512014-11-20 21:39:37 +1000566
Nick Coghlan6ea41862017-06-11 13:16:15 +1000567#ifdef __ANDROID__
568 /* Passing "" to setlocale() on Android requests the C locale rather
569 * than checking environment variables, so request C.UTF-8 explicitly
570 */
571 setlocale(LC_CTYPE, "C.UTF-8");
572#else
573#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000574 /* Set up the LC_CTYPE locale, so we can obtain
575 the locale's charset without having to switch
576 locales. */
577 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000578 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000579#endif
Nick Coghland6009512014-11-20 21:39:37 +1000580#endif
581
582 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
583 Py_DebugFlag = add_flag(Py_DebugFlag, p);
584 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
585 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
586 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
587 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
588 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
589 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700590 /* The variable is only tested for existence here;
591 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000592 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
593 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700594#ifdef MS_WINDOWS
595 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
596 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700597 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
598 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700599#endif
Nick Coghland6009512014-11-20 21:39:37 +1000600
Eric Snow1abcf672017-05-23 21:46:51 -0700601 _Py_HashRandomization_Init(&core_config);
602 if (!core_config.use_hash_seed || core_config.hash_seed) {
603 /* Random or non-zero hash seed */
604 Py_HashRandomizationFlag = 1;
605 }
Nick Coghland6009512014-11-20 21:39:37 +1000606
Eric Snow05351c12017-09-05 21:43:08 -0700607 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000608 interp = PyInterpreterState_New();
609 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700610 Py_FatalError("Py_InitializeCore: can't make main interpreter");
611 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700612 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000613
614 tstate = PyThreadState_New(interp);
615 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700616 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000617 (void) PyThreadState_Swap(tstate);
618
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000619 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000620 destroying the GIL might fail when it is being referenced from
621 another running thread (see issue #9901).
622 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000623 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000624 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000625 /* Auto-thread-state API */
626 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000627
628 _Py_ReadyTypes();
629
630 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700631 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000632
633 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700634 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000635
636 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700637 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000638
639 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700640 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000641
Eric Snow86b7afd2017-09-04 17:54:09 -0600642 PyObject *modules = PyDict_New();
643 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700644 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000645
Eric Snow86b7afd2017-09-04 17:54:09 -0600646 sysmod = _PySys_BeginInit();
647 if (sysmod == NULL)
648 Py_FatalError("Py_InitializeCore: can't initialize sys");
649 interp->sysdict = PyModule_GetDict(sysmod);
650 if (interp->sysdict == NULL)
651 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
652 Py_INCREF(interp->sysdict);
653 PyDict_SetItemString(interp->sysdict, "modules", modules);
654 _PyImport_FixupBuiltin(sysmod, "sys", modules);
655
Nick Coghland6009512014-11-20 21:39:37 +1000656 /* Init Unicode implementation; relies on the codec registry */
657 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700658 Py_FatalError("Py_InitializeCore: can't initialize unicode");
659
Nick Coghland6009512014-11-20 21:39:37 +1000660 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700661 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000662
663 bimod = _PyBuiltin_Init();
664 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700665 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snow86b7afd2017-09-04 17:54:09 -0600666 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000667 interp->builtins = PyModule_GetDict(bimod);
668 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700669 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000670 Py_INCREF(interp->builtins);
671
672 /* initialize builtin exceptions */
673 _PyExc_Init(bimod);
674
Nick Coghland6009512014-11-20 21:39:37 +1000675 /* Set up a preliminary stderr printer until we have enough
676 infrastructure for the io module in place. */
677 pstderr = PyFile_NewStdPrinter(fileno(stderr));
678 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700679 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000680 _PySys_SetObjectId(&PyId_stderr, pstderr);
681 PySys_SetObject("__stderr__", pstderr);
682 Py_DECREF(pstderr);
683
684 _PyImport_Init();
685
686 _PyImportHooks_Init();
687
688 /* Initialize _warnings. */
689 _PyWarnings_Init();
690
Eric Snow1abcf672017-05-23 21:46:51 -0700691 /* This call sets up builtin and frozen import support */
692 if (!interp->core_config._disable_importlib) {
693 initimport(interp, sysmod);
694 }
695
696 /* Only when we get here is the runtime core fully initialized */
Eric Snow05351c12017-09-05 21:43:08 -0700697 _Py_CoreInitialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700698}
699
Eric Snowc7ec9982017-05-23 23:00:52 -0700700/* Read configuration settings from standard locations
701 *
702 * This function doesn't make any changes to the interpreter state - it
703 * merely populates any missing configuration settings. This allows an
704 * embedding application to completely override a config option by
705 * setting it before calling this function, or else modify the default
706 * setting before passing the fully populated config to Py_EndInitialization.
707 *
708 * More advanced selective initialization tricks are possible by calling
709 * this function multiple times with various preconfigured settings.
710 */
711
712int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
713{
714 /* Signal handlers are installed by default */
715 if (config->install_signal_handlers < 0) {
716 config->install_signal_handlers = 1;
717 }
718
719 return 0;
720}
721
722/* Update interpreter state based on supplied configuration settings
723 *
724 * After calling this function, most of the restrictions on the interpreter
725 * are lifted. The only remaining incomplete settings are those related
726 * to the main module (sys.argv[0], __main__ metadata)
727 *
728 * Calling this when the interpreter is not initializing, is already
729 * initialized or without a valid current thread state is a fatal error.
730 * Other errors should be reported as normal Python exceptions with a
731 * non-zero return code.
732 */
733int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700734{
735 PyInterpreterState *interp;
736 PyThreadState *tstate;
737
Eric Snow05351c12017-09-05 21:43:08 -0700738 if (!_Py_CoreInitialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700739 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
740 }
Eric Snow05351c12017-09-05 21:43:08 -0700741 if (_Py_Initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700742 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
743 }
744
Eric Snow1abcf672017-05-23 21:46:51 -0700745 /* Get current thread state and interpreter pointer */
746 tstate = PyThreadState_GET();
747 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700748 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700749 interp = tstate->interp;
750 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700751 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700752
753 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700754 interp->config = *config;
755
Eric Snow1abcf672017-05-23 21:46:51 -0700756 if (interp->core_config._disable_importlib) {
757 /* Special mode for freeze_importlib: run with no import system
758 *
759 * This means anything which needs support from extension modules
760 * or pure Python code in the standard library won't work.
761 */
Eric Snow05351c12017-09-05 21:43:08 -0700762 _Py_Initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700763 return 0;
764 }
765 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000766
Victor Stinner13019fd2015-04-03 13:10:54 +0200767 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700768 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200769
Eric Snow1abcf672017-05-23 21:46:51 -0700770 /* Finish setting up the sys module and import system */
771 /* GetPath may initialize state that _PySys_EndInit locks
772 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700773 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700774 PySys_SetPath(Py_GetPath());
775 if (_PySys_EndInit(interp->sysdict) < 0)
776 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700777 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000778
779 /* initialize the faulthandler module */
780 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700781 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000782
Nick Coghland6009512014-11-20 21:39:37 +1000783 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700784 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000785
Eric Snowc7ec9982017-05-23 23:00:52 -0700786 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000787 initsigs(); /* Signal handling stuff, including initintr() */
788
789 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700790 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000791
792 initmain(interp); /* Module __main__ */
793 if (initstdio() < 0)
794 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700795 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000796
797 /* Initialize warnings. */
798 if (PySys_HasWarnOptions()) {
799 PyObject *warnings_module = PyImport_ImportModule("warnings");
800 if (warnings_module == NULL) {
801 fprintf(stderr, "'import warnings' failed; traceback:\n");
802 PyErr_Print();
803 }
804 Py_XDECREF(warnings_module);
805 }
806
Eric Snow05351c12017-09-05 21:43:08 -0700807 _Py_Initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700808
Nick Coghland6009512014-11-20 21:39:37 +1000809 if (!Py_NoSiteFlag)
810 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700811
Eric Snowc7ec9982017-05-23 23:00:52 -0700812 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000813}
814
Eric Snowc7ec9982017-05-23 23:00:52 -0700815#undef _INIT_DEBUG_PRINT
816
Nick Coghland6009512014-11-20 21:39:37 +1000817void
Eric Snow1abcf672017-05-23 21:46:51 -0700818_Py_InitializeEx_Private(int install_sigs, int install_importlib)
819{
820 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700821 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700822
823 /* TODO: Moar config options! */
824 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
825 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700826 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700827 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700828 /* TODO: Print any exceptions raised by these operations */
829 if (_Py_ReadMainInterpreterConfig(&config))
830 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
831 if (_Py_InitializeMainInterpreter(&config))
832 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700833}
834
835
836void
Nick Coghland6009512014-11-20 21:39:37 +1000837Py_InitializeEx(int install_sigs)
838{
839 _Py_InitializeEx_Private(install_sigs, 1);
840}
841
842void
843Py_Initialize(void)
844{
845 Py_InitializeEx(1);
846}
847
848
849#ifdef COUNT_ALLOCS
850extern void dump_counts(FILE*);
851#endif
852
853/* Flush stdout and stderr */
854
855static int
856file_is_closed(PyObject *fobj)
857{
858 int r;
859 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
860 if (tmp == NULL) {
861 PyErr_Clear();
862 return 0;
863 }
864 r = PyObject_IsTrue(tmp);
865 Py_DECREF(tmp);
866 if (r < 0)
867 PyErr_Clear();
868 return r > 0;
869}
870
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000871static int
Nick Coghland6009512014-11-20 21:39:37 +1000872flush_std_files(void)
873{
874 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
875 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
876 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000877 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000878
879 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700880 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000881 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000882 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000883 status = -1;
884 }
Nick Coghland6009512014-11-20 21:39:37 +1000885 else
886 Py_DECREF(tmp);
887 }
888
889 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700890 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000891 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000892 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000893 status = -1;
894 }
Nick Coghland6009512014-11-20 21:39:37 +1000895 else
896 Py_DECREF(tmp);
897 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000898
899 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000900}
901
902/* Undo the effect of Py_Initialize().
903
904 Beware: if multiple interpreter and/or thread states exist, these
905 are not wiped out; only the current thread and interpreter state
906 are deleted. But since everything else is deleted, those other
907 interpreter and thread states should no longer be used.
908
909 (XXX We should do better, e.g. wipe out all interpreters and
910 threads.)
911
912 Locking: as above.
913
914*/
915
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000916int
917Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000918{
919 PyInterpreterState *interp;
920 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000921 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000922
Eric Snow05351c12017-09-05 21:43:08 -0700923 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000924 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000925
926 wait_for_thread_shutdown();
927
928 /* The interpreter is still entirely intact at this point, and the
929 * exit funcs may be relying on that. In particular, if some thread
930 * or exit func is still waiting to do an import, the import machinery
931 * expects Py_IsInitialized() to return true. So don't say the
932 * interpreter is uninitialized until after the exit funcs have run.
933 * Note that Threading.py uses an exit func to do a join on all the
934 * threads created thru it, so this also protects pending imports in
935 * the threads created via Threading.
936 */
937 call_py_exitfuncs();
938
939 /* Get current thread state and interpreter pointer */
940 tstate = PyThreadState_GET();
941 interp = tstate->interp;
942
943 /* Remaining threads (e.g. daemon threads) will automatically exit
944 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow05351c12017-09-05 21:43:08 -0700945 _Py_Finalizing = tstate;
946 _Py_Initialized = 0;
947 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000948
Victor Stinnere0deff32015-03-24 13:46:18 +0100949 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000950 if (flush_std_files() < 0) {
951 status = -1;
952 }
Nick Coghland6009512014-11-20 21:39:37 +1000953
954 /* Disable signal handling */
955 PyOS_FiniInterrupts();
956
957 /* Collect garbage. This may call finalizers; it's nice to call these
958 * before all modules are destroyed.
959 * XXX If a __del__ or weakref callback is triggered here, and tries to
960 * XXX import a module, bad things can happen, because Python no
961 * XXX longer believes it's initialized.
962 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
963 * XXX is easy to provoke that way. I've also seen, e.g.,
964 * XXX Exception exceptions.ImportError: 'No module named sha'
965 * XXX in <function callback at 0x008F5718> ignored
966 * XXX but I'm unclear on exactly how that one happens. In any case,
967 * XXX I haven't seen a real-life report of either of these.
968 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700969 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000970#ifdef COUNT_ALLOCS
971 /* With COUNT_ALLOCS, it helps to run GC multiple times:
972 each collection might release some types from the type
973 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700974 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000975 /* nothing */;
976#endif
977 /* Destroy all modules */
978 PyImport_Cleanup();
979
Victor Stinnere0deff32015-03-24 13:46:18 +0100980 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000981 if (flush_std_files() < 0) {
982 status = -1;
983 }
Nick Coghland6009512014-11-20 21:39:37 +1000984
985 /* Collect final garbage. This disposes of cycles created by
986 * class definitions, for example.
987 * XXX This is disabled because it caused too many problems. If
988 * XXX a __del__ or weakref callback triggers here, Python code has
989 * XXX a hard time running, because even the sys module has been
990 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
991 * XXX One symptom is a sequence of information-free messages
992 * XXX coming from threads (if a __del__ or callback is invoked,
993 * XXX other threads can execute too, and any exception they encounter
994 * XXX triggers a comedy of errors as subsystem after subsystem
995 * XXX fails to find what it *expects* to find in sys to help report
996 * XXX the exception and consequent unexpected failures). I've also
997 * XXX seen segfaults then, after adding print statements to the
998 * XXX Python code getting called.
999 */
1000#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001001 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001002#endif
1003
1004 /* Disable tracemalloc after all Python objects have been destroyed,
1005 so it is possible to use tracemalloc in objects destructor. */
1006 _PyTraceMalloc_Fini();
1007
1008 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1009 _PyImport_Fini();
1010
1011 /* Cleanup typeobject.c's internal caches. */
1012 _PyType_Fini();
1013
1014 /* unload faulthandler module */
1015 _PyFaulthandler_Fini();
1016
1017 /* Debugging stuff */
1018#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001019 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001020#endif
1021 /* dump hash stats */
1022 _PyHash_Fini();
1023
1024 _PY_DEBUG_PRINT_TOTAL_REFS();
1025
1026#ifdef Py_TRACE_REFS
1027 /* Display all objects still alive -- this can invoke arbitrary
1028 * __repr__ overrides, so requires a mostly-intact interpreter.
1029 * Alas, a lot of stuff may still be alive now that will be cleaned
1030 * up later.
1031 */
1032 if (Py_GETENV("PYTHONDUMPREFS"))
1033 _Py_PrintReferences(stderr);
1034#endif /* Py_TRACE_REFS */
1035
1036 /* Clear interpreter state and all thread states. */
1037 PyInterpreterState_Clear(interp);
1038
1039 /* Now we decref the exception classes. After this point nothing
1040 can raise an exception. That's okay, because each Fini() method
1041 below has been checked to make sure no exceptions are ever
1042 raised.
1043 */
1044
1045 _PyExc_Fini();
1046
1047 /* Sundry finalizers */
1048 PyMethod_Fini();
1049 PyFrame_Fini();
1050 PyCFunction_Fini();
1051 PyTuple_Fini();
1052 PyList_Fini();
1053 PySet_Fini();
1054 PyBytes_Fini();
1055 PyByteArray_Fini();
1056 PyLong_Fini();
1057 PyFloat_Fini();
1058 PyDict_Fini();
1059 PySlice_Fini();
1060 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001061 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001062 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001063 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001064
1065 /* Cleanup Unicode implementation */
1066 _PyUnicode_Fini();
1067
1068 /* reset file system default encoding */
1069 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1070 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1071 Py_FileSystemDefaultEncoding = NULL;
1072 }
1073
1074 /* XXX Still allocated:
1075 - various static ad-hoc pointers to interned strings
1076 - int and float free list blocks
1077 - whatever various modules and libraries allocate
1078 */
1079
1080 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1081
1082 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001083 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001084
1085 /* Delete current thread. After this, many C API calls become crashy. */
1086 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001087
Nick Coghland6009512014-11-20 21:39:37 +10001088 PyInterpreterState_Delete(interp);
1089
1090#ifdef Py_TRACE_REFS
1091 /* Display addresses (& refcnts) of all objects still alive.
1092 * An address can be used to find the repr of the object, printed
1093 * above by _Py_PrintReferences.
1094 */
1095 if (Py_GETENV("PYTHONDUMPREFS"))
1096 _Py_PrintReferenceAddresses(stderr);
1097#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001098#ifdef WITH_PYMALLOC
1099 if (_PyMem_PymallocEnabled()) {
1100 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1101 if (opt != NULL && *opt != '\0')
1102 _PyObject_DebugMallocStats(stderr);
1103 }
Nick Coghland6009512014-11-20 21:39:37 +10001104#endif
1105
1106 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001107 return status;
1108}
1109
1110void
1111Py_Finalize(void)
1112{
1113 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001114}
1115
1116/* Create and initialize a new interpreter and thread, and return the
1117 new thread. This requires that Py_Initialize() has been called
1118 first.
1119
1120 Unsuccessful initialization yields a NULL pointer. Note that *no*
1121 exception information is available even in this case -- the
1122 exception information is held in the thread, and there is no
1123 thread.
1124
1125 Locking: as above.
1126
1127*/
1128
1129PyThreadState *
1130Py_NewInterpreter(void)
1131{
1132 PyInterpreterState *interp;
1133 PyThreadState *tstate, *save_tstate;
1134 PyObject *bimod, *sysmod;
1135
Eric Snow05351c12017-09-05 21:43:08 -07001136 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001137 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1138
Victor Stinner8a1be612016-03-14 22:07:55 +01001139 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1140 interpreters: disable PyGILState_Check(). */
1141 _PyGILState_check_enabled = 0;
1142
Nick Coghland6009512014-11-20 21:39:37 +10001143 interp = PyInterpreterState_New();
1144 if (interp == NULL)
1145 return NULL;
1146
1147 tstate = PyThreadState_New(interp);
1148 if (tstate == NULL) {
1149 PyInterpreterState_Delete(interp);
1150 return NULL;
1151 }
1152
1153 save_tstate = PyThreadState_Swap(tstate);
1154
Eric Snow1abcf672017-05-23 21:46:51 -07001155 /* Copy the current interpreter config into the new interpreter */
1156 if (save_tstate != NULL) {
1157 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001158 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001159 } else {
1160 /* No current thread state, copy from the main interpreter */
1161 PyInterpreterState *main_interp = PyInterpreterState_Main();
1162 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001163 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001164 }
1165
Nick Coghland6009512014-11-20 21:39:37 +10001166 /* XXX The following is lax in error checking */
1167
Eric Snow86b7afd2017-09-04 17:54:09 -06001168 PyObject *modules = PyDict_New();
1169 if (modules == NULL)
1170 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +10001171
Eric Snow86b7afd2017-09-04 17:54:09 -06001172 sysmod = _PyImport_FindBuiltin("sys", modules);
1173 if (sysmod != NULL) {
1174 interp->sysdict = PyModule_GetDict(sysmod);
1175 if (interp->sysdict == NULL)
1176 goto handle_error;
1177 Py_INCREF(interp->sysdict);
1178 PyDict_SetItemString(interp->sysdict, "modules", modules);
1179 PySys_SetPath(Py_GetPath());
1180 _PySys_EndInit(interp->sysdict);
1181 }
1182
1183 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001184 if (bimod != NULL) {
1185 interp->builtins = PyModule_GetDict(bimod);
1186 if (interp->builtins == NULL)
1187 goto handle_error;
1188 Py_INCREF(interp->builtins);
1189 }
1190
1191 /* initialize builtin exceptions */
1192 _PyExc_Init(bimod);
1193
Nick Coghland6009512014-11-20 21:39:37 +10001194 if (bimod != NULL && sysmod != NULL) {
1195 PyObject *pstderr;
1196
Nick Coghland6009512014-11-20 21:39:37 +10001197 /* Set up a preliminary stderr printer until we have enough
1198 infrastructure for the io module in place. */
1199 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1200 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001201 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001202 _PySys_SetObjectId(&PyId_stderr, pstderr);
1203 PySys_SetObject("__stderr__", pstderr);
1204 Py_DECREF(pstderr);
1205
1206 _PyImportHooks_Init();
1207
Eric Snow1abcf672017-05-23 21:46:51 -07001208 initimport(interp, sysmod);
1209 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001210
1211 if (initfsencoding(interp) < 0)
1212 goto handle_error;
1213
1214 if (initstdio() < 0)
1215 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001216 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001217 initmain(interp);
1218 if (!Py_NoSiteFlag)
1219 initsite();
1220 }
1221
1222 if (!PyErr_Occurred())
1223 return tstate;
1224
1225handle_error:
1226 /* Oops, it didn't work. Undo it all. */
1227
1228 PyErr_PrintEx(0);
1229 PyThreadState_Clear(tstate);
1230 PyThreadState_Swap(save_tstate);
1231 PyThreadState_Delete(tstate);
1232 PyInterpreterState_Delete(interp);
1233
1234 return NULL;
1235}
1236
1237/* Delete an interpreter and its last thread. This requires that the
1238 given thread state is current, that the thread has no remaining
1239 frames, and that it is its interpreter's only remaining thread.
1240 It is a fatal error to violate these constraints.
1241
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001242 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001243 everything, regardless.)
1244
1245 Locking: as above.
1246
1247*/
1248
1249void
1250Py_EndInterpreter(PyThreadState *tstate)
1251{
1252 PyInterpreterState *interp = tstate->interp;
1253
1254 if (tstate != PyThreadState_GET())
1255 Py_FatalError("Py_EndInterpreter: thread is not current");
1256 if (tstate->frame != NULL)
1257 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1258
1259 wait_for_thread_shutdown();
1260
1261 if (tstate != interp->tstate_head || tstate->next != NULL)
1262 Py_FatalError("Py_EndInterpreter: not the last thread");
1263
1264 PyImport_Cleanup();
1265 PyInterpreterState_Clear(interp);
1266 PyThreadState_Swap(NULL);
1267 PyInterpreterState_Delete(interp);
1268}
1269
1270#ifdef MS_WINDOWS
1271static wchar_t *progname = L"python";
1272#else
1273static wchar_t *progname = L"python3";
1274#endif
1275
1276void
1277Py_SetProgramName(wchar_t *pn)
1278{
1279 if (pn && *pn)
1280 progname = pn;
1281}
1282
1283wchar_t *
1284Py_GetProgramName(void)
1285{
1286 return progname;
1287}
1288
1289static wchar_t *default_home = NULL;
1290static wchar_t env_home[MAXPATHLEN+1];
1291
1292void
1293Py_SetPythonHome(wchar_t *home)
1294{
1295 default_home = home;
1296}
1297
1298wchar_t *
1299Py_GetPythonHome(void)
1300{
1301 wchar_t *home = default_home;
1302 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1303 char* chome = Py_GETENV("PYTHONHOME");
1304 if (chome) {
1305 size_t size = Py_ARRAY_LENGTH(env_home);
1306 size_t r = mbstowcs(env_home, chome, size);
1307 if (r != (size_t)-1 && r < size)
1308 home = env_home;
1309 }
1310
1311 }
1312 return home;
1313}
1314
1315/* Create __main__ module */
1316
1317static void
1318initmain(PyInterpreterState *interp)
1319{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001320 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001321 m = PyImport_AddModule("__main__");
1322 if (m == NULL)
1323 Py_FatalError("can't create __main__ module");
1324 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001325 ann_dict = PyDict_New();
1326 if ((ann_dict == NULL) ||
1327 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1328 Py_FatalError("Failed to initialize __main__.__annotations__");
1329 }
1330 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001331 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1332 PyObject *bimod = PyImport_ImportModule("builtins");
1333 if (bimod == NULL) {
1334 Py_FatalError("Failed to retrieve builtins module");
1335 }
1336 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1337 Py_FatalError("Failed to initialize __main__.__builtins__");
1338 }
1339 Py_DECREF(bimod);
1340 }
1341 /* Main is a little special - imp.is_builtin("__main__") will return
1342 * False, but BuiltinImporter is still the most appropriate initial
1343 * setting for its __loader__ attribute. A more suitable value will
1344 * be set if __main__ gets further initialized later in the startup
1345 * process.
1346 */
1347 loader = PyDict_GetItemString(d, "__loader__");
1348 if (loader == NULL || loader == Py_None) {
1349 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1350 "BuiltinImporter");
1351 if (loader == NULL) {
1352 Py_FatalError("Failed to retrieve BuiltinImporter");
1353 }
1354 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1355 Py_FatalError("Failed to initialize __main__.__loader__");
1356 }
1357 Py_DECREF(loader);
1358 }
1359}
1360
1361static int
1362initfsencoding(PyInterpreterState *interp)
1363{
1364 PyObject *codec;
1365
Steve Dowercc16be82016-09-08 10:35:16 -07001366#ifdef MS_WINDOWS
1367 if (Py_LegacyWindowsFSEncodingFlag)
1368 {
1369 Py_FileSystemDefaultEncoding = "mbcs";
1370 Py_FileSystemDefaultEncodeErrors = "replace";
1371 }
1372 else
1373 {
1374 Py_FileSystemDefaultEncoding = "utf-8";
1375 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1376 }
1377#else
Nick Coghland6009512014-11-20 21:39:37 +10001378 if (Py_FileSystemDefaultEncoding == NULL)
1379 {
1380 Py_FileSystemDefaultEncoding = get_locale_encoding();
1381 if (Py_FileSystemDefaultEncoding == NULL)
1382 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1383
1384 Py_HasFileSystemDefaultEncoding = 0;
1385 interp->fscodec_initialized = 1;
1386 return 0;
1387 }
Steve Dowercc16be82016-09-08 10:35:16 -07001388#endif
Nick Coghland6009512014-11-20 21:39:37 +10001389
1390 /* the encoding is mbcs, utf-8 or ascii */
1391 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1392 if (!codec) {
1393 /* Such error can only occurs in critical situations: no more
1394 * memory, import a module of the standard library failed,
1395 * etc. */
1396 return -1;
1397 }
1398 Py_DECREF(codec);
1399 interp->fscodec_initialized = 1;
1400 return 0;
1401}
1402
1403/* Import the site module (not into __main__ though) */
1404
1405static void
1406initsite(void)
1407{
1408 PyObject *m;
1409 m = PyImport_ImportModule("site");
1410 if (m == NULL) {
1411 fprintf(stderr, "Failed to import the site module\n");
1412 PyErr_Print();
1413 Py_Finalize();
1414 exit(1);
1415 }
1416 else {
1417 Py_DECREF(m);
1418 }
1419}
1420
Victor Stinner874dbe82015-09-04 17:29:57 +02001421/* Check if a file descriptor is valid or not.
1422 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1423static int
1424is_valid_fd(int fd)
1425{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001426#ifdef __APPLE__
1427 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1428 and the other side of the pipe is closed, dup(1) succeed, whereas
1429 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1430 such error. */
1431 struct stat st;
1432 return (fstat(fd, &st) == 0);
1433#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001434 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001435 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001436 return 0;
1437 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001438 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1439 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1440 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001441 fd2 = dup(fd);
1442 if (fd2 >= 0)
1443 close(fd2);
1444 _Py_END_SUPPRESS_IPH
1445 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001446#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001447}
1448
1449/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001450static PyObject*
1451create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001452 int fd, int write_mode, const char* name,
1453 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001454{
1455 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1456 const char* mode;
1457 const char* newline;
1458 PyObject *line_buffering;
1459 int buffering, isatty;
1460 _Py_IDENTIFIER(open);
1461 _Py_IDENTIFIER(isatty);
1462 _Py_IDENTIFIER(TextIOWrapper);
1463 _Py_IDENTIFIER(mode);
1464
Victor Stinner874dbe82015-09-04 17:29:57 +02001465 if (!is_valid_fd(fd))
1466 Py_RETURN_NONE;
1467
Nick Coghland6009512014-11-20 21:39:37 +10001468 /* stdin is always opened in buffered mode, first because it shouldn't
1469 make a difference in common use cases, second because TextIOWrapper
1470 depends on the presence of a read1() method which only exists on
1471 buffered streams.
1472 */
1473 if (Py_UnbufferedStdioFlag && write_mode)
1474 buffering = 0;
1475 else
1476 buffering = -1;
1477 if (write_mode)
1478 mode = "wb";
1479 else
1480 mode = "rb";
1481 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1482 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001483 Py_None, Py_None, /* encoding, errors */
1484 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001485 if (buf == NULL)
1486 goto error;
1487
1488 if (buffering) {
1489 _Py_IDENTIFIER(raw);
1490 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1491 if (raw == NULL)
1492 goto error;
1493 }
1494 else {
1495 raw = buf;
1496 Py_INCREF(raw);
1497 }
1498
Steve Dower39294992016-08-30 21:22:36 -07001499#ifdef MS_WINDOWS
1500 /* Windows console IO is always UTF-8 encoded */
1501 if (PyWindowsConsoleIO_Check(raw))
1502 encoding = "utf-8";
1503#endif
1504
Nick Coghland6009512014-11-20 21:39:37 +10001505 text = PyUnicode_FromString(name);
1506 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1507 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001508 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001509 if (res == NULL)
1510 goto error;
1511 isatty = PyObject_IsTrue(res);
1512 Py_DECREF(res);
1513 if (isatty == -1)
1514 goto error;
1515 if (isatty || Py_UnbufferedStdioFlag)
1516 line_buffering = Py_True;
1517 else
1518 line_buffering = Py_False;
1519
1520 Py_CLEAR(raw);
1521 Py_CLEAR(text);
1522
1523#ifdef MS_WINDOWS
1524 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1525 newlines to "\n".
1526 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1527 newline = NULL;
1528#else
1529 /* sys.stdin: split lines at "\n".
1530 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1531 newline = "\n";
1532#endif
1533
1534 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1535 buf, encoding, errors,
1536 newline, line_buffering);
1537 Py_CLEAR(buf);
1538 if (stream == NULL)
1539 goto error;
1540
1541 if (write_mode)
1542 mode = "w";
1543 else
1544 mode = "r";
1545 text = PyUnicode_FromString(mode);
1546 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1547 goto error;
1548 Py_CLEAR(text);
1549 return stream;
1550
1551error:
1552 Py_XDECREF(buf);
1553 Py_XDECREF(stream);
1554 Py_XDECREF(text);
1555 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001556
Victor Stinner874dbe82015-09-04 17:29:57 +02001557 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1558 /* Issue #24891: the file descriptor was closed after the first
1559 is_valid_fd() check was called. Ignore the OSError and set the
1560 stream to None. */
1561 PyErr_Clear();
1562 Py_RETURN_NONE;
1563 }
1564 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001565}
1566
1567/* Initialize sys.stdin, stdout, stderr and builtins.open */
1568static int
1569initstdio(void)
1570{
1571 PyObject *iomod = NULL, *wrapper;
1572 PyObject *bimod = NULL;
1573 PyObject *m;
1574 PyObject *std = NULL;
1575 int status = 0, fd;
1576 PyObject * encoding_attr;
1577 char *pythonioencoding = NULL, *encoding, *errors;
1578
1579 /* Hack to avoid a nasty recursion issue when Python is invoked
1580 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1581 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1582 goto error;
1583 }
1584 Py_DECREF(m);
1585
1586 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1587 goto error;
1588 }
1589 Py_DECREF(m);
1590
1591 if (!(bimod = PyImport_ImportModule("builtins"))) {
1592 goto error;
1593 }
1594
1595 if (!(iomod = PyImport_ImportModule("io"))) {
1596 goto error;
1597 }
1598 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1599 goto error;
1600 }
1601
1602 /* Set builtins.open */
1603 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1604 Py_DECREF(wrapper);
1605 goto error;
1606 }
1607 Py_DECREF(wrapper);
1608
1609 encoding = _Py_StandardStreamEncoding;
1610 errors = _Py_StandardStreamErrors;
1611 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001612 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1613 if (pythonioencoding) {
1614 char *err;
1615 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1616 if (pythonioencoding == NULL) {
1617 PyErr_NoMemory();
1618 goto error;
1619 }
1620 err = strchr(pythonioencoding, ':');
1621 if (err) {
1622 *err = '\0';
1623 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001624 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001625 errors = err;
1626 }
1627 }
1628 if (*pythonioencoding && !encoding) {
1629 encoding = pythonioencoding;
1630 }
1631 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001632 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001633 /* Choose the default error handler based on the current locale */
1634 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001635 }
Nick Coghland6009512014-11-20 21:39:37 +10001636 }
1637
1638 /* Set sys.stdin */
1639 fd = fileno(stdin);
1640 /* Under some conditions stdin, stdout and stderr may not be connected
1641 * and fileno() may point to an invalid file descriptor. For example
1642 * GUI apps don't have valid standard streams by default.
1643 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001644 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1645 if (std == NULL)
1646 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001647 PySys_SetObject("__stdin__", std);
1648 _PySys_SetObjectId(&PyId_stdin, std);
1649 Py_DECREF(std);
1650
1651 /* Set sys.stdout */
1652 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001653 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1654 if (std == NULL)
1655 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001656 PySys_SetObject("__stdout__", std);
1657 _PySys_SetObjectId(&PyId_stdout, std);
1658 Py_DECREF(std);
1659
1660#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1661 /* Set sys.stderr, replaces the preliminary stderr */
1662 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001663 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1664 if (std == NULL)
1665 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001666
1667 /* Same as hack above, pre-import stderr's codec to avoid recursion
1668 when import.c tries to write to stderr in verbose mode. */
1669 encoding_attr = PyObject_GetAttrString(std, "encoding");
1670 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001671 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001672 if (std_encoding != NULL) {
1673 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1674 Py_XDECREF(codec_info);
1675 }
1676 Py_DECREF(encoding_attr);
1677 }
1678 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1679
1680 if (PySys_SetObject("__stderr__", std) < 0) {
1681 Py_DECREF(std);
1682 goto error;
1683 }
1684 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1685 Py_DECREF(std);
1686 goto error;
1687 }
1688 Py_DECREF(std);
1689#endif
1690
1691 if (0) {
1692 error:
1693 status = -1;
1694 }
1695
1696 /* We won't need them anymore. */
1697 if (_Py_StandardStreamEncoding) {
1698 PyMem_RawFree(_Py_StandardStreamEncoding);
1699 _Py_StandardStreamEncoding = NULL;
1700 }
1701 if (_Py_StandardStreamErrors) {
1702 PyMem_RawFree(_Py_StandardStreamErrors);
1703 _Py_StandardStreamErrors = NULL;
1704 }
1705 PyMem_Free(pythonioencoding);
1706 Py_XDECREF(bimod);
1707 Py_XDECREF(iomod);
1708 return status;
1709}
1710
1711
Victor Stinner10dc4842015-03-24 12:01:30 +01001712static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001713_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001714{
Victor Stinner10dc4842015-03-24 12:01:30 +01001715 fputc('\n', stderr);
1716 fflush(stderr);
1717
1718 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001719 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001720}
Victor Stinner791da1c2016-03-14 16:53:12 +01001721
1722/* Print the current exception (if an exception is set) with its traceback,
1723 or display the current Python stack.
1724
1725 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1726 called on catastrophic cases.
1727
1728 Return 1 if the traceback was displayed, 0 otherwise. */
1729
1730static int
1731_Py_FatalError_PrintExc(int fd)
1732{
1733 PyObject *ferr, *res;
1734 PyObject *exception, *v, *tb;
1735 int has_tb;
1736
1737 if (PyThreadState_GET() == NULL) {
1738 /* The GIL is released: trying to acquire it is likely to deadlock,
1739 just give up. */
1740 return 0;
1741 }
1742
1743 PyErr_Fetch(&exception, &v, &tb);
1744 if (exception == NULL) {
1745 /* No current exception */
1746 return 0;
1747 }
1748
1749 ferr = _PySys_GetObjectId(&PyId_stderr);
1750 if (ferr == NULL || ferr == Py_None) {
1751 /* sys.stderr is not set yet or set to None,
1752 no need to try to display the exception */
1753 return 0;
1754 }
1755
1756 PyErr_NormalizeException(&exception, &v, &tb);
1757 if (tb == NULL) {
1758 tb = Py_None;
1759 Py_INCREF(tb);
1760 }
1761 PyException_SetTraceback(v, tb);
1762 if (exception == NULL) {
1763 /* PyErr_NormalizeException() failed */
1764 return 0;
1765 }
1766
1767 has_tb = (tb != Py_None);
1768 PyErr_Display(exception, v, tb);
1769 Py_XDECREF(exception);
1770 Py_XDECREF(v);
1771 Py_XDECREF(tb);
1772
1773 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001774 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001775 if (res == NULL)
1776 PyErr_Clear();
1777 else
1778 Py_DECREF(res);
1779
1780 return has_tb;
1781}
1782
Nick Coghland6009512014-11-20 21:39:37 +10001783/* Print fatal error message and abort */
1784
1785void
1786Py_FatalError(const char *msg)
1787{
1788 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001789 static int reentrant = 0;
1790#ifdef MS_WINDOWS
1791 size_t len;
1792 WCHAR* buffer;
1793 size_t i;
1794#endif
1795
1796 if (reentrant) {
1797 /* Py_FatalError() caused a second fatal error.
1798 Example: flush_std_files() raises a recursion error. */
1799 goto exit;
1800 }
1801 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001802
1803 fprintf(stderr, "Fatal Python error: %s\n", msg);
1804 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001805
Victor Stinnere0deff32015-03-24 13:46:18 +01001806 /* Print the exception (if an exception is set) with its traceback,
1807 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001808 if (!_Py_FatalError_PrintExc(fd))
1809 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001810
Victor Stinner2025d782016-03-16 23:19:15 +01001811 /* The main purpose of faulthandler is to display the traceback. We already
1812 * did our best to display it. So faulthandler can now be disabled.
1813 * (Don't trigger it on abort().) */
1814 _PyFaulthandler_Fini();
1815
Victor Stinner791da1c2016-03-14 16:53:12 +01001816 /* Check if the current Python thread hold the GIL */
1817 if (PyThreadState_GET() != NULL) {
1818 /* Flush sys.stdout and sys.stderr */
1819 flush_std_files();
1820 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001821
Nick Coghland6009512014-11-20 21:39:37 +10001822#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001823 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001824
Victor Stinner53345a42015-03-25 01:55:14 +01001825 /* Convert the message to wchar_t. This uses a simple one-to-one
1826 conversion, assuming that the this error message actually uses ASCII
1827 only. If this ceases to be true, we will have to convert. */
1828 buffer = alloca( (len+1) * (sizeof *buffer));
1829 for( i=0; i<=len; ++i)
1830 buffer[i] = msg[i];
1831 OutputDebugStringW(L"Fatal Python error: ");
1832 OutputDebugStringW(buffer);
1833 OutputDebugStringW(L"\n");
1834#endif /* MS_WINDOWS */
1835
1836exit:
1837#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001838 DebugBreak();
1839#endif
Nick Coghland6009512014-11-20 21:39:37 +10001840 abort();
1841}
1842
1843/* Clean up and exit */
1844
Victor Stinnerd7292b52016-06-17 12:29:00 +02001845# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001846
Eric Snow05351c12017-09-05 21:43:08 -07001847static void (*pyexitfunc)(void) = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001848/* For the atexit module. */
1849void _Py_PyAtExit(void (*func)(void))
1850{
Eric Snow05351c12017-09-05 21:43:08 -07001851 pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001852}
1853
1854static void
1855call_py_exitfuncs(void)
1856{
Eric Snow05351c12017-09-05 21:43:08 -07001857 if (pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001858 return;
1859
Eric Snow05351c12017-09-05 21:43:08 -07001860 (*pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001861 PyErr_Clear();
1862}
1863
1864/* Wait until threading._shutdown completes, provided
1865 the threading module was imported in the first place.
1866 The shutdown routine will wait until all non-daemon
1867 "threading" threads have completed. */
1868static void
1869wait_for_thread_shutdown(void)
1870{
Nick Coghland6009512014-11-20 21:39:37 +10001871 _Py_IDENTIFIER(_shutdown);
1872 PyObject *result;
Eric Snow86b7afd2017-09-04 17:54:09 -06001873 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001874 if (threading == NULL) {
1875 /* threading not imported */
1876 PyErr_Clear();
1877 return;
1878 }
Eric Snow86b7afd2017-09-04 17:54:09 -06001879 Py_INCREF(threading);
Victor Stinner3466bde2016-09-05 18:16:01 -07001880 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001881 if (result == NULL) {
1882 PyErr_WriteUnraisable(threading);
1883 }
1884 else {
1885 Py_DECREF(result);
1886 }
1887 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001888}
1889
1890#define NEXITFUNCS 32
Eric Snow05351c12017-09-05 21:43:08 -07001891static void (*exitfuncs[NEXITFUNCS])(void);
1892static int nexitfuncs = 0;
1893
Nick Coghland6009512014-11-20 21:39:37 +10001894int Py_AtExit(void (*func)(void))
1895{
Eric Snow05351c12017-09-05 21:43:08 -07001896 if (nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001897 return -1;
Eric Snow05351c12017-09-05 21:43:08 -07001898 exitfuncs[nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001899 return 0;
1900}
1901
1902static void
1903call_ll_exitfuncs(void)
1904{
Eric Snow05351c12017-09-05 21:43:08 -07001905 while (nexitfuncs > 0)
1906 (*exitfuncs[--nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001907
1908 fflush(stdout);
1909 fflush(stderr);
1910}
1911
1912void
1913Py_Exit(int sts)
1914{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001915 if (Py_FinalizeEx() < 0) {
1916 sts = 120;
1917 }
Nick Coghland6009512014-11-20 21:39:37 +10001918
1919 exit(sts);
1920}
1921
1922static void
1923initsigs(void)
1924{
1925#ifdef SIGPIPE
1926 PyOS_setsig(SIGPIPE, SIG_IGN);
1927#endif
1928#ifdef SIGXFZ
1929 PyOS_setsig(SIGXFZ, SIG_IGN);
1930#endif
1931#ifdef SIGXFSZ
1932 PyOS_setsig(SIGXFSZ, SIG_IGN);
1933#endif
1934 PyOS_InitInterrupts(); /* May imply initsignal() */
1935 if (PyErr_Occurred()) {
1936 Py_FatalError("Py_Initialize: can't import signal");
1937 }
1938}
1939
1940
1941/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1942 *
1943 * All of the code in this function must only use async-signal-safe functions,
1944 * listed at `man 7 signal` or
1945 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1946 */
1947void
1948_Py_RestoreSignals(void)
1949{
1950#ifdef SIGPIPE
1951 PyOS_setsig(SIGPIPE, SIG_DFL);
1952#endif
1953#ifdef SIGXFZ
1954 PyOS_setsig(SIGXFZ, SIG_DFL);
1955#endif
1956#ifdef SIGXFSZ
1957 PyOS_setsig(SIGXFSZ, SIG_DFL);
1958#endif
1959}
1960
1961
1962/*
1963 * The file descriptor fd is considered ``interactive'' if either
1964 * a) isatty(fd) is TRUE, or
1965 * b) the -i flag was given, and the filename associated with
1966 * the descriptor is NULL or "<stdin>" or "???".
1967 */
1968int
1969Py_FdIsInteractive(FILE *fp, const char *filename)
1970{
1971 if (isatty((int)fileno(fp)))
1972 return 1;
1973 if (!Py_InteractiveFlag)
1974 return 0;
1975 return (filename == NULL) ||
1976 (strcmp(filename, "<stdin>") == 0) ||
1977 (strcmp(filename, "???") == 0);
1978}
1979
1980
Nick Coghland6009512014-11-20 21:39:37 +10001981/* Wrappers around sigaction() or signal(). */
1982
1983PyOS_sighandler_t
1984PyOS_getsig(int sig)
1985{
1986#ifdef HAVE_SIGACTION
1987 struct sigaction context;
1988 if (sigaction(sig, NULL, &context) == -1)
1989 return SIG_ERR;
1990 return context.sa_handler;
1991#else
1992 PyOS_sighandler_t handler;
1993/* Special signal handling for the secure CRT in Visual Studio 2005 */
1994#if defined(_MSC_VER) && _MSC_VER >= 1400
1995 switch (sig) {
1996 /* Only these signals are valid */
1997 case SIGINT:
1998 case SIGILL:
1999 case SIGFPE:
2000 case SIGSEGV:
2001 case SIGTERM:
2002 case SIGBREAK:
2003 case SIGABRT:
2004 break;
2005 /* Don't call signal() with other values or it will assert */
2006 default:
2007 return SIG_ERR;
2008 }
2009#endif /* _MSC_VER && _MSC_VER >= 1400 */
2010 handler = signal(sig, SIG_IGN);
2011 if (handler != SIG_ERR)
2012 signal(sig, handler);
2013 return handler;
2014#endif
2015}
2016
2017/*
2018 * All of the code in this function must only use async-signal-safe functions,
2019 * listed at `man 7 signal` or
2020 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2021 */
2022PyOS_sighandler_t
2023PyOS_setsig(int sig, PyOS_sighandler_t handler)
2024{
2025#ifdef HAVE_SIGACTION
2026 /* Some code in Modules/signalmodule.c depends on sigaction() being
2027 * used here if HAVE_SIGACTION is defined. Fix that if this code
2028 * changes to invalidate that assumption.
2029 */
2030 struct sigaction context, ocontext;
2031 context.sa_handler = handler;
2032 sigemptyset(&context.sa_mask);
2033 context.sa_flags = 0;
2034 if (sigaction(sig, &context, &ocontext) == -1)
2035 return SIG_ERR;
2036 return ocontext.sa_handler;
2037#else
2038 PyOS_sighandler_t oldhandler;
2039 oldhandler = signal(sig, handler);
2040#ifdef HAVE_SIGINTERRUPT
2041 siginterrupt(sig, 1);
2042#endif
2043 return oldhandler;
2044#endif
2045}
2046
2047#ifdef __cplusplus
2048}
2049#endif