blob: 3f405b1225a3096def8632e716f41ab970b38e7d [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
75#ifdef WITH_THREAD
76extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
78#endif /* WITH_THREAD */
79
Benjamin Petersonb0a9a5a2017-09-05 20:19:12 -070080_PyRuntimeState _PyRuntime = {0, 0};
Eric Snow76d5abc2017-09-05 18:26:16 -070081
82void
83_PyRuntime_Initialize(void)
84{
85 /* XXX We only initialize once in the process, which aligns with
86 the static initialization of the former globals now found in
87 _PyRuntime. However, _PyRuntime *should* be initialized with
88 every Py_Initialize() call, but doing so breaks the runtime.
89 This is because the runtime state is not properly finalized
90 currently. */
91 static int initialized = 0;
92 if (initialized)
93 return;
94 initialized = 1;
95 _PyRuntimeState_Init(&_PyRuntime);
96}
97
98void
99_PyRuntime_Finalize(void)
100{
101 _PyRuntimeState_Fini(&_PyRuntime);
102}
103
Nick Coghland6009512014-11-20 21:39:37 +1000104/* Global configuration variable declarations are in pydebug.h */
105/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
106int Py_DebugFlag; /* Needed by parser.c */
107int Py_VerboseFlag; /* Needed by import.c */
108int Py_QuietFlag; /* Needed by sysmodule.c */
109int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
110int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
111int Py_OptimizeFlag = 0; /* Needed by compile.c */
112int Py_NoSiteFlag; /* Suppress 'import site' */
113int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
114int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
115int Py_FrozenFlag; /* Needed by getpath.c */
116int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800117int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000118int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
119int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
120int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
121int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700122#ifdef MS_WINDOWS
123int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700124int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700125#endif
Nick Coghland6009512014-11-20 21:39:37 +1000126
Nick Coghland6009512014-11-20 21:39:37 +1000127/* Hack to force loading of object files */
128int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
129 PyOS_mystrnicmp; /* Python/pystrcmp.o */
130
131/* PyModule_GetWarningsModule is no longer necessary as of 2.6
132since _warnings is builtin. This API should not be used. */
133PyObject *
134PyModule_GetWarningsModule(void)
135{
136 return PyImport_ImportModule("warnings");
137}
138
Eric Snowc7ec9982017-05-23 23:00:52 -0700139
Eric Snow1abcf672017-05-23 21:46:51 -0700140/* APIs to access the initialization flags
141 *
142 * Can be called prior to Py_Initialize.
143 */
Nick Coghland6009512014-11-20 21:39:37 +1000144
Eric Snow1abcf672017-05-23 21:46:51 -0700145int
146_Py_IsCoreInitialized(void)
147{
Eric Snow76d5abc2017-09-05 18:26:16 -0700148 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700149}
Nick Coghland6009512014-11-20 21:39:37 +1000150
151int
152Py_IsInitialized(void)
153{
Eric Snow76d5abc2017-09-05 18:26:16 -0700154 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000155}
156
157/* Helper to allow an embedding application to override the normal
158 * mechanism that attempts to figure out an appropriate IO encoding
159 */
160
161static char *_Py_StandardStreamEncoding = NULL;
162static char *_Py_StandardStreamErrors = NULL;
163
164int
165Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
166{
167 if (Py_IsInitialized()) {
168 /* This is too late to have any effect */
169 return -1;
170 }
171 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
172 * initialised yet.
173 *
174 * However, the raw memory allocators are initialised appropriately
175 * as C static variables, so _PyMem_RawStrdup is OK even though
176 * Py_Initialize hasn't been called yet.
177 */
178 if (encoding) {
179 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
180 if (!_Py_StandardStreamEncoding) {
181 return -2;
182 }
183 }
184 if (errors) {
185 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
186 if (!_Py_StandardStreamErrors) {
187 if (_Py_StandardStreamEncoding) {
188 PyMem_RawFree(_Py_StandardStreamEncoding);
189 }
190 return -3;
191 }
192 }
Steve Dower39294992016-08-30 21:22:36 -0700193#ifdef MS_WINDOWS
194 if (_Py_StandardStreamEncoding) {
195 /* Overriding the stream encoding implies legacy streams */
196 Py_LegacyWindowsStdioFlag = 1;
197 }
198#endif
Nick Coghland6009512014-11-20 21:39:37 +1000199 return 0;
200}
201
Nick Coghlan6ea41862017-06-11 13:16:15 +1000202
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000203/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
204 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000205 initializations fail, a fatal error is issued and the function does
206 not return. On return, the first thread and interpreter state have
207 been created.
208
209 Locking: you must hold the interpreter lock while calling this.
210 (If the lock has not yet been initialized, that's equivalent to
211 having the lock, but you cannot use multiple threads.)
212
213*/
214
215static int
216add_flag(int flag, const char *envs)
217{
218 int env = atoi(envs);
219 if (flag < env)
220 flag = env;
221 if (flag < 1)
222 flag = 1;
223 return flag;
224}
225
226static char*
227get_codec_name(const char *encoding)
228{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200229 const char *name_utf8;
230 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000231 PyObject *codec, *name = NULL;
232
233 codec = _PyCodec_Lookup(encoding);
234 if (!codec)
235 goto error;
236
237 name = _PyObject_GetAttrId(codec, &PyId_name);
238 Py_CLEAR(codec);
239 if (!name)
240 goto error;
241
Serhiy Storchaka06515832016-11-20 09:13:07 +0200242 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000243 if (name_utf8 == NULL)
244 goto error;
245 name_str = _PyMem_RawStrdup(name_utf8);
246 Py_DECREF(name);
247 if (name_str == NULL) {
248 PyErr_NoMemory();
249 return NULL;
250 }
251 return name_str;
252
253error:
254 Py_XDECREF(codec);
255 Py_XDECREF(name);
256 return NULL;
257}
258
259static char*
260get_locale_encoding(void)
261{
262#ifdef MS_WINDOWS
263 char codepage[100];
264 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
265 return get_codec_name(codepage);
266#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
267 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;
Nick Coghland6009512014-11-20 21:39:37 +1000286 PyObject *value;
287
288 /* Import _importlib through its frozen version, _frozen_importlib. */
289 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
290 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
291 }
292 else if (Py_VerboseFlag) {
293 PySys_FormatStderr("import _frozen_importlib # frozen\n");
294 }
295 importlib = PyImport_AddModule("_frozen_importlib");
296 if (importlib == NULL) {
297 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
298 "sys.modules");
299 }
300 interp->importlib = importlib;
301 Py_INCREF(interp->importlib);
302
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300303 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
304 if (interp->import_func == NULL)
305 Py_FatalError("Py_Initialize: __import__ not found");
306 Py_INCREF(interp->import_func);
307
Victor Stinnercd6e6942015-09-18 09:11:57 +0200308 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000309 impmod = PyInit_imp();
310 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200311 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000312 }
313 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200314 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000315 }
Eric Snow86b7afd2017-09-04 17:54:09 -0600316 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000317 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
318 }
319
Victor Stinnercd6e6942015-09-18 09:11:57 +0200320 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000321 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200322 if (value != NULL) {
323 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700324 value = PyObject_CallMethod(importlib,
325 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200326 }
Nick Coghland6009512014-11-20 21:39:37 +1000327 if (value == NULL) {
328 PyErr_Print();
329 Py_FatalError("Py_Initialize: importlib install failed");
330 }
331 Py_DECREF(value);
332 Py_DECREF(impmod);
333
334 _PyImportZip_Init();
335}
336
Eric Snow1abcf672017-05-23 21:46:51 -0700337static void
338initexternalimport(PyInterpreterState *interp)
339{
340 PyObject *value;
341 value = PyObject_CallMethod(interp->importlib,
342 "_install_external_importers", "");
343 if (value == NULL) {
344 PyErr_Print();
345 Py_FatalError("Py_EndInitialization: external importer setup failed");
346 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200347 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700348}
Nick Coghland6009512014-11-20 21:39:37 +1000349
Nick Coghlan6ea41862017-06-11 13:16:15 +1000350/* Helper functions to better handle the legacy C locale
351 *
352 * The legacy C locale assumes ASCII as the default text encoding, which
353 * causes problems not only for the CPython runtime, but also other
354 * components like GNU readline.
355 *
356 * Accordingly, when the CLI detects it, it attempts to coerce it to a
357 * more capable UTF-8 based alternative as follows:
358 *
359 * if (_Py_LegacyLocaleDetected()) {
360 * _Py_CoerceLegacyLocale();
361 * }
362 *
363 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
364 *
365 * Locale coercion also impacts the default error handler for the standard
366 * streams: while the usual default is "strict", the default for the legacy
367 * C locale and for any of the coercion target locales is "surrogateescape".
368 */
369
370int
371_Py_LegacyLocaleDetected(void)
372{
373#ifndef MS_WINDOWS
374 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000375 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
376 * the POSIX locale as a simple alias for the C locale, so
377 * we may also want to check for that explicitly.
378 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000379 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
380 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
381#else
382 /* Windows uses code pages instead of locales, so no locale is legacy */
383 return 0;
384#endif
385}
386
Nick Coghlaneb817952017-06-18 12:29:42 +1000387static const char *_C_LOCALE_WARNING =
388 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
389 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
390 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
391 "locales is recommended.\n";
392
393static int
394_legacy_locale_warnings_enabled(void)
395{
396 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
397 return (coerce_c_locale != NULL &&
398 strncmp(coerce_c_locale, "warn", 5) == 0);
399}
400
401static void
402_emit_stderr_warning_for_legacy_locale(void)
403{
404 if (_legacy_locale_warnings_enabled()) {
405 if (_Py_LegacyLocaleDetected()) {
406 fprintf(stderr, "%s", _C_LOCALE_WARNING);
407 }
408 }
409}
410
Nick Coghlan6ea41862017-06-11 13:16:15 +1000411typedef struct _CandidateLocale {
412 const char *locale_name; /* The locale to try as a coercion target */
413} _LocaleCoercionTarget;
414
415static _LocaleCoercionTarget _TARGET_LOCALES[] = {
416 {"C.UTF-8"},
417 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000418 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000419 {NULL}
420};
421
422static char *
423get_default_standard_stream_error_handler(void)
424{
425 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
426 if (ctype_loc != NULL) {
427 /* "surrogateescape" is the default in the legacy C locale */
428 if (strcmp(ctype_loc, "C") == 0) {
429 return "surrogateescape";
430 }
431
432#ifdef PY_COERCE_C_LOCALE
433 /* "surrogateescape" is the default in locale coercion target locales */
434 const _LocaleCoercionTarget *target = NULL;
435 for (target = _TARGET_LOCALES; target->locale_name; target++) {
436 if (strcmp(ctype_loc, target->locale_name) == 0) {
437 return "surrogateescape";
438 }
439 }
440#endif
441 }
442
443 /* Otherwise return NULL to request the typical default error handler */
444 return NULL;
445}
446
447#ifdef PY_COERCE_C_LOCALE
448static const char *_C_LOCALE_COERCION_WARNING =
449 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
450 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
451
452static void
453_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
454{
455 const char *newloc = target->locale_name;
456
457 /* Reset locale back to currently configured defaults */
458 setlocale(LC_ALL, "");
459
460 /* Set the relevant locale environment variable */
461 if (setenv("LC_CTYPE", newloc, 1)) {
462 fprintf(stderr,
463 "Error setting LC_CTYPE, skipping C locale coercion\n");
464 return;
465 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000466 if (_legacy_locale_warnings_enabled()) {
467 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
468 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000469
470 /* Reconfigure with the overridden environment variables */
471 setlocale(LC_ALL, "");
472}
473#endif
474
475void
476_Py_CoerceLegacyLocale(void)
477{
478#ifdef PY_COERCE_C_LOCALE
479 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
480 * the locale settings *before* we try to do anything with the command
481 * line arguments. For cross-platform debugging purposes, we also need
482 * to give end users a way to force even scripts that are otherwise
483 * isolated from their environment to use the legacy ASCII-centric C
484 * locale.
485 *
486 * Ignoring -E and -I is safe from a security perspective, as we only use
487 * the setting to turn *off* the implicit locale coercion, and anyone with
488 * access to the process environment already has the ability to set
489 * `LC_ALL=C` to override the C level locale settings anyway.
490 */
491 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
492 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
493 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
494 const char *locale_override = getenv("LC_ALL");
495 if (locale_override == NULL || *locale_override == '\0') {
496 /* LC_ALL is also not set (or is set to an empty string) */
497 const _LocaleCoercionTarget *target = NULL;
498 for (target = _TARGET_LOCALES; target->locale_name; target++) {
499 const char *new_locale = setlocale(LC_CTYPE,
500 target->locale_name);
501 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000502#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
503 /* Also ensure that nl_langinfo works in this locale */
504 char *codeset = nl_langinfo(CODESET);
505 if (!codeset || *codeset == '\0') {
506 /* CODESET is not set or empty, so skip coercion */
507 new_locale = NULL;
508 setlocale(LC_CTYPE, "");
509 continue;
510 }
511#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000512 /* Successfully configured locale, so make it the default */
513 _coerce_default_locale_settings(target);
514 return;
515 }
516 }
517 }
518 }
519 /* No C locale warning here, as Py_Initialize will emit one later */
520#endif
521}
522
523
Eric Snow1abcf672017-05-23 21:46:51 -0700524/* Global initializations. Can be undone by Py_Finalize(). Don't
525 call this twice without an intervening Py_Finalize() call.
526
527 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
528 must have a corresponding call to Py_Finalize.
529
530 Locking: you must hold the interpreter lock while calling these APIs.
531 (If the lock has not yet been initialized, that's equivalent to
532 having the lock, but you cannot use multiple threads.)
533
534*/
535
536/* Begin interpreter initialization
537 *
538 * On return, the first thread and interpreter state have been created,
539 * but the compiler, signal handling, multithreading and
540 * multiple interpreter support, and codec infrastructure are not yet
541 * available.
542 *
543 * The import system will support builtin and frozen modules only.
544 * The only supported io is writing to sys.stderr
545 *
546 * If any operation invoked by this function fails, a fatal error is
547 * issued and the function does not return.
548 *
549 * Any code invoked from this function should *not* assume it has access
550 * to the Python C API (unless the API is explicitly listed as being
551 * safe to call without calling Py_Initialize first)
552 */
553
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200554/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700555 * Py_ReadConfig and Py_EndInitialization
556 */
557
558void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000559{
560 PyInterpreterState *interp;
561 PyThreadState *tstate;
562 PyObject *bimod, *sysmod, *pstderr;
563 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700564 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700565 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000566
Eric Snow76d5abc2017-09-05 18:26:16 -0700567 _PyRuntime_Initialize();
568
Eric Snow1abcf672017-05-23 21:46:51 -0700569 if (config != NULL) {
570 core_config = *config;
571 }
572
Eric Snow76d5abc2017-09-05 18:26:16 -0700573 if (_PyRuntime.initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700574 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
575 }
Eric Snow76d5abc2017-09-05 18:26:16 -0700576 if (_PyRuntime.core_initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700577 Py_FatalError("Py_InitializeCore: runtime core already initialized");
578 }
579
580 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
581 * threads behave a little more gracefully at interpreter shutdown.
582 * We clobber it here so the new interpreter can start with a clean
583 * slate.
584 *
585 * However, this may still lead to misbehaviour if there are daemon
586 * threads still hanging around from a previous Py_Initialize/Finalize
587 * pair :(
588 */
Eric Snow76d5abc2017-09-05 18:26:16 -0700589 _PyRuntime.finalizing = NULL;
590
591 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
592 fprintf(stderr,
593 "Error in PYTHONMALLOC: unknown allocator \"%s\"!\n",
594 core_config.allocator);
595 exit(1);
596 }
Nick Coghland6009512014-11-20 21:39:37 +1000597
Nick Coghlan6ea41862017-06-11 13:16:15 +1000598#ifdef __ANDROID__
599 /* Passing "" to setlocale() on Android requests the C locale rather
600 * than checking environment variables, so request C.UTF-8 explicitly
601 */
602 setlocale(LC_CTYPE, "C.UTF-8");
603#else
604#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000605 /* Set up the LC_CTYPE locale, so we can obtain
606 the locale's charset without having to switch
607 locales. */
608 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000609 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000610#endif
Nick Coghland6009512014-11-20 21:39:37 +1000611#endif
612
613 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
614 Py_DebugFlag = add_flag(Py_DebugFlag, p);
615 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
616 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
617 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
618 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
619 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
620 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700621 /* The variable is only tested for existence here;
622 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000623 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
624 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700625#ifdef MS_WINDOWS
626 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
627 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700628 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
629 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700630#endif
Nick Coghland6009512014-11-20 21:39:37 +1000631
Eric Snow1abcf672017-05-23 21:46:51 -0700632 _Py_HashRandomization_Init(&core_config);
633 if (!core_config.use_hash_seed || core_config.hash_seed) {
634 /* Random or non-zero hash seed */
635 Py_HashRandomizationFlag = 1;
636 }
Nick Coghland6009512014-11-20 21:39:37 +1000637
Eric Snow76d5abc2017-09-05 18:26:16 -0700638 _PyInterpreterState_Enable(&_PyRuntime);
Nick Coghland6009512014-11-20 21:39:37 +1000639 interp = PyInterpreterState_New();
640 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700641 Py_FatalError("Py_InitializeCore: can't make main interpreter");
642 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700643 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000644
645 tstate = PyThreadState_New(interp);
646 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700647 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000648 (void) PyThreadState_Swap(tstate);
649
650#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000651 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000652 destroying the GIL might fail when it is being referenced from
653 another running thread (see issue #9901).
654 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000655 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000656 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000657 /* Auto-thread-state API */
658 _PyGILState_Init(interp, tstate);
659#endif /* WITH_THREAD */
660
661 _Py_ReadyTypes();
662
663 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700664 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000665
666 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700667 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000668
669 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700670 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000671
672 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700673 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000674
Eric Snow86b7afd2017-09-04 17:54:09 -0600675 PyObject *modules = PyDict_New();
676 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700677 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000678
Eric Snow86b7afd2017-09-04 17:54:09 -0600679 sysmod = _PySys_BeginInit();
680 if (sysmod == NULL)
681 Py_FatalError("Py_InitializeCore: can't initialize sys");
682 interp->sysdict = PyModule_GetDict(sysmod);
683 if (interp->sysdict == NULL)
684 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
685 Py_INCREF(interp->sysdict);
686 PyDict_SetItemString(interp->sysdict, "modules", modules);
687 _PyImport_FixupBuiltin(sysmod, "sys", modules);
688
Nick Coghland6009512014-11-20 21:39:37 +1000689 /* Init Unicode implementation; relies on the codec registry */
690 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700691 Py_FatalError("Py_InitializeCore: can't initialize unicode");
692
Nick Coghland6009512014-11-20 21:39:37 +1000693 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700694 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000695
696 bimod = _PyBuiltin_Init();
697 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700698 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snow86b7afd2017-09-04 17:54:09 -0600699 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000700 interp->builtins = PyModule_GetDict(bimod);
701 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700702 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000703 Py_INCREF(interp->builtins);
704
705 /* initialize builtin exceptions */
706 _PyExc_Init(bimod);
707
Nick Coghland6009512014-11-20 21:39:37 +1000708 /* Set up a preliminary stderr printer until we have enough
709 infrastructure for the io module in place. */
710 pstderr = PyFile_NewStdPrinter(fileno(stderr));
711 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700712 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000713 _PySys_SetObjectId(&PyId_stderr, pstderr);
714 PySys_SetObject("__stderr__", pstderr);
715 Py_DECREF(pstderr);
716
717 _PyImport_Init();
718
719 _PyImportHooks_Init();
720
721 /* Initialize _warnings. */
722 _PyWarnings_Init();
723
Eric Snow1abcf672017-05-23 21:46:51 -0700724 /* This call sets up builtin and frozen import support */
725 if (!interp->core_config._disable_importlib) {
726 initimport(interp, sysmod);
727 }
728
729 /* Only when we get here is the runtime core fully initialized */
Eric Snow76d5abc2017-09-05 18:26:16 -0700730 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700731}
732
Eric Snowc7ec9982017-05-23 23:00:52 -0700733/* Read configuration settings from standard locations
734 *
735 * This function doesn't make any changes to the interpreter state - it
736 * merely populates any missing configuration settings. This allows an
737 * embedding application to completely override a config option by
738 * setting it before calling this function, or else modify the default
739 * setting before passing the fully populated config to Py_EndInitialization.
740 *
741 * More advanced selective initialization tricks are possible by calling
742 * this function multiple times with various preconfigured settings.
743 */
744
745int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
746{
747 /* Signal handlers are installed by default */
748 if (config->install_signal_handlers < 0) {
749 config->install_signal_handlers = 1;
750 }
751
752 return 0;
753}
754
755/* Update interpreter state based on supplied configuration settings
756 *
757 * After calling this function, most of the restrictions on the interpreter
758 * are lifted. The only remaining incomplete settings are those related
759 * to the main module (sys.argv[0], __main__ metadata)
760 *
761 * Calling this when the interpreter is not initializing, is already
762 * initialized or without a valid current thread state is a fatal error.
763 * Other errors should be reported as normal Python exceptions with a
764 * non-zero return code.
765 */
766int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700767{
768 PyInterpreterState *interp;
769 PyThreadState *tstate;
770
Eric Snow76d5abc2017-09-05 18:26:16 -0700771 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700772 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
773 }
Eric Snow76d5abc2017-09-05 18:26:16 -0700774 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700775 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
776 }
777
Eric Snow1abcf672017-05-23 21:46:51 -0700778 /* Get current thread state and interpreter pointer */
779 tstate = PyThreadState_GET();
780 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700781 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700782 interp = tstate->interp;
783 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700784 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700785
786 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700787 interp->config = *config;
788
Eric Snow1abcf672017-05-23 21:46:51 -0700789 if (interp->core_config._disable_importlib) {
790 /* Special mode for freeze_importlib: run with no import system
791 *
792 * This means anything which needs support from extension modules
793 * or pure Python code in the standard library won't work.
794 */
Eric Snow76d5abc2017-09-05 18:26:16 -0700795 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700796 return 0;
797 }
798 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000799
Victor Stinner13019fd2015-04-03 13:10:54 +0200800 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700801 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200802
Eric Snow1abcf672017-05-23 21:46:51 -0700803 /* Finish setting up the sys module and import system */
804 /* GetPath may initialize state that _PySys_EndInit locks
805 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700806 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700807 PySys_SetPath(Py_GetPath());
808 if (_PySys_EndInit(interp->sysdict) < 0)
809 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700810 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000811
812 /* initialize the faulthandler module */
813 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700814 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000815
Nick Coghland6009512014-11-20 21:39:37 +1000816 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700817 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000818
Eric Snowc7ec9982017-05-23 23:00:52 -0700819 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000820 initsigs(); /* Signal handling stuff, including initintr() */
821
822 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700823 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000824
825 initmain(interp); /* Module __main__ */
826 if (initstdio() < 0)
827 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700828 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000829
830 /* Initialize warnings. */
831 if (PySys_HasWarnOptions()) {
832 PyObject *warnings_module = PyImport_ImportModule("warnings");
833 if (warnings_module == NULL) {
834 fprintf(stderr, "'import warnings' failed; traceback:\n");
835 PyErr_Print();
836 }
837 Py_XDECREF(warnings_module);
838 }
839
Eric Snow76d5abc2017-09-05 18:26:16 -0700840 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700841
Nick Coghland6009512014-11-20 21:39:37 +1000842 if (!Py_NoSiteFlag)
843 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700844
Eric Snowc7ec9982017-05-23 23:00:52 -0700845 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000846}
847
Eric Snowc7ec9982017-05-23 23:00:52 -0700848#undef _INIT_DEBUG_PRINT
849
Nick Coghland6009512014-11-20 21:39:37 +1000850void
Eric Snow1abcf672017-05-23 21:46:51 -0700851_Py_InitializeEx_Private(int install_sigs, int install_importlib)
852{
853 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700854 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700855
856 /* TODO: Moar config options! */
857 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
858 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700859 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700860 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700861 /* TODO: Print any exceptions raised by these operations */
862 if (_Py_ReadMainInterpreterConfig(&config))
863 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
864 if (_Py_InitializeMainInterpreter(&config))
865 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700866}
867
868
869void
Nick Coghland6009512014-11-20 21:39:37 +1000870Py_InitializeEx(int install_sigs)
871{
872 _Py_InitializeEx_Private(install_sigs, 1);
873}
874
875void
876Py_Initialize(void)
877{
878 Py_InitializeEx(1);
879}
880
881
882#ifdef COUNT_ALLOCS
883extern void dump_counts(FILE*);
884#endif
885
886/* Flush stdout and stderr */
887
888static int
889file_is_closed(PyObject *fobj)
890{
891 int r;
892 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
893 if (tmp == NULL) {
894 PyErr_Clear();
895 return 0;
896 }
897 r = PyObject_IsTrue(tmp);
898 Py_DECREF(tmp);
899 if (r < 0)
900 PyErr_Clear();
901 return r > 0;
902}
903
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000904static int
Nick Coghland6009512014-11-20 21:39:37 +1000905flush_std_files(void)
906{
907 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
908 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
909 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000910 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000911
912 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700913 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000914 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000915 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000916 status = -1;
917 }
Nick Coghland6009512014-11-20 21:39:37 +1000918 else
919 Py_DECREF(tmp);
920 }
921
922 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700923 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000924 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000925 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000926 status = -1;
927 }
Nick Coghland6009512014-11-20 21:39:37 +1000928 else
929 Py_DECREF(tmp);
930 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000931
932 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000933}
934
935/* Undo the effect of Py_Initialize().
936
937 Beware: if multiple interpreter and/or thread states exist, these
938 are not wiped out; only the current thread and interpreter state
939 are deleted. But since everything else is deleted, those other
940 interpreter and thread states should no longer be used.
941
942 (XXX We should do better, e.g. wipe out all interpreters and
943 threads.)
944
945 Locking: as above.
946
947*/
948
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000949int
950Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000951{
952 PyInterpreterState *interp;
953 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000954 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000955
Eric Snow76d5abc2017-09-05 18:26:16 -0700956 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000957 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000958
959 wait_for_thread_shutdown();
960
961 /* The interpreter is still entirely intact at this point, and the
962 * exit funcs may be relying on that. In particular, if some thread
963 * or exit func is still waiting to do an import, the import machinery
964 * expects Py_IsInitialized() to return true. So don't say the
965 * interpreter is uninitialized until after the exit funcs have run.
966 * Note that Threading.py uses an exit func to do a join on all the
967 * threads created thru it, so this also protects pending imports in
968 * the threads created via Threading.
969 */
970 call_py_exitfuncs();
971
972 /* Get current thread state and interpreter pointer */
973 tstate = PyThreadState_GET();
974 interp = tstate->interp;
975
976 /* Remaining threads (e.g. daemon threads) will automatically exit
977 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow76d5abc2017-09-05 18:26:16 -0700978 _PyRuntime.finalizing = tstate;
979 _PyRuntime.initialized = 0;
980 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000981
Victor Stinnere0deff32015-03-24 13:46:18 +0100982 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000983 if (flush_std_files() < 0) {
984 status = -1;
985 }
Nick Coghland6009512014-11-20 21:39:37 +1000986
987 /* Disable signal handling */
988 PyOS_FiniInterrupts();
989
990 /* Collect garbage. This may call finalizers; it's nice to call these
991 * before all modules are destroyed.
992 * XXX If a __del__ or weakref callback is triggered here, and tries to
993 * XXX import a module, bad things can happen, because Python no
994 * XXX longer believes it's initialized.
995 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
996 * XXX is easy to provoke that way. I've also seen, e.g.,
997 * XXX Exception exceptions.ImportError: 'No module named sha'
998 * XXX in <function callback at 0x008F5718> ignored
999 * XXX but I'm unclear on exactly how that one happens. In any case,
1000 * XXX I haven't seen a real-life report of either of these.
1001 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001002 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001003#ifdef COUNT_ALLOCS
1004 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1005 each collection might release some types from the type
1006 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001007 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001008 /* nothing */;
1009#endif
1010 /* Destroy all modules */
1011 PyImport_Cleanup();
1012
Victor Stinnere0deff32015-03-24 13:46:18 +01001013 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001014 if (flush_std_files() < 0) {
1015 status = -1;
1016 }
Nick Coghland6009512014-11-20 21:39:37 +10001017
1018 /* Collect final garbage. This disposes of cycles created by
1019 * class definitions, for example.
1020 * XXX This is disabled because it caused too many problems. If
1021 * XXX a __del__ or weakref callback triggers here, Python code has
1022 * XXX a hard time running, because even the sys module has been
1023 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1024 * XXX One symptom is a sequence of information-free messages
1025 * XXX coming from threads (if a __del__ or callback is invoked,
1026 * XXX other threads can execute too, and any exception they encounter
1027 * XXX triggers a comedy of errors as subsystem after subsystem
1028 * XXX fails to find what it *expects* to find in sys to help report
1029 * XXX the exception and consequent unexpected failures). I've also
1030 * XXX seen segfaults then, after adding print statements to the
1031 * XXX Python code getting called.
1032 */
1033#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001034 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001035#endif
1036
1037 /* Disable tracemalloc after all Python objects have been destroyed,
1038 so it is possible to use tracemalloc in objects destructor. */
1039 _PyTraceMalloc_Fini();
1040
1041 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1042 _PyImport_Fini();
1043
1044 /* Cleanup typeobject.c's internal caches. */
1045 _PyType_Fini();
1046
1047 /* unload faulthandler module */
1048 _PyFaulthandler_Fini();
1049
1050 /* Debugging stuff */
1051#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001052 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001053#endif
1054 /* dump hash stats */
1055 _PyHash_Fini();
1056
1057 _PY_DEBUG_PRINT_TOTAL_REFS();
1058
1059#ifdef Py_TRACE_REFS
1060 /* Display all objects still alive -- this can invoke arbitrary
1061 * __repr__ overrides, so requires a mostly-intact interpreter.
1062 * Alas, a lot of stuff may still be alive now that will be cleaned
1063 * up later.
1064 */
1065 if (Py_GETENV("PYTHONDUMPREFS"))
1066 _Py_PrintReferences(stderr);
1067#endif /* Py_TRACE_REFS */
1068
1069 /* Clear interpreter state and all thread states. */
1070 PyInterpreterState_Clear(interp);
1071
1072 /* Now we decref the exception classes. After this point nothing
1073 can raise an exception. That's okay, because each Fini() method
1074 below has been checked to make sure no exceptions are ever
1075 raised.
1076 */
1077
1078 _PyExc_Fini();
1079
1080 /* Sundry finalizers */
1081 PyMethod_Fini();
1082 PyFrame_Fini();
1083 PyCFunction_Fini();
1084 PyTuple_Fini();
1085 PyList_Fini();
1086 PySet_Fini();
1087 PyBytes_Fini();
1088 PyByteArray_Fini();
1089 PyLong_Fini();
1090 PyFloat_Fini();
1091 PyDict_Fini();
1092 PySlice_Fini();
1093 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001094 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001095 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001096 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001097
1098 /* Cleanup Unicode implementation */
1099 _PyUnicode_Fini();
1100
1101 /* reset file system default encoding */
1102 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1103 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1104 Py_FileSystemDefaultEncoding = NULL;
1105 }
1106
1107 /* XXX Still allocated:
1108 - various static ad-hoc pointers to interned strings
1109 - int and float free list blocks
1110 - whatever various modules and libraries allocate
1111 */
1112
1113 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1114
1115 /* Cleanup auto-thread-state */
1116#ifdef WITH_THREAD
1117 _PyGILState_Fini();
1118#endif /* WITH_THREAD */
1119
1120 /* Delete current thread. After this, many C API calls become crashy. */
1121 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001122
Nick Coghland6009512014-11-20 21:39:37 +10001123 PyInterpreterState_Delete(interp);
1124
1125#ifdef Py_TRACE_REFS
1126 /* Display addresses (& refcnts) of all objects still alive.
1127 * An address can be used to find the repr of the object, printed
1128 * above by _Py_PrintReferences.
1129 */
1130 if (Py_GETENV("PYTHONDUMPREFS"))
1131 _Py_PrintReferenceAddresses(stderr);
1132#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001133#ifdef WITH_PYMALLOC
1134 if (_PyMem_PymallocEnabled()) {
1135 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1136 if (opt != NULL && *opt != '\0')
1137 _PyObject_DebugMallocStats(stderr);
1138 }
Nick Coghland6009512014-11-20 21:39:37 +10001139#endif
1140
1141 call_ll_exitfuncs();
Eric Snow76d5abc2017-09-05 18:26:16 -07001142 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001143 return status;
1144}
1145
1146void
1147Py_Finalize(void)
1148{
1149 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001150}
1151
1152/* Create and initialize a new interpreter and thread, and return the
1153 new thread. This requires that Py_Initialize() has been called
1154 first.
1155
1156 Unsuccessful initialization yields a NULL pointer. Note that *no*
1157 exception information is available even in this case -- the
1158 exception information is held in the thread, and there is no
1159 thread.
1160
1161 Locking: as above.
1162
1163*/
1164
1165PyThreadState *
1166Py_NewInterpreter(void)
1167{
1168 PyInterpreterState *interp;
1169 PyThreadState *tstate, *save_tstate;
1170 PyObject *bimod, *sysmod;
1171
Eric Snow76d5abc2017-09-05 18:26:16 -07001172 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001173 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1174
Victor Stinnerd7292b52016-06-17 12:29:00 +02001175#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +01001176 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1177 interpreters: disable PyGILState_Check(). */
1178 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +03001179#endif
Victor Stinner8a1be612016-03-14 22:07:55 +01001180
Nick Coghland6009512014-11-20 21:39:37 +10001181 interp = PyInterpreterState_New();
1182 if (interp == NULL)
1183 return NULL;
1184
1185 tstate = PyThreadState_New(interp);
1186 if (tstate == NULL) {
1187 PyInterpreterState_Delete(interp);
1188 return NULL;
1189 }
1190
1191 save_tstate = PyThreadState_Swap(tstate);
1192
Eric Snow1abcf672017-05-23 21:46:51 -07001193 /* Copy the current interpreter config into the new interpreter */
1194 if (save_tstate != NULL) {
1195 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001196 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001197 } else {
1198 /* No current thread state, copy from the main interpreter */
1199 PyInterpreterState *main_interp = PyInterpreterState_Main();
1200 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001201 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001202 }
1203
Nick Coghland6009512014-11-20 21:39:37 +10001204 /* XXX The following is lax in error checking */
1205
Eric Snow86b7afd2017-09-04 17:54:09 -06001206 PyObject *modules = PyDict_New();
1207 if (modules == NULL)
1208 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +10001209
Eric Snow86b7afd2017-09-04 17:54:09 -06001210 sysmod = _PyImport_FindBuiltin("sys", modules);
1211 if (sysmod != NULL) {
1212 interp->sysdict = PyModule_GetDict(sysmod);
1213 if (interp->sysdict == NULL)
1214 goto handle_error;
1215 Py_INCREF(interp->sysdict);
1216 PyDict_SetItemString(interp->sysdict, "modules", modules);
1217 PySys_SetPath(Py_GetPath());
1218 _PySys_EndInit(interp->sysdict);
1219 }
1220
1221 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001222 if (bimod != NULL) {
1223 interp->builtins = PyModule_GetDict(bimod);
1224 if (interp->builtins == NULL)
1225 goto handle_error;
1226 Py_INCREF(interp->builtins);
1227 }
1228
1229 /* initialize builtin exceptions */
1230 _PyExc_Init(bimod);
1231
Nick Coghland6009512014-11-20 21:39:37 +10001232 if (bimod != NULL && sysmod != NULL) {
1233 PyObject *pstderr;
1234
Nick Coghland6009512014-11-20 21:39:37 +10001235 /* Set up a preliminary stderr printer until we have enough
1236 infrastructure for the io module in place. */
1237 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1238 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001239 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001240 _PySys_SetObjectId(&PyId_stderr, pstderr);
1241 PySys_SetObject("__stderr__", pstderr);
1242 Py_DECREF(pstderr);
1243
1244 _PyImportHooks_Init();
1245
Eric Snow1abcf672017-05-23 21:46:51 -07001246 initimport(interp, sysmod);
1247 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001248
1249 if (initfsencoding(interp) < 0)
1250 goto handle_error;
1251
1252 if (initstdio() < 0)
1253 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001254 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001255 initmain(interp);
1256 if (!Py_NoSiteFlag)
1257 initsite();
1258 }
1259
1260 if (!PyErr_Occurred())
1261 return tstate;
1262
1263handle_error:
1264 /* Oops, it didn't work. Undo it all. */
1265
1266 PyErr_PrintEx(0);
1267 PyThreadState_Clear(tstate);
1268 PyThreadState_Swap(save_tstate);
1269 PyThreadState_Delete(tstate);
1270 PyInterpreterState_Delete(interp);
1271
1272 return NULL;
1273}
1274
1275/* Delete an interpreter and its last thread. This requires that the
1276 given thread state is current, that the thread has no remaining
1277 frames, and that it is its interpreter's only remaining thread.
1278 It is a fatal error to violate these constraints.
1279
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001280 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001281 everything, regardless.)
1282
1283 Locking: as above.
1284
1285*/
1286
1287void
1288Py_EndInterpreter(PyThreadState *tstate)
1289{
1290 PyInterpreterState *interp = tstate->interp;
1291
1292 if (tstate != PyThreadState_GET())
1293 Py_FatalError("Py_EndInterpreter: thread is not current");
1294 if (tstate->frame != NULL)
1295 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1296
1297 wait_for_thread_shutdown();
1298
1299 if (tstate != interp->tstate_head || tstate->next != NULL)
1300 Py_FatalError("Py_EndInterpreter: not the last thread");
1301
1302 PyImport_Cleanup();
1303 PyInterpreterState_Clear(interp);
1304 PyThreadState_Swap(NULL);
1305 PyInterpreterState_Delete(interp);
1306}
1307
1308#ifdef MS_WINDOWS
1309static wchar_t *progname = L"python";
1310#else
1311static wchar_t *progname = L"python3";
1312#endif
1313
1314void
1315Py_SetProgramName(wchar_t *pn)
1316{
1317 if (pn && *pn)
1318 progname = pn;
1319}
1320
1321wchar_t *
1322Py_GetProgramName(void)
1323{
1324 return progname;
1325}
1326
1327static wchar_t *default_home = NULL;
1328static wchar_t env_home[MAXPATHLEN+1];
1329
1330void
1331Py_SetPythonHome(wchar_t *home)
1332{
1333 default_home = home;
1334}
1335
1336wchar_t *
1337Py_GetPythonHome(void)
1338{
1339 wchar_t *home = default_home;
1340 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1341 char* chome = Py_GETENV("PYTHONHOME");
1342 if (chome) {
1343 size_t size = Py_ARRAY_LENGTH(env_home);
1344 size_t r = mbstowcs(env_home, chome, size);
1345 if (r != (size_t)-1 && r < size)
1346 home = env_home;
1347 }
1348
1349 }
1350 return home;
1351}
1352
1353/* Create __main__ module */
1354
1355static void
1356initmain(PyInterpreterState *interp)
1357{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001358 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001359 m = PyImport_AddModule("__main__");
1360 if (m == NULL)
1361 Py_FatalError("can't create __main__ module");
1362 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001363 ann_dict = PyDict_New();
1364 if ((ann_dict == NULL) ||
1365 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1366 Py_FatalError("Failed to initialize __main__.__annotations__");
1367 }
1368 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001369 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1370 PyObject *bimod = PyImport_ImportModule("builtins");
1371 if (bimod == NULL) {
1372 Py_FatalError("Failed to retrieve builtins module");
1373 }
1374 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1375 Py_FatalError("Failed to initialize __main__.__builtins__");
1376 }
1377 Py_DECREF(bimod);
1378 }
1379 /* Main is a little special - imp.is_builtin("__main__") will return
1380 * False, but BuiltinImporter is still the most appropriate initial
1381 * setting for its __loader__ attribute. A more suitable value will
1382 * be set if __main__ gets further initialized later in the startup
1383 * process.
1384 */
1385 loader = PyDict_GetItemString(d, "__loader__");
1386 if (loader == NULL || loader == Py_None) {
1387 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1388 "BuiltinImporter");
1389 if (loader == NULL) {
1390 Py_FatalError("Failed to retrieve BuiltinImporter");
1391 }
1392 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1393 Py_FatalError("Failed to initialize __main__.__loader__");
1394 }
1395 Py_DECREF(loader);
1396 }
1397}
1398
1399static int
1400initfsencoding(PyInterpreterState *interp)
1401{
1402 PyObject *codec;
1403
Steve Dowercc16be82016-09-08 10:35:16 -07001404#ifdef MS_WINDOWS
1405 if (Py_LegacyWindowsFSEncodingFlag)
1406 {
1407 Py_FileSystemDefaultEncoding = "mbcs";
1408 Py_FileSystemDefaultEncodeErrors = "replace";
1409 }
1410 else
1411 {
1412 Py_FileSystemDefaultEncoding = "utf-8";
1413 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1414 }
1415#else
Nick Coghland6009512014-11-20 21:39:37 +10001416 if (Py_FileSystemDefaultEncoding == NULL)
1417 {
1418 Py_FileSystemDefaultEncoding = get_locale_encoding();
1419 if (Py_FileSystemDefaultEncoding == NULL)
1420 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1421
1422 Py_HasFileSystemDefaultEncoding = 0;
1423 interp->fscodec_initialized = 1;
1424 return 0;
1425 }
Steve Dowercc16be82016-09-08 10:35:16 -07001426#endif
Nick Coghland6009512014-11-20 21:39:37 +10001427
1428 /* the encoding is mbcs, utf-8 or ascii */
1429 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1430 if (!codec) {
1431 /* Such error can only occurs in critical situations: no more
1432 * memory, import a module of the standard library failed,
1433 * etc. */
1434 return -1;
1435 }
1436 Py_DECREF(codec);
1437 interp->fscodec_initialized = 1;
1438 return 0;
1439}
1440
1441/* Import the site module (not into __main__ though) */
1442
1443static void
1444initsite(void)
1445{
1446 PyObject *m;
1447 m = PyImport_ImportModule("site");
1448 if (m == NULL) {
1449 fprintf(stderr, "Failed to import the site module\n");
1450 PyErr_Print();
1451 Py_Finalize();
1452 exit(1);
1453 }
1454 else {
1455 Py_DECREF(m);
1456 }
1457}
1458
Victor Stinner874dbe82015-09-04 17:29:57 +02001459/* Check if a file descriptor is valid or not.
1460 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1461static int
1462is_valid_fd(int fd)
1463{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001464#ifdef __APPLE__
1465 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1466 and the other side of the pipe is closed, dup(1) succeed, whereas
1467 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1468 such error. */
1469 struct stat st;
1470 return (fstat(fd, &st) == 0);
1471#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001472 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001473 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001474 return 0;
1475 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001476 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1477 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1478 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001479 fd2 = dup(fd);
1480 if (fd2 >= 0)
1481 close(fd2);
1482 _Py_END_SUPPRESS_IPH
1483 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001484#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001485}
1486
1487/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001488static PyObject*
1489create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001490 int fd, int write_mode, const char* name,
1491 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001492{
1493 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1494 const char* mode;
1495 const char* newline;
1496 PyObject *line_buffering;
1497 int buffering, isatty;
1498 _Py_IDENTIFIER(open);
1499 _Py_IDENTIFIER(isatty);
1500 _Py_IDENTIFIER(TextIOWrapper);
1501 _Py_IDENTIFIER(mode);
1502
Victor Stinner874dbe82015-09-04 17:29:57 +02001503 if (!is_valid_fd(fd))
1504 Py_RETURN_NONE;
1505
Nick Coghland6009512014-11-20 21:39:37 +10001506 /* stdin is always opened in buffered mode, first because it shouldn't
1507 make a difference in common use cases, second because TextIOWrapper
1508 depends on the presence of a read1() method which only exists on
1509 buffered streams.
1510 */
1511 if (Py_UnbufferedStdioFlag && write_mode)
1512 buffering = 0;
1513 else
1514 buffering = -1;
1515 if (write_mode)
1516 mode = "wb";
1517 else
1518 mode = "rb";
1519 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1520 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001521 Py_None, Py_None, /* encoding, errors */
1522 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001523 if (buf == NULL)
1524 goto error;
1525
1526 if (buffering) {
1527 _Py_IDENTIFIER(raw);
1528 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1529 if (raw == NULL)
1530 goto error;
1531 }
1532 else {
1533 raw = buf;
1534 Py_INCREF(raw);
1535 }
1536
Steve Dower39294992016-08-30 21:22:36 -07001537#ifdef MS_WINDOWS
1538 /* Windows console IO is always UTF-8 encoded */
1539 if (PyWindowsConsoleIO_Check(raw))
1540 encoding = "utf-8";
1541#endif
1542
Nick Coghland6009512014-11-20 21:39:37 +10001543 text = PyUnicode_FromString(name);
1544 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1545 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001546 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001547 if (res == NULL)
1548 goto error;
1549 isatty = PyObject_IsTrue(res);
1550 Py_DECREF(res);
1551 if (isatty == -1)
1552 goto error;
1553 if (isatty || Py_UnbufferedStdioFlag)
1554 line_buffering = Py_True;
1555 else
1556 line_buffering = Py_False;
1557
1558 Py_CLEAR(raw);
1559 Py_CLEAR(text);
1560
1561#ifdef MS_WINDOWS
1562 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1563 newlines to "\n".
1564 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1565 newline = NULL;
1566#else
1567 /* sys.stdin: split lines at "\n".
1568 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1569 newline = "\n";
1570#endif
1571
1572 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1573 buf, encoding, errors,
1574 newline, line_buffering);
1575 Py_CLEAR(buf);
1576 if (stream == NULL)
1577 goto error;
1578
1579 if (write_mode)
1580 mode = "w";
1581 else
1582 mode = "r";
1583 text = PyUnicode_FromString(mode);
1584 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1585 goto error;
1586 Py_CLEAR(text);
1587 return stream;
1588
1589error:
1590 Py_XDECREF(buf);
1591 Py_XDECREF(stream);
1592 Py_XDECREF(text);
1593 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001594
Victor Stinner874dbe82015-09-04 17:29:57 +02001595 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1596 /* Issue #24891: the file descriptor was closed after the first
1597 is_valid_fd() check was called. Ignore the OSError and set the
1598 stream to None. */
1599 PyErr_Clear();
1600 Py_RETURN_NONE;
1601 }
1602 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001603}
1604
1605/* Initialize sys.stdin, stdout, stderr and builtins.open */
1606static int
1607initstdio(void)
1608{
1609 PyObject *iomod = NULL, *wrapper;
1610 PyObject *bimod = NULL;
1611 PyObject *m;
1612 PyObject *std = NULL;
1613 int status = 0, fd;
1614 PyObject * encoding_attr;
1615 char *pythonioencoding = NULL, *encoding, *errors;
1616
1617 /* Hack to avoid a nasty recursion issue when Python is invoked
1618 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1619 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1620 goto error;
1621 }
1622 Py_DECREF(m);
1623
1624 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1625 goto error;
1626 }
1627 Py_DECREF(m);
1628
1629 if (!(bimod = PyImport_ImportModule("builtins"))) {
1630 goto error;
1631 }
1632
1633 if (!(iomod = PyImport_ImportModule("io"))) {
1634 goto error;
1635 }
1636 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1637 goto error;
1638 }
1639
1640 /* Set builtins.open */
1641 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1642 Py_DECREF(wrapper);
1643 goto error;
1644 }
1645 Py_DECREF(wrapper);
1646
1647 encoding = _Py_StandardStreamEncoding;
1648 errors = _Py_StandardStreamErrors;
1649 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001650 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1651 if (pythonioencoding) {
1652 char *err;
1653 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1654 if (pythonioencoding == NULL) {
1655 PyErr_NoMemory();
1656 goto error;
1657 }
1658 err = strchr(pythonioencoding, ':');
1659 if (err) {
1660 *err = '\0';
1661 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001662 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001663 errors = err;
1664 }
1665 }
1666 if (*pythonioencoding && !encoding) {
1667 encoding = pythonioencoding;
1668 }
1669 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001670 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001671 /* Choose the default error handler based on the current locale */
1672 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001673 }
Nick Coghland6009512014-11-20 21:39:37 +10001674 }
1675
1676 /* Set sys.stdin */
1677 fd = fileno(stdin);
1678 /* Under some conditions stdin, stdout and stderr may not be connected
1679 * and fileno() may point to an invalid file descriptor. For example
1680 * GUI apps don't have valid standard streams by default.
1681 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001682 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1683 if (std == NULL)
1684 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001685 PySys_SetObject("__stdin__", std);
1686 _PySys_SetObjectId(&PyId_stdin, std);
1687 Py_DECREF(std);
1688
1689 /* Set sys.stdout */
1690 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001691 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1692 if (std == NULL)
1693 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001694 PySys_SetObject("__stdout__", std);
1695 _PySys_SetObjectId(&PyId_stdout, std);
1696 Py_DECREF(std);
1697
1698#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1699 /* Set sys.stderr, replaces the preliminary stderr */
1700 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001701 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1702 if (std == NULL)
1703 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001704
1705 /* Same as hack above, pre-import stderr's codec to avoid recursion
1706 when import.c tries to write to stderr in verbose mode. */
1707 encoding_attr = PyObject_GetAttrString(std, "encoding");
1708 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001709 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001710 if (std_encoding != NULL) {
1711 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1712 Py_XDECREF(codec_info);
1713 }
1714 Py_DECREF(encoding_attr);
1715 }
1716 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1717
1718 if (PySys_SetObject("__stderr__", std) < 0) {
1719 Py_DECREF(std);
1720 goto error;
1721 }
1722 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1723 Py_DECREF(std);
1724 goto error;
1725 }
1726 Py_DECREF(std);
1727#endif
1728
1729 if (0) {
1730 error:
1731 status = -1;
1732 }
1733
1734 /* We won't need them anymore. */
1735 if (_Py_StandardStreamEncoding) {
1736 PyMem_RawFree(_Py_StandardStreamEncoding);
1737 _Py_StandardStreamEncoding = NULL;
1738 }
1739 if (_Py_StandardStreamErrors) {
1740 PyMem_RawFree(_Py_StandardStreamErrors);
1741 _Py_StandardStreamErrors = NULL;
1742 }
1743 PyMem_Free(pythonioencoding);
1744 Py_XDECREF(bimod);
1745 Py_XDECREF(iomod);
1746 return status;
1747}
1748
1749
Victor Stinner10dc4842015-03-24 12:01:30 +01001750static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001751_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001752{
Victor Stinner10dc4842015-03-24 12:01:30 +01001753 fputc('\n', stderr);
1754 fflush(stderr);
1755
1756 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001757 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001758}
Victor Stinner791da1c2016-03-14 16:53:12 +01001759
1760/* Print the current exception (if an exception is set) with its traceback,
1761 or display the current Python stack.
1762
1763 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1764 called on catastrophic cases.
1765
1766 Return 1 if the traceback was displayed, 0 otherwise. */
1767
1768static int
1769_Py_FatalError_PrintExc(int fd)
1770{
1771 PyObject *ferr, *res;
1772 PyObject *exception, *v, *tb;
1773 int has_tb;
1774
1775 if (PyThreadState_GET() == NULL) {
1776 /* The GIL is released: trying to acquire it is likely to deadlock,
1777 just give up. */
1778 return 0;
1779 }
1780
1781 PyErr_Fetch(&exception, &v, &tb);
1782 if (exception == NULL) {
1783 /* No current exception */
1784 return 0;
1785 }
1786
1787 ferr = _PySys_GetObjectId(&PyId_stderr);
1788 if (ferr == NULL || ferr == Py_None) {
1789 /* sys.stderr is not set yet or set to None,
1790 no need to try to display the exception */
1791 return 0;
1792 }
1793
1794 PyErr_NormalizeException(&exception, &v, &tb);
1795 if (tb == NULL) {
1796 tb = Py_None;
1797 Py_INCREF(tb);
1798 }
1799 PyException_SetTraceback(v, tb);
1800 if (exception == NULL) {
1801 /* PyErr_NormalizeException() failed */
1802 return 0;
1803 }
1804
1805 has_tb = (tb != Py_None);
1806 PyErr_Display(exception, v, tb);
1807 Py_XDECREF(exception);
1808 Py_XDECREF(v);
1809 Py_XDECREF(tb);
1810
1811 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001812 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001813 if (res == NULL)
1814 PyErr_Clear();
1815 else
1816 Py_DECREF(res);
1817
1818 return has_tb;
1819}
1820
Nick Coghland6009512014-11-20 21:39:37 +10001821/* Print fatal error message and abort */
1822
1823void
1824Py_FatalError(const char *msg)
1825{
1826 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001827 static int reentrant = 0;
1828#ifdef MS_WINDOWS
1829 size_t len;
1830 WCHAR* buffer;
1831 size_t i;
1832#endif
1833
1834 if (reentrant) {
1835 /* Py_FatalError() caused a second fatal error.
1836 Example: flush_std_files() raises a recursion error. */
1837 goto exit;
1838 }
1839 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001840
1841 fprintf(stderr, "Fatal Python error: %s\n", msg);
1842 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001843
Victor Stinnere0deff32015-03-24 13:46:18 +01001844 /* Print the exception (if an exception is set) with its traceback,
1845 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001846 if (!_Py_FatalError_PrintExc(fd))
1847 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001848
Victor Stinner2025d782016-03-16 23:19:15 +01001849 /* The main purpose of faulthandler is to display the traceback. We already
1850 * did our best to display it. So faulthandler can now be disabled.
1851 * (Don't trigger it on abort().) */
1852 _PyFaulthandler_Fini();
1853
Victor Stinner791da1c2016-03-14 16:53:12 +01001854 /* Check if the current Python thread hold the GIL */
1855 if (PyThreadState_GET() != NULL) {
1856 /* Flush sys.stdout and sys.stderr */
1857 flush_std_files();
1858 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001859
Nick Coghland6009512014-11-20 21:39:37 +10001860#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001861 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001862
Victor Stinner53345a42015-03-25 01:55:14 +01001863 /* Convert the message to wchar_t. This uses a simple one-to-one
1864 conversion, assuming that the this error message actually uses ASCII
1865 only. If this ceases to be true, we will have to convert. */
1866 buffer = alloca( (len+1) * (sizeof *buffer));
1867 for( i=0; i<=len; ++i)
1868 buffer[i] = msg[i];
1869 OutputDebugStringW(L"Fatal Python error: ");
1870 OutputDebugStringW(buffer);
1871 OutputDebugStringW(L"\n");
1872#endif /* MS_WINDOWS */
1873
1874exit:
1875#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001876 DebugBreak();
1877#endif
Nick Coghland6009512014-11-20 21:39:37 +10001878 abort();
1879}
1880
1881/* Clean up and exit */
1882
1883#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001884# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001885#endif
1886
Nick Coghland6009512014-11-20 21:39:37 +10001887/* For the atexit module. */
1888void _Py_PyAtExit(void (*func)(void))
1889{
Eric Snow76d5abc2017-09-05 18:26:16 -07001890 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001891}
1892
1893static void
1894call_py_exitfuncs(void)
1895{
Eric Snow76d5abc2017-09-05 18:26:16 -07001896 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001897 return;
1898
Eric Snow76d5abc2017-09-05 18:26:16 -07001899 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001900 PyErr_Clear();
1901}
1902
1903/* Wait until threading._shutdown completes, provided
1904 the threading module was imported in the first place.
1905 The shutdown routine will wait until all non-daemon
1906 "threading" threads have completed. */
1907static void
1908wait_for_thread_shutdown(void)
1909{
1910#ifdef WITH_THREAD
1911 _Py_IDENTIFIER(_shutdown);
1912 PyObject *result;
Eric Snow86b7afd2017-09-04 17:54:09 -06001913 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001914 if (threading == NULL) {
1915 /* threading not imported */
1916 PyErr_Clear();
1917 return;
1918 }
Eric Snow86b7afd2017-09-04 17:54:09 -06001919 Py_INCREF(threading);
Victor Stinner3466bde2016-09-05 18:16:01 -07001920 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001921 if (result == NULL) {
1922 PyErr_WriteUnraisable(threading);
1923 }
1924 else {
1925 Py_DECREF(result);
1926 }
1927 Py_DECREF(threading);
1928#endif
1929}
1930
1931#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001932int Py_AtExit(void (*func)(void))
1933{
Eric Snow76d5abc2017-09-05 18:26:16 -07001934 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001935 return -1;
Eric Snow76d5abc2017-09-05 18:26:16 -07001936 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001937 return 0;
1938}
1939
1940static void
1941call_ll_exitfuncs(void)
1942{
Eric Snow76d5abc2017-09-05 18:26:16 -07001943 while (_PyRuntime.nexitfuncs > 0)
1944 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001945
1946 fflush(stdout);
1947 fflush(stderr);
1948}
1949
1950void
1951Py_Exit(int sts)
1952{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001953 if (Py_FinalizeEx() < 0) {
1954 sts = 120;
1955 }
Nick Coghland6009512014-11-20 21:39:37 +10001956
1957 exit(sts);
1958}
1959
1960static void
1961initsigs(void)
1962{
1963#ifdef SIGPIPE
1964 PyOS_setsig(SIGPIPE, SIG_IGN);
1965#endif
1966#ifdef SIGXFZ
1967 PyOS_setsig(SIGXFZ, SIG_IGN);
1968#endif
1969#ifdef SIGXFSZ
1970 PyOS_setsig(SIGXFSZ, SIG_IGN);
1971#endif
1972 PyOS_InitInterrupts(); /* May imply initsignal() */
1973 if (PyErr_Occurred()) {
1974 Py_FatalError("Py_Initialize: can't import signal");
1975 }
1976}
1977
1978
1979/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1980 *
1981 * All of the code in this function must only use async-signal-safe functions,
1982 * listed at `man 7 signal` or
1983 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1984 */
1985void
1986_Py_RestoreSignals(void)
1987{
1988#ifdef SIGPIPE
1989 PyOS_setsig(SIGPIPE, SIG_DFL);
1990#endif
1991#ifdef SIGXFZ
1992 PyOS_setsig(SIGXFZ, SIG_DFL);
1993#endif
1994#ifdef SIGXFSZ
1995 PyOS_setsig(SIGXFSZ, SIG_DFL);
1996#endif
1997}
1998
1999
2000/*
2001 * The file descriptor fd is considered ``interactive'' if either
2002 * a) isatty(fd) is TRUE, or
2003 * b) the -i flag was given, and the filename associated with
2004 * the descriptor is NULL or "<stdin>" or "???".
2005 */
2006int
2007Py_FdIsInteractive(FILE *fp, const char *filename)
2008{
2009 if (isatty((int)fileno(fp)))
2010 return 1;
2011 if (!Py_InteractiveFlag)
2012 return 0;
2013 return (filename == NULL) ||
2014 (strcmp(filename, "<stdin>") == 0) ||
2015 (strcmp(filename, "???") == 0);
2016}
2017
2018
Nick Coghland6009512014-11-20 21:39:37 +10002019/* Wrappers around sigaction() or signal(). */
2020
2021PyOS_sighandler_t
2022PyOS_getsig(int sig)
2023{
2024#ifdef HAVE_SIGACTION
2025 struct sigaction context;
2026 if (sigaction(sig, NULL, &context) == -1)
2027 return SIG_ERR;
2028 return context.sa_handler;
2029#else
2030 PyOS_sighandler_t handler;
2031/* Special signal handling for the secure CRT in Visual Studio 2005 */
2032#if defined(_MSC_VER) && _MSC_VER >= 1400
2033 switch (sig) {
2034 /* Only these signals are valid */
2035 case SIGINT:
2036 case SIGILL:
2037 case SIGFPE:
2038 case SIGSEGV:
2039 case SIGTERM:
2040 case SIGBREAK:
2041 case SIGABRT:
2042 break;
2043 /* Don't call signal() with other values or it will assert */
2044 default:
2045 return SIG_ERR;
2046 }
2047#endif /* _MSC_VER && _MSC_VER >= 1400 */
2048 handler = signal(sig, SIG_IGN);
2049 if (handler != SIG_ERR)
2050 signal(sig, handler);
2051 return handler;
2052#endif
2053}
2054
2055/*
2056 * All of the code in this function must only use async-signal-safe functions,
2057 * listed at `man 7 signal` or
2058 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2059 */
2060PyOS_sighandler_t
2061PyOS_setsig(int sig, PyOS_sighandler_t handler)
2062{
2063#ifdef HAVE_SIGACTION
2064 /* Some code in Modules/signalmodule.c depends on sigaction() being
2065 * used here if HAVE_SIGACTION is defined. Fix that if this code
2066 * changes to invalidate that assumption.
2067 */
2068 struct sigaction context, ocontext;
2069 context.sa_handler = handler;
2070 sigemptyset(&context.sa_mask);
2071 context.sa_flags = 0;
2072 if (sigaction(sig, &context, &ocontext) == -1)
2073 return SIG_ERR;
2074 return ocontext.sa_handler;
2075#else
2076 PyOS_sighandler_t oldhandler;
2077 oldhandler = signal(sig, handler);
2078#ifdef HAVE_SIGINTERRUPT
2079 siginterrupt(sig, 1);
2080#endif
2081 return oldhandler;
2082#endif
2083}
2084
2085#ifdef __cplusplus
2086}
2087#endif