blob: 953bc90a456bdbc22339114d35aafd9fe97ab994 [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);
44
45#ifdef __cplusplus
46extern "C" {
47#endif
48
49extern wchar_t *Py_GetPath(void);
50
51extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
54static void initmain(PyInterpreterState *interp);
55static int initfsencoding(PyInterpreterState *interp);
56static void initsite(void);
57static int initstdio(void);
58static void initsigs(void);
59static void call_py_exitfuncs(void);
60static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
67extern int _PyFaulthandler_Init(void);
68extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
70extern int _PyTraceMalloc_Init(void);
71extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
74#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
79/* Global configuration variable declarations are in pydebug.h */
80/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
81int Py_DebugFlag; /* Needed by parser.c */
82int Py_VerboseFlag; /* Needed by import.c */
83int Py_QuietFlag; /* Needed by sysmodule.c */
84int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
85int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
86int Py_OptimizeFlag = 0; /* Needed by compile.c */
87int Py_NoSiteFlag; /* Suppress 'import site' */
88int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
89int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
90int Py_FrozenFlag; /* Needed by getpath.c */
91int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +080092int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +100093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
94int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
95int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
96int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -070097#ifdef MS_WINDOWS
98int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -070099int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700100#endif
Nick Coghland6009512014-11-20 21:39:37 +1000101
102PyThreadState *_Py_Finalizing = NULL;
103
104/* Hack to force loading of object files */
105int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
106 PyOS_mystrnicmp; /* Python/pystrcmp.o */
107
108/* PyModule_GetWarningsModule is no longer necessary as of 2.6
109since _warnings is builtin. This API should not be used. */
110PyObject *
111PyModule_GetWarningsModule(void)
112{
113 return PyImport_ImportModule("warnings");
114}
115
Eric Snowc7ec9982017-05-23 23:00:52 -0700116
Eric Snow1abcf672017-05-23 21:46:51 -0700117/* APIs to access the initialization flags
118 *
119 * Can be called prior to Py_Initialize.
120 */
121int _Py_CoreInitialized = 0;
122int _Py_Initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000123
Eric Snow1abcf672017-05-23 21:46:51 -0700124int
125_Py_IsCoreInitialized(void)
126{
127 return _Py_CoreInitialized;
128}
Nick Coghland6009512014-11-20 21:39:37 +1000129
130int
131Py_IsInitialized(void)
132{
Eric Snow1abcf672017-05-23 21:46:51 -0700133 return _Py_Initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000134}
135
136/* Helper to allow an embedding application to override the normal
137 * mechanism that attempts to figure out an appropriate IO encoding
138 */
139
140static char *_Py_StandardStreamEncoding = NULL;
141static char *_Py_StandardStreamErrors = NULL;
142
143int
144Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
145{
146 if (Py_IsInitialized()) {
147 /* This is too late to have any effect */
148 return -1;
149 }
150 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
151 * initialised yet.
152 *
153 * However, the raw memory allocators are initialised appropriately
154 * as C static variables, so _PyMem_RawStrdup is OK even though
155 * Py_Initialize hasn't been called yet.
156 */
157 if (encoding) {
158 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
159 if (!_Py_StandardStreamEncoding) {
160 return -2;
161 }
162 }
163 if (errors) {
164 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
165 if (!_Py_StandardStreamErrors) {
166 if (_Py_StandardStreamEncoding) {
167 PyMem_RawFree(_Py_StandardStreamEncoding);
168 }
169 return -3;
170 }
171 }
Steve Dower39294992016-08-30 21:22:36 -0700172#ifdef MS_WINDOWS
173 if (_Py_StandardStreamEncoding) {
174 /* Overriding the stream encoding implies legacy streams */
175 Py_LegacyWindowsStdioFlag = 1;
176 }
177#endif
Nick Coghland6009512014-11-20 21:39:37 +1000178 return 0;
179}
180
Nick Coghlan6ea41862017-06-11 13:16:15 +1000181
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000182/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
183 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000184 initializations fail, a fatal error is issued and the function does
185 not return. On return, the first thread and interpreter state have
186 been created.
187
188 Locking: you must hold the interpreter lock while calling this.
189 (If the lock has not yet been initialized, that's equivalent to
190 having the lock, but you cannot use multiple threads.)
191
192*/
193
194static int
195add_flag(int flag, const char *envs)
196{
197 int env = atoi(envs);
198 if (flag < env)
199 flag = env;
200 if (flag < 1)
201 flag = 1;
202 return flag;
203}
204
205static char*
206get_codec_name(const char *encoding)
207{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200208 const char *name_utf8;
209 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000210 PyObject *codec, *name = NULL;
211
212 codec = _PyCodec_Lookup(encoding);
213 if (!codec)
214 goto error;
215
216 name = _PyObject_GetAttrId(codec, &PyId_name);
217 Py_CLEAR(codec);
218 if (!name)
219 goto error;
220
Serhiy Storchaka06515832016-11-20 09:13:07 +0200221 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000222 if (name_utf8 == NULL)
223 goto error;
224 name_str = _PyMem_RawStrdup(name_utf8);
225 Py_DECREF(name);
226 if (name_str == NULL) {
227 PyErr_NoMemory();
228 return NULL;
229 }
230 return name_str;
231
232error:
233 Py_XDECREF(codec);
234 Py_XDECREF(name);
235 return NULL;
236}
237
238static char*
239get_locale_encoding(void)
240{
241#ifdef MS_WINDOWS
242 char codepage[100];
243 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
244 return get_codec_name(codepage);
245#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
246 char* codeset = nl_langinfo(CODESET);
247 if (!codeset || codeset[0] == '\0') {
248 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
249 return NULL;
250 }
251 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200252#elif defined(__ANDROID__)
253 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000254#else
255 PyErr_SetNone(PyExc_NotImplementedError);
256 return NULL;
257#endif
258}
259
260static void
Eric Snow1abcf672017-05-23 21:46:51 -0700261initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000262{
263 PyObject *importlib;
264 PyObject *impmod;
265 PyObject *sys_modules;
266 PyObject *value;
267
268 /* Import _importlib through its frozen version, _frozen_importlib. */
269 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
270 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
271 }
272 else if (Py_VerboseFlag) {
273 PySys_FormatStderr("import _frozen_importlib # frozen\n");
274 }
275 importlib = PyImport_AddModule("_frozen_importlib");
276 if (importlib == NULL) {
277 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
278 "sys.modules");
279 }
280 interp->importlib = importlib;
281 Py_INCREF(interp->importlib);
282
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300283 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
284 if (interp->import_func == NULL)
285 Py_FatalError("Py_Initialize: __import__ not found");
286 Py_INCREF(interp->import_func);
287
Victor Stinnercd6e6942015-09-18 09:11:57 +0200288 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000289 impmod = PyInit_imp();
290 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200291 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000292 }
293 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200294 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000295 }
296 sys_modules = PyImport_GetModuleDict();
297 if (Py_VerboseFlag) {
298 PySys_FormatStderr("import sys # builtin\n");
299 }
300 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
301 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
302 }
303
Victor Stinnercd6e6942015-09-18 09:11:57 +0200304 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000305 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200306 if (value != NULL) {
307 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700308 value = PyObject_CallMethod(importlib,
309 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200310 }
Nick Coghland6009512014-11-20 21:39:37 +1000311 if (value == NULL) {
312 PyErr_Print();
313 Py_FatalError("Py_Initialize: importlib install failed");
314 }
315 Py_DECREF(value);
316 Py_DECREF(impmod);
317
318 _PyImportZip_Init();
319}
320
Eric Snow1abcf672017-05-23 21:46:51 -0700321static void
322initexternalimport(PyInterpreterState *interp)
323{
324 PyObject *value;
325 value = PyObject_CallMethod(interp->importlib,
326 "_install_external_importers", "");
327 if (value == NULL) {
328 PyErr_Print();
329 Py_FatalError("Py_EndInitialization: external importer setup failed");
330 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200331 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700332}
Nick Coghland6009512014-11-20 21:39:37 +1000333
Nick Coghlan6ea41862017-06-11 13:16:15 +1000334/* Helper functions to better handle the legacy C locale
335 *
336 * The legacy C locale assumes ASCII as the default text encoding, which
337 * causes problems not only for the CPython runtime, but also other
338 * components like GNU readline.
339 *
340 * Accordingly, when the CLI detects it, it attempts to coerce it to a
341 * more capable UTF-8 based alternative as follows:
342 *
343 * if (_Py_LegacyLocaleDetected()) {
344 * _Py_CoerceLegacyLocale();
345 * }
346 *
347 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
348 *
349 * Locale coercion also impacts the default error handler for the standard
350 * streams: while the usual default is "strict", the default for the legacy
351 * C locale and for any of the coercion target locales is "surrogateescape".
352 */
353
354int
355_Py_LegacyLocaleDetected(void)
356{
357#ifndef MS_WINDOWS
358 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000359 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
360 * the POSIX locale as a simple alias for the C locale, so
361 * we may also want to check for that explicitly.
362 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000363 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
364 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
365#else
366 /* Windows uses code pages instead of locales, so no locale is legacy */
367 return 0;
368#endif
369}
370
Nick Coghlaneb817952017-06-18 12:29:42 +1000371static const char *_C_LOCALE_WARNING =
372 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
373 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
374 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
375 "locales is recommended.\n";
376
377static int
378_legacy_locale_warnings_enabled(void)
379{
380 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
381 return (coerce_c_locale != NULL &&
382 strncmp(coerce_c_locale, "warn", 5) == 0);
383}
384
385static void
386_emit_stderr_warning_for_legacy_locale(void)
387{
388 if (_legacy_locale_warnings_enabled()) {
389 if (_Py_LegacyLocaleDetected()) {
390 fprintf(stderr, "%s", _C_LOCALE_WARNING);
391 }
392 }
393}
394
Nick Coghlan6ea41862017-06-11 13:16:15 +1000395typedef struct _CandidateLocale {
396 const char *locale_name; /* The locale to try as a coercion target */
397} _LocaleCoercionTarget;
398
399static _LocaleCoercionTarget _TARGET_LOCALES[] = {
400 {"C.UTF-8"},
401 {"C.utf8"},
Nick Coghlaneb817952017-06-18 12:29:42 +1000402 /* {"UTF-8"}, */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000403 {NULL}
404};
405
Nick Coghlaneb817952017-06-18 12:29:42 +1000406/* XXX (ncoghlan): Using UTF-8 as a target locale is currently disabled due to
407 * problems encountered on *BSD systems with those test cases
408 * For additional details see:
409 * nl_langinfo CODESET error: https://bugs.python.org/issue30647
410 * locale handling differences: https://bugs.python.org/issue30672
411 */
412
Nick Coghlan6ea41862017-06-11 13:16:15 +1000413static char *
414get_default_standard_stream_error_handler(void)
415{
416 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
417 if (ctype_loc != NULL) {
418 /* "surrogateescape" is the default in the legacy C locale */
419 if (strcmp(ctype_loc, "C") == 0) {
420 return "surrogateescape";
421 }
422
423#ifdef PY_COERCE_C_LOCALE
424 /* "surrogateescape" is the default in locale coercion target locales */
425 const _LocaleCoercionTarget *target = NULL;
426 for (target = _TARGET_LOCALES; target->locale_name; target++) {
427 if (strcmp(ctype_loc, target->locale_name) == 0) {
428 return "surrogateescape";
429 }
430 }
431#endif
432 }
433
434 /* Otherwise return NULL to request the typical default error handler */
435 return NULL;
436}
437
438#ifdef PY_COERCE_C_LOCALE
439static const char *_C_LOCALE_COERCION_WARNING =
440 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
441 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
442
443static void
444_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
445{
446 const char *newloc = target->locale_name;
447
448 /* Reset locale back to currently configured defaults */
449 setlocale(LC_ALL, "");
450
451 /* Set the relevant locale environment variable */
452 if (setenv("LC_CTYPE", newloc, 1)) {
453 fprintf(stderr,
454 "Error setting LC_CTYPE, skipping C locale coercion\n");
455 return;
456 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000457 if (_legacy_locale_warnings_enabled()) {
458 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
459 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000460
461 /* Reconfigure with the overridden environment variables */
462 setlocale(LC_ALL, "");
463}
464#endif
465
466void
467_Py_CoerceLegacyLocale(void)
468{
469#ifdef PY_COERCE_C_LOCALE
470 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
471 * the locale settings *before* we try to do anything with the command
472 * line arguments. For cross-platform debugging purposes, we also need
473 * to give end users a way to force even scripts that are otherwise
474 * isolated from their environment to use the legacy ASCII-centric C
475 * locale.
476 *
477 * Ignoring -E and -I is safe from a security perspective, as we only use
478 * the setting to turn *off* the implicit locale coercion, and anyone with
479 * access to the process environment already has the ability to set
480 * `LC_ALL=C` to override the C level locale settings anyway.
481 */
482 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
483 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
484 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
485 const char *locale_override = getenv("LC_ALL");
486 if (locale_override == NULL || *locale_override == '\0') {
487 /* LC_ALL is also not set (or is set to an empty string) */
488 const _LocaleCoercionTarget *target = NULL;
489 for (target = _TARGET_LOCALES; target->locale_name; target++) {
490 const char *new_locale = setlocale(LC_CTYPE,
491 target->locale_name);
492 if (new_locale != NULL) {
493 /* Successfully configured locale, so make it the default */
494 _coerce_default_locale_settings(target);
495 return;
496 }
497 }
498 }
499 }
500 /* No C locale warning here, as Py_Initialize will emit one later */
501#endif
502}
503
504
Eric Snow1abcf672017-05-23 21:46:51 -0700505/* Global initializations. Can be undone by Py_Finalize(). Don't
506 call this twice without an intervening Py_Finalize() call.
507
508 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
509 must have a corresponding call to Py_Finalize.
510
511 Locking: you must hold the interpreter lock while calling these APIs.
512 (If the lock has not yet been initialized, that's equivalent to
513 having the lock, but you cannot use multiple threads.)
514
515*/
516
517/* Begin interpreter initialization
518 *
519 * On return, the first thread and interpreter state have been created,
520 * but the compiler, signal handling, multithreading and
521 * multiple interpreter support, and codec infrastructure are not yet
522 * available.
523 *
524 * The import system will support builtin and frozen modules only.
525 * The only supported io is writing to sys.stderr
526 *
527 * If any operation invoked by this function fails, a fatal error is
528 * issued and the function does not return.
529 *
530 * Any code invoked from this function should *not* assume it has access
531 * to the Python C API (unless the API is explicitly listed as being
532 * safe to call without calling Py_Initialize first)
533 */
534
535/* TODO: Progresively move functionality from Py_BeginInitialization to
536 * Py_ReadConfig and Py_EndInitialization
537 */
538
539void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000540{
541 PyInterpreterState *interp;
542 PyThreadState *tstate;
543 PyObject *bimod, *sysmod, *pstderr;
544 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700545 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700546 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000547
Eric Snow1abcf672017-05-23 21:46:51 -0700548 if (config != NULL) {
549 core_config = *config;
550 }
551
552 if (_Py_Initialized) {
553 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
554 }
555 if (_Py_CoreInitialized) {
556 Py_FatalError("Py_InitializeCore: runtime core already initialized");
557 }
558
559 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
560 * threads behave a little more gracefully at interpreter shutdown.
561 * We clobber it here so the new interpreter can start with a clean
562 * slate.
563 *
564 * However, this may still lead to misbehaviour if there are daemon
565 * threads still hanging around from a previous Py_Initialize/Finalize
566 * pair :(
567 */
Nick Coghland6009512014-11-20 21:39:37 +1000568 _Py_Finalizing = NULL;
569
Nick Coghlan6ea41862017-06-11 13:16:15 +1000570#ifdef __ANDROID__
571 /* Passing "" to setlocale() on Android requests the C locale rather
572 * than checking environment variables, so request C.UTF-8 explicitly
573 */
574 setlocale(LC_CTYPE, "C.UTF-8");
575#else
576#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000577 /* Set up the LC_CTYPE locale, so we can obtain
578 the locale's charset without having to switch
579 locales. */
580 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000581 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000582#endif
Nick Coghland6009512014-11-20 21:39:37 +1000583#endif
584
585 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
586 Py_DebugFlag = add_flag(Py_DebugFlag, p);
587 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
588 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
589 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
590 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
591 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
592 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700593 /* The variable is only tested for existence here;
594 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000595 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
596 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700597#ifdef MS_WINDOWS
598 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
599 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700600 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
601 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700602#endif
Nick Coghland6009512014-11-20 21:39:37 +1000603
Eric Snow1abcf672017-05-23 21:46:51 -0700604 _Py_HashRandomization_Init(&core_config);
605 if (!core_config.use_hash_seed || core_config.hash_seed) {
606 /* Random or non-zero hash seed */
607 Py_HashRandomizationFlag = 1;
608 }
Nick Coghland6009512014-11-20 21:39:37 +1000609
Eric Snowe3774162017-05-22 19:46:40 -0700610 _PyInterpreterState_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000611 interp = PyInterpreterState_New();
612 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700613 Py_FatalError("Py_InitializeCore: can't make main interpreter");
614 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700615 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000616
617 tstate = PyThreadState_New(interp);
618 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700619 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000620 (void) PyThreadState_Swap(tstate);
621
622#ifdef WITH_THREAD
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000623 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000624 destroying the GIL might fail when it is being referenced from
625 another running thread (see issue #9901).
626 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000627 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000628 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000629 /* Auto-thread-state API */
630 _PyGILState_Init(interp, tstate);
631#endif /* WITH_THREAD */
632
633 _Py_ReadyTypes();
634
635 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700636 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000637
638 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700639 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000640
641 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700642 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000643
644 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700645 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000646
647 interp->modules = PyDict_New();
648 if (interp->modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700649 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000650
651 /* Init Unicode implementation; relies on the codec registry */
652 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700653 Py_FatalError("Py_InitializeCore: can't initialize unicode");
654
Nick Coghland6009512014-11-20 21:39:37 +1000655 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700656 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000657
658 bimod = _PyBuiltin_Init();
659 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700660 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Nick Coghland6009512014-11-20 21:39:37 +1000661 _PyImport_FixupBuiltin(bimod, "builtins");
662 interp->builtins = PyModule_GetDict(bimod);
663 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700664 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000665 Py_INCREF(interp->builtins);
666
667 /* initialize builtin exceptions */
668 _PyExc_Init(bimod);
669
Eric Snow6b4be192017-05-22 21:36:03 -0700670 sysmod = _PySys_BeginInit();
Nick Coghland6009512014-11-20 21:39:37 +1000671 if (sysmod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700672 Py_FatalError("Py_InitializeCore: can't initialize sys");
Nick Coghland6009512014-11-20 21:39:37 +1000673 interp->sysdict = PyModule_GetDict(sysmod);
674 if (interp->sysdict == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700675 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
Nick Coghland6009512014-11-20 21:39:37 +1000676 Py_INCREF(interp->sysdict);
677 _PyImport_FixupBuiltin(sysmod, "sys");
Nick Coghland6009512014-11-20 21:39:37 +1000678 PyDict_SetItemString(interp->sysdict, "modules",
679 interp->modules);
680
681 /* Set up a preliminary stderr printer until we have enough
682 infrastructure for the io module in place. */
683 pstderr = PyFile_NewStdPrinter(fileno(stderr));
684 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700685 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000686 _PySys_SetObjectId(&PyId_stderr, pstderr);
687 PySys_SetObject("__stderr__", pstderr);
688 Py_DECREF(pstderr);
689
690 _PyImport_Init();
691
692 _PyImportHooks_Init();
693
694 /* Initialize _warnings. */
695 _PyWarnings_Init();
696
Eric Snow1abcf672017-05-23 21:46:51 -0700697 /* This call sets up builtin and frozen import support */
698 if (!interp->core_config._disable_importlib) {
699 initimport(interp, sysmod);
700 }
701
702 /* Only when we get here is the runtime core fully initialized */
703 _Py_CoreInitialized = 1;
704}
705
Eric Snowc7ec9982017-05-23 23:00:52 -0700706/* Read configuration settings from standard locations
707 *
708 * This function doesn't make any changes to the interpreter state - it
709 * merely populates any missing configuration settings. This allows an
710 * embedding application to completely override a config option by
711 * setting it before calling this function, or else modify the default
712 * setting before passing the fully populated config to Py_EndInitialization.
713 *
714 * More advanced selective initialization tricks are possible by calling
715 * this function multiple times with various preconfigured settings.
716 */
717
718int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
719{
720 /* Signal handlers are installed by default */
721 if (config->install_signal_handlers < 0) {
722 config->install_signal_handlers = 1;
723 }
724
725 return 0;
726}
727
728/* Update interpreter state based on supplied configuration settings
729 *
730 * After calling this function, most of the restrictions on the interpreter
731 * are lifted. The only remaining incomplete settings are those related
732 * to the main module (sys.argv[0], __main__ metadata)
733 *
734 * Calling this when the interpreter is not initializing, is already
735 * initialized or without a valid current thread state is a fatal error.
736 * Other errors should be reported as normal Python exceptions with a
737 * non-zero return code.
738 */
739int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700740{
741 PyInterpreterState *interp;
742 PyThreadState *tstate;
743
Eric Snowc7ec9982017-05-23 23:00:52 -0700744 if (!_Py_CoreInitialized) {
745 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
746 }
747 if (_Py_Initialized) {
748 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
749 }
750
Eric Snow1abcf672017-05-23 21:46:51 -0700751 /* Get current thread state and interpreter pointer */
752 tstate = PyThreadState_GET();
753 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700754 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700755 interp = tstate->interp;
756 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700757 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700758
759 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700760 interp->config = *config;
761
Eric Snow1abcf672017-05-23 21:46:51 -0700762 if (interp->core_config._disable_importlib) {
763 /* Special mode for freeze_importlib: run with no import system
764 *
765 * This means anything which needs support from extension modules
766 * or pure Python code in the standard library won't work.
767 */
768 _Py_Initialized = 1;
769 return 0;
770 }
771 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000772
Victor Stinner13019fd2015-04-03 13:10:54 +0200773 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700774 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200775
Eric Snow1abcf672017-05-23 21:46:51 -0700776 /* Finish setting up the sys module and import system */
777 /* GetPath may initialize state that _PySys_EndInit locks
778 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700779 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700780 PySys_SetPath(Py_GetPath());
781 if (_PySys_EndInit(interp->sysdict) < 0)
782 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700783 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000784
785 /* initialize the faulthandler module */
786 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700787 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000788
Nick Coghland6009512014-11-20 21:39:37 +1000789 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700790 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000791
Eric Snowc7ec9982017-05-23 23:00:52 -0700792 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000793 initsigs(); /* Signal handling stuff, including initintr() */
794
795 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700796 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000797
798 initmain(interp); /* Module __main__ */
799 if (initstdio() < 0)
800 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700801 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000802
803 /* Initialize warnings. */
804 if (PySys_HasWarnOptions()) {
805 PyObject *warnings_module = PyImport_ImportModule("warnings");
806 if (warnings_module == NULL) {
807 fprintf(stderr, "'import warnings' failed; traceback:\n");
808 PyErr_Print();
809 }
810 Py_XDECREF(warnings_module);
811 }
812
Eric Snow1abcf672017-05-23 21:46:51 -0700813 _Py_Initialized = 1;
814
Nick Coghland6009512014-11-20 21:39:37 +1000815 if (!Py_NoSiteFlag)
816 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700817
Eric Snowc7ec9982017-05-23 23:00:52 -0700818 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000819}
820
Eric Snowc7ec9982017-05-23 23:00:52 -0700821#undef _INIT_DEBUG_PRINT
822
Nick Coghland6009512014-11-20 21:39:37 +1000823void
Eric Snow1abcf672017-05-23 21:46:51 -0700824_Py_InitializeEx_Private(int install_sigs, int install_importlib)
825{
826 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700827 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700828
829 /* TODO: Moar config options! */
830 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
831 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700833 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700834 /* TODO: Print any exceptions raised by these operations */
835 if (_Py_ReadMainInterpreterConfig(&config))
836 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
837 if (_Py_InitializeMainInterpreter(&config))
838 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700839}
840
841
842void
Nick Coghland6009512014-11-20 21:39:37 +1000843Py_InitializeEx(int install_sigs)
844{
845 _Py_InitializeEx_Private(install_sigs, 1);
846}
847
848void
849Py_Initialize(void)
850{
851 Py_InitializeEx(1);
852}
853
854
855#ifdef COUNT_ALLOCS
856extern void dump_counts(FILE*);
857#endif
858
859/* Flush stdout and stderr */
860
861static int
862file_is_closed(PyObject *fobj)
863{
864 int r;
865 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
866 if (tmp == NULL) {
867 PyErr_Clear();
868 return 0;
869 }
870 r = PyObject_IsTrue(tmp);
871 Py_DECREF(tmp);
872 if (r < 0)
873 PyErr_Clear();
874 return r > 0;
875}
876
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000877static int
Nick Coghland6009512014-11-20 21:39:37 +1000878flush_std_files(void)
879{
880 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
881 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
882 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000883 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000884
885 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700886 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000887 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000888 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000889 status = -1;
890 }
Nick Coghland6009512014-11-20 21:39:37 +1000891 else
892 Py_DECREF(tmp);
893 }
894
895 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700896 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000897 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000898 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000899 status = -1;
900 }
Nick Coghland6009512014-11-20 21:39:37 +1000901 else
902 Py_DECREF(tmp);
903 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000904
905 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000906}
907
908/* Undo the effect of Py_Initialize().
909
910 Beware: if multiple interpreter and/or thread states exist, these
911 are not wiped out; only the current thread and interpreter state
912 are deleted. But since everything else is deleted, those other
913 interpreter and thread states should no longer be used.
914
915 (XXX We should do better, e.g. wipe out all interpreters and
916 threads.)
917
918 Locking: as above.
919
920*/
921
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000922int
923Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000924{
925 PyInterpreterState *interp;
926 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000927 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000928
Eric Snow1abcf672017-05-23 21:46:51 -0700929 if (!_Py_Initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000930 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000931
932 wait_for_thread_shutdown();
933
934 /* The interpreter is still entirely intact at this point, and the
935 * exit funcs may be relying on that. In particular, if some thread
936 * or exit func is still waiting to do an import, the import machinery
937 * expects Py_IsInitialized() to return true. So don't say the
938 * interpreter is uninitialized until after the exit funcs have run.
939 * Note that Threading.py uses an exit func to do a join on all the
940 * threads created thru it, so this also protects pending imports in
941 * the threads created via Threading.
942 */
943 call_py_exitfuncs();
944
945 /* Get current thread state and interpreter pointer */
946 tstate = PyThreadState_GET();
947 interp = tstate->interp;
948
949 /* Remaining threads (e.g. daemon threads) will automatically exit
950 after taking the GIL (in PyEval_RestoreThread()). */
951 _Py_Finalizing = tstate;
Eric Snow1abcf672017-05-23 21:46:51 -0700952 _Py_Initialized = 0;
953 _Py_CoreInitialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000954
Victor Stinnere0deff32015-03-24 13:46:18 +0100955 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000956 if (flush_std_files() < 0) {
957 status = -1;
958 }
Nick Coghland6009512014-11-20 21:39:37 +1000959
960 /* Disable signal handling */
961 PyOS_FiniInterrupts();
962
963 /* Collect garbage. This may call finalizers; it's nice to call these
964 * before all modules are destroyed.
965 * XXX If a __del__ or weakref callback is triggered here, and tries to
966 * XXX import a module, bad things can happen, because Python no
967 * XXX longer believes it's initialized.
968 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
969 * XXX is easy to provoke that way. I've also seen, e.g.,
970 * XXX Exception exceptions.ImportError: 'No module named sha'
971 * XXX in <function callback at 0x008F5718> ignored
972 * XXX but I'm unclear on exactly how that one happens. In any case,
973 * XXX I haven't seen a real-life report of either of these.
974 */
Łukasz Langafef7e942016-09-09 21:47:46 -0700975 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +1000976#ifdef COUNT_ALLOCS
977 /* With COUNT_ALLOCS, it helps to run GC multiple times:
978 each collection might release some types from the type
979 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -0700980 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +1000981 /* nothing */;
982#endif
983 /* Destroy all modules */
984 PyImport_Cleanup();
985
Victor Stinnere0deff32015-03-24 13:46:18 +0100986 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000987 if (flush_std_files() < 0) {
988 status = -1;
989 }
Nick Coghland6009512014-11-20 21:39:37 +1000990
991 /* Collect final garbage. This disposes of cycles created by
992 * class definitions, for example.
993 * XXX This is disabled because it caused too many problems. If
994 * XXX a __del__ or weakref callback triggers here, Python code has
995 * XXX a hard time running, because even the sys module has been
996 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
997 * XXX One symptom is a sequence of information-free messages
998 * XXX coming from threads (if a __del__ or callback is invoked,
999 * XXX other threads can execute too, and any exception they encounter
1000 * XXX triggers a comedy of errors as subsystem after subsystem
1001 * XXX fails to find what it *expects* to find in sys to help report
1002 * XXX the exception and consequent unexpected failures). I've also
1003 * XXX seen segfaults then, after adding print statements to the
1004 * XXX Python code getting called.
1005 */
1006#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001007 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001008#endif
1009
1010 /* Disable tracemalloc after all Python objects have been destroyed,
1011 so it is possible to use tracemalloc in objects destructor. */
1012 _PyTraceMalloc_Fini();
1013
1014 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1015 _PyImport_Fini();
1016
1017 /* Cleanup typeobject.c's internal caches. */
1018 _PyType_Fini();
1019
1020 /* unload faulthandler module */
1021 _PyFaulthandler_Fini();
1022
1023 /* Debugging stuff */
1024#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001025 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001026#endif
1027 /* dump hash stats */
1028 _PyHash_Fini();
1029
1030 _PY_DEBUG_PRINT_TOTAL_REFS();
1031
1032#ifdef Py_TRACE_REFS
1033 /* Display all objects still alive -- this can invoke arbitrary
1034 * __repr__ overrides, so requires a mostly-intact interpreter.
1035 * Alas, a lot of stuff may still be alive now that will be cleaned
1036 * up later.
1037 */
1038 if (Py_GETENV("PYTHONDUMPREFS"))
1039 _Py_PrintReferences(stderr);
1040#endif /* Py_TRACE_REFS */
1041
1042 /* Clear interpreter state and all thread states. */
1043 PyInterpreterState_Clear(interp);
1044
1045 /* Now we decref the exception classes. After this point nothing
1046 can raise an exception. That's okay, because each Fini() method
1047 below has been checked to make sure no exceptions are ever
1048 raised.
1049 */
1050
1051 _PyExc_Fini();
1052
1053 /* Sundry finalizers */
1054 PyMethod_Fini();
1055 PyFrame_Fini();
1056 PyCFunction_Fini();
1057 PyTuple_Fini();
1058 PyList_Fini();
1059 PySet_Fini();
1060 PyBytes_Fini();
1061 PyByteArray_Fini();
1062 PyLong_Fini();
1063 PyFloat_Fini();
1064 PyDict_Fini();
1065 PySlice_Fini();
1066 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001067 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001068 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001069 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001070
1071 /* Cleanup Unicode implementation */
1072 _PyUnicode_Fini();
1073
1074 /* reset file system default encoding */
1075 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1076 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1077 Py_FileSystemDefaultEncoding = NULL;
1078 }
1079
1080 /* XXX Still allocated:
1081 - various static ad-hoc pointers to interned strings
1082 - int and float free list blocks
1083 - whatever various modules and libraries allocate
1084 */
1085
1086 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1087
1088 /* Cleanup auto-thread-state */
1089#ifdef WITH_THREAD
1090 _PyGILState_Fini();
1091#endif /* WITH_THREAD */
1092
1093 /* Delete current thread. After this, many C API calls become crashy. */
1094 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001095
Nick Coghland6009512014-11-20 21:39:37 +10001096 PyInterpreterState_Delete(interp);
1097
1098#ifdef Py_TRACE_REFS
1099 /* Display addresses (& refcnts) of all objects still alive.
1100 * An address can be used to find the repr of the object, printed
1101 * above by _Py_PrintReferences.
1102 */
1103 if (Py_GETENV("PYTHONDUMPREFS"))
1104 _Py_PrintReferenceAddresses(stderr);
1105#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001106#ifdef WITH_PYMALLOC
1107 if (_PyMem_PymallocEnabled()) {
1108 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1109 if (opt != NULL && *opt != '\0')
1110 _PyObject_DebugMallocStats(stderr);
1111 }
Nick Coghland6009512014-11-20 21:39:37 +10001112#endif
1113
1114 call_ll_exitfuncs();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001115 return status;
1116}
1117
1118void
1119Py_Finalize(void)
1120{
1121 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001122}
1123
1124/* Create and initialize a new interpreter and thread, and return the
1125 new thread. This requires that Py_Initialize() has been called
1126 first.
1127
1128 Unsuccessful initialization yields a NULL pointer. Note that *no*
1129 exception information is available even in this case -- the
1130 exception information is held in the thread, and there is no
1131 thread.
1132
1133 Locking: as above.
1134
1135*/
1136
1137PyThreadState *
1138Py_NewInterpreter(void)
1139{
1140 PyInterpreterState *interp;
1141 PyThreadState *tstate, *save_tstate;
1142 PyObject *bimod, *sysmod;
1143
Eric Snow1abcf672017-05-23 21:46:51 -07001144 if (!_Py_Initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001145 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1146
Victor Stinnerd7292b52016-06-17 12:29:00 +02001147#ifdef WITH_THREAD
Victor Stinner8a1be612016-03-14 22:07:55 +01001148 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1149 interpreters: disable PyGILState_Check(). */
1150 _PyGILState_check_enabled = 0;
Berker Peksag531396c2016-06-17 13:25:01 +03001151#endif
Victor Stinner8a1be612016-03-14 22:07:55 +01001152
Nick Coghland6009512014-11-20 21:39:37 +10001153 interp = PyInterpreterState_New();
1154 if (interp == NULL)
1155 return NULL;
1156
1157 tstate = PyThreadState_New(interp);
1158 if (tstate == NULL) {
1159 PyInterpreterState_Delete(interp);
1160 return NULL;
1161 }
1162
1163 save_tstate = PyThreadState_Swap(tstate);
1164
Eric Snow1abcf672017-05-23 21:46:51 -07001165 /* Copy the current interpreter config into the new interpreter */
1166 if (save_tstate != NULL) {
1167 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001168 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001169 } else {
1170 /* No current thread state, copy from the main interpreter */
1171 PyInterpreterState *main_interp = PyInterpreterState_Main();
1172 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001173 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001174 }
1175
Nick Coghland6009512014-11-20 21:39:37 +10001176 /* XXX The following is lax in error checking */
1177
1178 interp->modules = PyDict_New();
1179
1180 bimod = _PyImport_FindBuiltin("builtins");
1181 if (bimod != NULL) {
1182 interp->builtins = PyModule_GetDict(bimod);
1183 if (interp->builtins == NULL)
1184 goto handle_error;
1185 Py_INCREF(interp->builtins);
1186 }
1187
1188 /* initialize builtin exceptions */
1189 _PyExc_Init(bimod);
1190
1191 sysmod = _PyImport_FindBuiltin("sys");
1192 if (bimod != NULL && sysmod != NULL) {
1193 PyObject *pstderr;
1194
1195 interp->sysdict = PyModule_GetDict(sysmod);
1196 if (interp->sysdict == NULL)
1197 goto handle_error;
1198 Py_INCREF(interp->sysdict);
Eric Snow1abcf672017-05-23 21:46:51 -07001199 _PySys_EndInit(interp->sysdict);
Nick Coghland6009512014-11-20 21:39:37 +10001200 PySys_SetPath(Py_GetPath());
1201 PyDict_SetItemString(interp->sysdict, "modules",
1202 interp->modules);
1203 /* Set up a preliminary stderr printer until we have enough
1204 infrastructure for the io module in place. */
1205 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1206 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001207 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001208 _PySys_SetObjectId(&PyId_stderr, pstderr);
1209 PySys_SetObject("__stderr__", pstderr);
1210 Py_DECREF(pstderr);
1211
1212 _PyImportHooks_Init();
1213
Eric Snow1abcf672017-05-23 21:46:51 -07001214 initimport(interp, sysmod);
1215 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001216
1217 if (initfsencoding(interp) < 0)
1218 goto handle_error;
1219
1220 if (initstdio() < 0)
1221 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001222 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001223 initmain(interp);
1224 if (!Py_NoSiteFlag)
1225 initsite();
1226 }
1227
1228 if (!PyErr_Occurred())
1229 return tstate;
1230
1231handle_error:
1232 /* Oops, it didn't work. Undo it all. */
1233
1234 PyErr_PrintEx(0);
1235 PyThreadState_Clear(tstate);
1236 PyThreadState_Swap(save_tstate);
1237 PyThreadState_Delete(tstate);
1238 PyInterpreterState_Delete(interp);
1239
1240 return NULL;
1241}
1242
1243/* Delete an interpreter and its last thread. This requires that the
1244 given thread state is current, that the thread has no remaining
1245 frames, and that it is its interpreter's only remaining thread.
1246 It is a fatal error to violate these constraints.
1247
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001248 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001249 everything, regardless.)
1250
1251 Locking: as above.
1252
1253*/
1254
1255void
1256Py_EndInterpreter(PyThreadState *tstate)
1257{
1258 PyInterpreterState *interp = tstate->interp;
1259
1260 if (tstate != PyThreadState_GET())
1261 Py_FatalError("Py_EndInterpreter: thread is not current");
1262 if (tstate->frame != NULL)
1263 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1264
1265 wait_for_thread_shutdown();
1266
1267 if (tstate != interp->tstate_head || tstate->next != NULL)
1268 Py_FatalError("Py_EndInterpreter: not the last thread");
1269
1270 PyImport_Cleanup();
1271 PyInterpreterState_Clear(interp);
1272 PyThreadState_Swap(NULL);
1273 PyInterpreterState_Delete(interp);
1274}
1275
1276#ifdef MS_WINDOWS
1277static wchar_t *progname = L"python";
1278#else
1279static wchar_t *progname = L"python3";
1280#endif
1281
1282void
1283Py_SetProgramName(wchar_t *pn)
1284{
1285 if (pn && *pn)
1286 progname = pn;
1287}
1288
1289wchar_t *
1290Py_GetProgramName(void)
1291{
1292 return progname;
1293}
1294
1295static wchar_t *default_home = NULL;
1296static wchar_t env_home[MAXPATHLEN+1];
1297
1298void
1299Py_SetPythonHome(wchar_t *home)
1300{
1301 default_home = home;
1302}
1303
1304wchar_t *
1305Py_GetPythonHome(void)
1306{
1307 wchar_t *home = default_home;
1308 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1309 char* chome = Py_GETENV("PYTHONHOME");
1310 if (chome) {
1311 size_t size = Py_ARRAY_LENGTH(env_home);
1312 size_t r = mbstowcs(env_home, chome, size);
1313 if (r != (size_t)-1 && r < size)
1314 home = env_home;
1315 }
1316
1317 }
1318 return home;
1319}
1320
1321/* Create __main__ module */
1322
1323static void
1324initmain(PyInterpreterState *interp)
1325{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001326 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001327 m = PyImport_AddModule("__main__");
1328 if (m == NULL)
1329 Py_FatalError("can't create __main__ module");
1330 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001331 ann_dict = PyDict_New();
1332 if ((ann_dict == NULL) ||
1333 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1334 Py_FatalError("Failed to initialize __main__.__annotations__");
1335 }
1336 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001337 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1338 PyObject *bimod = PyImport_ImportModule("builtins");
1339 if (bimod == NULL) {
1340 Py_FatalError("Failed to retrieve builtins module");
1341 }
1342 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1343 Py_FatalError("Failed to initialize __main__.__builtins__");
1344 }
1345 Py_DECREF(bimod);
1346 }
1347 /* Main is a little special - imp.is_builtin("__main__") will return
1348 * False, but BuiltinImporter is still the most appropriate initial
1349 * setting for its __loader__ attribute. A more suitable value will
1350 * be set if __main__ gets further initialized later in the startup
1351 * process.
1352 */
1353 loader = PyDict_GetItemString(d, "__loader__");
1354 if (loader == NULL || loader == Py_None) {
1355 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1356 "BuiltinImporter");
1357 if (loader == NULL) {
1358 Py_FatalError("Failed to retrieve BuiltinImporter");
1359 }
1360 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1361 Py_FatalError("Failed to initialize __main__.__loader__");
1362 }
1363 Py_DECREF(loader);
1364 }
1365}
1366
1367static int
1368initfsencoding(PyInterpreterState *interp)
1369{
1370 PyObject *codec;
1371
Steve Dowercc16be82016-09-08 10:35:16 -07001372#ifdef MS_WINDOWS
1373 if (Py_LegacyWindowsFSEncodingFlag)
1374 {
1375 Py_FileSystemDefaultEncoding = "mbcs";
1376 Py_FileSystemDefaultEncodeErrors = "replace";
1377 }
1378 else
1379 {
1380 Py_FileSystemDefaultEncoding = "utf-8";
1381 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1382 }
1383#else
Nick Coghland6009512014-11-20 21:39:37 +10001384 if (Py_FileSystemDefaultEncoding == NULL)
1385 {
1386 Py_FileSystemDefaultEncoding = get_locale_encoding();
1387 if (Py_FileSystemDefaultEncoding == NULL)
1388 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1389
1390 Py_HasFileSystemDefaultEncoding = 0;
1391 interp->fscodec_initialized = 1;
1392 return 0;
1393 }
Steve Dowercc16be82016-09-08 10:35:16 -07001394#endif
Nick Coghland6009512014-11-20 21:39:37 +10001395
1396 /* the encoding is mbcs, utf-8 or ascii */
1397 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1398 if (!codec) {
1399 /* Such error can only occurs in critical situations: no more
1400 * memory, import a module of the standard library failed,
1401 * etc. */
1402 return -1;
1403 }
1404 Py_DECREF(codec);
1405 interp->fscodec_initialized = 1;
1406 return 0;
1407}
1408
1409/* Import the site module (not into __main__ though) */
1410
1411static void
1412initsite(void)
1413{
1414 PyObject *m;
1415 m = PyImport_ImportModule("site");
1416 if (m == NULL) {
1417 fprintf(stderr, "Failed to import the site module\n");
1418 PyErr_Print();
1419 Py_Finalize();
1420 exit(1);
1421 }
1422 else {
1423 Py_DECREF(m);
1424 }
1425}
1426
Victor Stinner874dbe82015-09-04 17:29:57 +02001427/* Check if a file descriptor is valid or not.
1428 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1429static int
1430is_valid_fd(int fd)
1431{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001432#ifdef __APPLE__
1433 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1434 and the other side of the pipe is closed, dup(1) succeed, whereas
1435 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1436 such error. */
1437 struct stat st;
1438 return (fstat(fd, &st) == 0);
1439#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001440 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001441 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001442 return 0;
1443 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001444 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1445 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1446 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001447 fd2 = dup(fd);
1448 if (fd2 >= 0)
1449 close(fd2);
1450 _Py_END_SUPPRESS_IPH
1451 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001452#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001453}
1454
1455/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001456static PyObject*
1457create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001458 int fd, int write_mode, const char* name,
1459 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001460{
1461 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1462 const char* mode;
1463 const char* newline;
1464 PyObject *line_buffering;
1465 int buffering, isatty;
1466 _Py_IDENTIFIER(open);
1467 _Py_IDENTIFIER(isatty);
1468 _Py_IDENTIFIER(TextIOWrapper);
1469 _Py_IDENTIFIER(mode);
1470
Victor Stinner874dbe82015-09-04 17:29:57 +02001471 if (!is_valid_fd(fd))
1472 Py_RETURN_NONE;
1473
Nick Coghland6009512014-11-20 21:39:37 +10001474 /* stdin is always opened in buffered mode, first because it shouldn't
1475 make a difference in common use cases, second because TextIOWrapper
1476 depends on the presence of a read1() method which only exists on
1477 buffered streams.
1478 */
1479 if (Py_UnbufferedStdioFlag && write_mode)
1480 buffering = 0;
1481 else
1482 buffering = -1;
1483 if (write_mode)
1484 mode = "wb";
1485 else
1486 mode = "rb";
1487 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1488 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001489 Py_None, Py_None, /* encoding, errors */
1490 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001491 if (buf == NULL)
1492 goto error;
1493
1494 if (buffering) {
1495 _Py_IDENTIFIER(raw);
1496 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1497 if (raw == NULL)
1498 goto error;
1499 }
1500 else {
1501 raw = buf;
1502 Py_INCREF(raw);
1503 }
1504
Steve Dower39294992016-08-30 21:22:36 -07001505#ifdef MS_WINDOWS
1506 /* Windows console IO is always UTF-8 encoded */
1507 if (PyWindowsConsoleIO_Check(raw))
1508 encoding = "utf-8";
1509#endif
1510
Nick Coghland6009512014-11-20 21:39:37 +10001511 text = PyUnicode_FromString(name);
1512 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1513 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001514 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001515 if (res == NULL)
1516 goto error;
1517 isatty = PyObject_IsTrue(res);
1518 Py_DECREF(res);
1519 if (isatty == -1)
1520 goto error;
1521 if (isatty || Py_UnbufferedStdioFlag)
1522 line_buffering = Py_True;
1523 else
1524 line_buffering = Py_False;
1525
1526 Py_CLEAR(raw);
1527 Py_CLEAR(text);
1528
1529#ifdef MS_WINDOWS
1530 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1531 newlines to "\n".
1532 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1533 newline = NULL;
1534#else
1535 /* sys.stdin: split lines at "\n".
1536 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1537 newline = "\n";
1538#endif
1539
1540 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1541 buf, encoding, errors,
1542 newline, line_buffering);
1543 Py_CLEAR(buf);
1544 if (stream == NULL)
1545 goto error;
1546
1547 if (write_mode)
1548 mode = "w";
1549 else
1550 mode = "r";
1551 text = PyUnicode_FromString(mode);
1552 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1553 goto error;
1554 Py_CLEAR(text);
1555 return stream;
1556
1557error:
1558 Py_XDECREF(buf);
1559 Py_XDECREF(stream);
1560 Py_XDECREF(text);
1561 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001562
Victor Stinner874dbe82015-09-04 17:29:57 +02001563 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1564 /* Issue #24891: the file descriptor was closed after the first
1565 is_valid_fd() check was called. Ignore the OSError and set the
1566 stream to None. */
1567 PyErr_Clear();
1568 Py_RETURN_NONE;
1569 }
1570 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001571}
1572
1573/* Initialize sys.stdin, stdout, stderr and builtins.open */
1574static int
1575initstdio(void)
1576{
1577 PyObject *iomod = NULL, *wrapper;
1578 PyObject *bimod = NULL;
1579 PyObject *m;
1580 PyObject *std = NULL;
1581 int status = 0, fd;
1582 PyObject * encoding_attr;
1583 char *pythonioencoding = NULL, *encoding, *errors;
1584
1585 /* Hack to avoid a nasty recursion issue when Python is invoked
1586 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1587 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1588 goto error;
1589 }
1590 Py_DECREF(m);
1591
1592 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1593 goto error;
1594 }
1595 Py_DECREF(m);
1596
1597 if (!(bimod = PyImport_ImportModule("builtins"))) {
1598 goto error;
1599 }
1600
1601 if (!(iomod = PyImport_ImportModule("io"))) {
1602 goto error;
1603 }
1604 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1605 goto error;
1606 }
1607
1608 /* Set builtins.open */
1609 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1610 Py_DECREF(wrapper);
1611 goto error;
1612 }
1613 Py_DECREF(wrapper);
1614
1615 encoding = _Py_StandardStreamEncoding;
1616 errors = _Py_StandardStreamErrors;
1617 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001618 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1619 if (pythonioencoding) {
1620 char *err;
1621 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1622 if (pythonioencoding == NULL) {
1623 PyErr_NoMemory();
1624 goto error;
1625 }
1626 err = strchr(pythonioencoding, ':');
1627 if (err) {
1628 *err = '\0';
1629 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001630 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001631 errors = err;
1632 }
1633 }
1634 if (*pythonioencoding && !encoding) {
1635 encoding = pythonioencoding;
1636 }
1637 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001638 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001639 /* Choose the default error handler based on the current locale */
1640 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001641 }
Nick Coghland6009512014-11-20 21:39:37 +10001642 }
1643
1644 /* Set sys.stdin */
1645 fd = fileno(stdin);
1646 /* Under some conditions stdin, stdout and stderr may not be connected
1647 * and fileno() may point to an invalid file descriptor. For example
1648 * GUI apps don't have valid standard streams by default.
1649 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001650 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1651 if (std == NULL)
1652 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001653 PySys_SetObject("__stdin__", std);
1654 _PySys_SetObjectId(&PyId_stdin, std);
1655 Py_DECREF(std);
1656
1657 /* Set sys.stdout */
1658 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001659 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1660 if (std == NULL)
1661 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001662 PySys_SetObject("__stdout__", std);
1663 _PySys_SetObjectId(&PyId_stdout, std);
1664 Py_DECREF(std);
1665
1666#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1667 /* Set sys.stderr, replaces the preliminary stderr */
1668 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001669 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1670 if (std == NULL)
1671 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001672
1673 /* Same as hack above, pre-import stderr's codec to avoid recursion
1674 when import.c tries to write to stderr in verbose mode. */
1675 encoding_attr = PyObject_GetAttrString(std, "encoding");
1676 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001677 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001678 if (std_encoding != NULL) {
1679 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1680 Py_XDECREF(codec_info);
1681 }
1682 Py_DECREF(encoding_attr);
1683 }
1684 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1685
1686 if (PySys_SetObject("__stderr__", std) < 0) {
1687 Py_DECREF(std);
1688 goto error;
1689 }
1690 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1691 Py_DECREF(std);
1692 goto error;
1693 }
1694 Py_DECREF(std);
1695#endif
1696
1697 if (0) {
1698 error:
1699 status = -1;
1700 }
1701
1702 /* We won't need them anymore. */
1703 if (_Py_StandardStreamEncoding) {
1704 PyMem_RawFree(_Py_StandardStreamEncoding);
1705 _Py_StandardStreamEncoding = NULL;
1706 }
1707 if (_Py_StandardStreamErrors) {
1708 PyMem_RawFree(_Py_StandardStreamErrors);
1709 _Py_StandardStreamErrors = NULL;
1710 }
1711 PyMem_Free(pythonioencoding);
1712 Py_XDECREF(bimod);
1713 Py_XDECREF(iomod);
1714 return status;
1715}
1716
1717
Victor Stinner10dc4842015-03-24 12:01:30 +01001718static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001719_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001720{
Victor Stinner10dc4842015-03-24 12:01:30 +01001721 fputc('\n', stderr);
1722 fflush(stderr);
1723
1724 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001725 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001726}
Victor Stinner791da1c2016-03-14 16:53:12 +01001727
1728/* Print the current exception (if an exception is set) with its traceback,
1729 or display the current Python stack.
1730
1731 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1732 called on catastrophic cases.
1733
1734 Return 1 if the traceback was displayed, 0 otherwise. */
1735
1736static int
1737_Py_FatalError_PrintExc(int fd)
1738{
1739 PyObject *ferr, *res;
1740 PyObject *exception, *v, *tb;
1741 int has_tb;
1742
1743 if (PyThreadState_GET() == NULL) {
1744 /* The GIL is released: trying to acquire it is likely to deadlock,
1745 just give up. */
1746 return 0;
1747 }
1748
1749 PyErr_Fetch(&exception, &v, &tb);
1750 if (exception == NULL) {
1751 /* No current exception */
1752 return 0;
1753 }
1754
1755 ferr = _PySys_GetObjectId(&PyId_stderr);
1756 if (ferr == NULL || ferr == Py_None) {
1757 /* sys.stderr is not set yet or set to None,
1758 no need to try to display the exception */
1759 return 0;
1760 }
1761
1762 PyErr_NormalizeException(&exception, &v, &tb);
1763 if (tb == NULL) {
1764 tb = Py_None;
1765 Py_INCREF(tb);
1766 }
1767 PyException_SetTraceback(v, tb);
1768 if (exception == NULL) {
1769 /* PyErr_NormalizeException() failed */
1770 return 0;
1771 }
1772
1773 has_tb = (tb != Py_None);
1774 PyErr_Display(exception, v, tb);
1775 Py_XDECREF(exception);
1776 Py_XDECREF(v);
1777 Py_XDECREF(tb);
1778
1779 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001780 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001781 if (res == NULL)
1782 PyErr_Clear();
1783 else
1784 Py_DECREF(res);
1785
1786 return has_tb;
1787}
1788
Nick Coghland6009512014-11-20 21:39:37 +10001789/* Print fatal error message and abort */
1790
1791void
1792Py_FatalError(const char *msg)
1793{
1794 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001795 static int reentrant = 0;
1796#ifdef MS_WINDOWS
1797 size_t len;
1798 WCHAR* buffer;
1799 size_t i;
1800#endif
1801
1802 if (reentrant) {
1803 /* Py_FatalError() caused a second fatal error.
1804 Example: flush_std_files() raises a recursion error. */
1805 goto exit;
1806 }
1807 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001808
1809 fprintf(stderr, "Fatal Python error: %s\n", msg);
1810 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001811
Victor Stinnere0deff32015-03-24 13:46:18 +01001812 /* Print the exception (if an exception is set) with its traceback,
1813 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001814 if (!_Py_FatalError_PrintExc(fd))
1815 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001816
Victor Stinner2025d782016-03-16 23:19:15 +01001817 /* The main purpose of faulthandler is to display the traceback. We already
1818 * did our best to display it. So faulthandler can now be disabled.
1819 * (Don't trigger it on abort().) */
1820 _PyFaulthandler_Fini();
1821
Victor Stinner791da1c2016-03-14 16:53:12 +01001822 /* Check if the current Python thread hold the GIL */
1823 if (PyThreadState_GET() != NULL) {
1824 /* Flush sys.stdout and sys.stderr */
1825 flush_std_files();
1826 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001827
Nick Coghland6009512014-11-20 21:39:37 +10001828#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001829 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001830
Victor Stinner53345a42015-03-25 01:55:14 +01001831 /* Convert the message to wchar_t. This uses a simple one-to-one
1832 conversion, assuming that the this error message actually uses ASCII
1833 only. If this ceases to be true, we will have to convert. */
1834 buffer = alloca( (len+1) * (sizeof *buffer));
1835 for( i=0; i<=len; ++i)
1836 buffer[i] = msg[i];
1837 OutputDebugStringW(L"Fatal Python error: ");
1838 OutputDebugStringW(buffer);
1839 OutputDebugStringW(L"\n");
1840#endif /* MS_WINDOWS */
1841
1842exit:
1843#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001844 DebugBreak();
1845#endif
Nick Coghland6009512014-11-20 21:39:37 +10001846 abort();
1847}
1848
1849/* Clean up and exit */
1850
1851#ifdef WITH_THREAD
Victor Stinnerd7292b52016-06-17 12:29:00 +02001852# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001853#endif
1854
1855static void (*pyexitfunc)(void) = NULL;
1856/* For the atexit module. */
1857void _Py_PyAtExit(void (*func)(void))
1858{
1859 pyexitfunc = func;
1860}
1861
1862static void
1863call_py_exitfuncs(void)
1864{
1865 if (pyexitfunc == NULL)
1866 return;
1867
1868 (*pyexitfunc)();
1869 PyErr_Clear();
1870}
1871
1872/* Wait until threading._shutdown completes, provided
1873 the threading module was imported in the first place.
1874 The shutdown routine will wait until all non-daemon
1875 "threading" threads have completed. */
1876static void
1877wait_for_thread_shutdown(void)
1878{
1879#ifdef WITH_THREAD
1880 _Py_IDENTIFIER(_shutdown);
1881 PyObject *result;
1882 PyThreadState *tstate = PyThreadState_GET();
1883 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1884 "threading");
1885 if (threading == NULL) {
1886 /* threading not imported */
1887 PyErr_Clear();
1888 return;
1889 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001890 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001891 if (result == NULL) {
1892 PyErr_WriteUnraisable(threading);
1893 }
1894 else {
1895 Py_DECREF(result);
1896 }
1897 Py_DECREF(threading);
1898#endif
1899}
1900
1901#define NEXITFUNCS 32
1902static void (*exitfuncs[NEXITFUNCS])(void);
1903static int nexitfuncs = 0;
1904
1905int Py_AtExit(void (*func)(void))
1906{
1907 if (nexitfuncs >= NEXITFUNCS)
1908 return -1;
1909 exitfuncs[nexitfuncs++] = func;
1910 return 0;
1911}
1912
1913static void
1914call_ll_exitfuncs(void)
1915{
1916 while (nexitfuncs > 0)
1917 (*exitfuncs[--nexitfuncs])();
1918
1919 fflush(stdout);
1920 fflush(stderr);
1921}
1922
1923void
1924Py_Exit(int sts)
1925{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001926 if (Py_FinalizeEx() < 0) {
1927 sts = 120;
1928 }
Nick Coghland6009512014-11-20 21:39:37 +10001929
1930 exit(sts);
1931}
1932
1933static void
1934initsigs(void)
1935{
1936#ifdef SIGPIPE
1937 PyOS_setsig(SIGPIPE, SIG_IGN);
1938#endif
1939#ifdef SIGXFZ
1940 PyOS_setsig(SIGXFZ, SIG_IGN);
1941#endif
1942#ifdef SIGXFSZ
1943 PyOS_setsig(SIGXFSZ, SIG_IGN);
1944#endif
1945 PyOS_InitInterrupts(); /* May imply initsignal() */
1946 if (PyErr_Occurred()) {
1947 Py_FatalError("Py_Initialize: can't import signal");
1948 }
1949}
1950
1951
1952/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1953 *
1954 * All of the code in this function must only use async-signal-safe functions,
1955 * listed at `man 7 signal` or
1956 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1957 */
1958void
1959_Py_RestoreSignals(void)
1960{
1961#ifdef SIGPIPE
1962 PyOS_setsig(SIGPIPE, SIG_DFL);
1963#endif
1964#ifdef SIGXFZ
1965 PyOS_setsig(SIGXFZ, SIG_DFL);
1966#endif
1967#ifdef SIGXFSZ
1968 PyOS_setsig(SIGXFSZ, SIG_DFL);
1969#endif
1970}
1971
1972
1973/*
1974 * The file descriptor fd is considered ``interactive'' if either
1975 * a) isatty(fd) is TRUE, or
1976 * b) the -i flag was given, and the filename associated with
1977 * the descriptor is NULL or "<stdin>" or "???".
1978 */
1979int
1980Py_FdIsInteractive(FILE *fp, const char *filename)
1981{
1982 if (isatty((int)fileno(fp)))
1983 return 1;
1984 if (!Py_InteractiveFlag)
1985 return 0;
1986 return (filename == NULL) ||
1987 (strcmp(filename, "<stdin>") == 0) ||
1988 (strcmp(filename, "???") == 0);
1989}
1990
1991
Nick Coghland6009512014-11-20 21:39:37 +10001992/* Wrappers around sigaction() or signal(). */
1993
1994PyOS_sighandler_t
1995PyOS_getsig(int sig)
1996{
1997#ifdef HAVE_SIGACTION
1998 struct sigaction context;
1999 if (sigaction(sig, NULL, &context) == -1)
2000 return SIG_ERR;
2001 return context.sa_handler;
2002#else
2003 PyOS_sighandler_t handler;
2004/* Special signal handling for the secure CRT in Visual Studio 2005 */
2005#if defined(_MSC_VER) && _MSC_VER >= 1400
2006 switch (sig) {
2007 /* Only these signals are valid */
2008 case SIGINT:
2009 case SIGILL:
2010 case SIGFPE:
2011 case SIGSEGV:
2012 case SIGTERM:
2013 case SIGBREAK:
2014 case SIGABRT:
2015 break;
2016 /* Don't call signal() with other values or it will assert */
2017 default:
2018 return SIG_ERR;
2019 }
2020#endif /* _MSC_VER && _MSC_VER >= 1400 */
2021 handler = signal(sig, SIG_IGN);
2022 if (handler != SIG_ERR)
2023 signal(sig, handler);
2024 return handler;
2025#endif
2026}
2027
2028/*
2029 * All of the code in this function must only use async-signal-safe functions,
2030 * listed at `man 7 signal` or
2031 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2032 */
2033PyOS_sighandler_t
2034PyOS_setsig(int sig, PyOS_sighandler_t handler)
2035{
2036#ifdef HAVE_SIGACTION
2037 /* Some code in Modules/signalmodule.c depends on sigaction() being
2038 * used here if HAVE_SIGACTION is defined. Fix that if this code
2039 * changes to invalidate that assumption.
2040 */
2041 struct sigaction context, ocontext;
2042 context.sa_handler = handler;
2043 sigemptyset(&context.sa_mask);
2044 context.sa_flags = 0;
2045 if (sigaction(sig, &context, &ocontext) == -1)
2046 return SIG_ERR;
2047 return ocontext.sa_handler;
2048#else
2049 PyOS_sighandler_t oldhandler;
2050 oldhandler = signal(sig, handler);
2051#ifdef HAVE_SIGINTERRUPT
2052 siginterrupt(sig, 1);
2053#endif
2054 return oldhandler;
2055#endif
2056}
2057
2058#ifdef __cplusplus
2059}
2060#endif