blob: 8c626075d5d12060a1dda5d07ef8c679eb805b62 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054static _PyInitError add_main_module(PyInterpreterState *interp);
55static _PyInitError initfsencoding(PyInterpreterState *interp);
56static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010057static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080058static _PyInitError initsigs(void);
Nick Coghland6009512014-11-20 21:39:37 +100059static 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);
Victor Stinnera7368ac2017-11-15 18:11:45 -080067extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100068extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080070extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100071extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
Nick Coghland6009512014-11-20 21:39:37 +100074extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100076
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080_PyRuntime_Initialize(void)
81{
82 /* XXX We only initialize once in the process, which aligns with
83 the static initialization of the former globals now found in
84 _PyRuntime. However, _PyRuntime *should* be initialized with
85 every Py_Initialize() call, but doing so breaks the runtime.
86 This is because the runtime state is not properly finalized
87 currently. */
88 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089 if (initialized) {
90 return _Py_INIT_OK();
91 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080093
94 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Nick Coghland6009512014-11-20 21:39:37 +1000119int Py_FrozenFlag; /* Needed by getpath.c */
120int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000122int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
123int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
124int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
125int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700126#ifdef MS_WINDOWS
127int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700128int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700129#endif
Nick Coghland6009512014-11-20 21:39:37 +1000130
Nick Coghland6009512014-11-20 21:39:37 +1000131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
139{
140 return PyImport_ImportModule("warnings");
141}
142
Eric Snowc7ec9982017-05-23 23:00:52 -0700143
Eric Snow1abcf672017-05-23 21:46:51 -0700144/* APIs to access the initialization flags
145 *
146 * Can be called prior to Py_Initialize.
147 */
Nick Coghland6009512014-11-20 21:39:37 +1000148
Eric Snow1abcf672017-05-23 21:46:51 -0700149int
150_Py_IsCoreInitialized(void)
151{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600152 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700153}
Nick Coghland6009512014-11-20 21:39:37 +1000154
155int
156Py_IsInitialized(void)
157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000159}
160
161/* Helper to allow an embedding application to override the normal
162 * mechanism that attempts to figure out an appropriate IO encoding
163 */
164
165static char *_Py_StandardStreamEncoding = NULL;
166static char *_Py_StandardStreamErrors = NULL;
167
168int
169Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
170{
171 if (Py_IsInitialized()) {
172 /* This is too late to have any effect */
173 return -1;
174 }
175 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
176 * initialised yet.
177 *
178 * However, the raw memory allocators are initialised appropriately
179 * as C static variables, so _PyMem_RawStrdup is OK even though
180 * Py_Initialize hasn't been called yet.
181 */
182 if (encoding) {
183 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
184 if (!_Py_StandardStreamEncoding) {
185 return -2;
186 }
187 }
188 if (errors) {
189 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
190 if (!_Py_StandardStreamErrors) {
191 if (_Py_StandardStreamEncoding) {
192 PyMem_RawFree(_Py_StandardStreamEncoding);
193 }
194 return -3;
195 }
196 }
Steve Dower39294992016-08-30 21:22:36 -0700197#ifdef MS_WINDOWS
198 if (_Py_StandardStreamEncoding) {
199 /* Overriding the stream encoding implies legacy streams */
200 Py_LegacyWindowsStdioFlag = 1;
201 }
202#endif
Nick Coghland6009512014-11-20 21:39:37 +1000203 return 0;
204}
205
Nick Coghlan6ea41862017-06-11 13:16:15 +1000206
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000207/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
208 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000209 initializations fail, a fatal error is issued and the function does
210 not return. On return, the first thread and interpreter state have
211 been created.
212
213 Locking: you must hold the interpreter lock while calling this.
214 (If the lock has not yet been initialized, that's equivalent to
215 having the lock, but you cannot use multiple threads.)
216
217*/
218
Nick Coghland6009512014-11-20 21:39:37 +1000219static char*
220get_codec_name(const char *encoding)
221{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200222 const char *name_utf8;
223 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000224 PyObject *codec, *name = NULL;
225
226 codec = _PyCodec_Lookup(encoding);
227 if (!codec)
228 goto error;
229
230 name = _PyObject_GetAttrId(codec, &PyId_name);
231 Py_CLEAR(codec);
232 if (!name)
233 goto error;
234
Serhiy Storchaka06515832016-11-20 09:13:07 +0200235 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000236 if (name_utf8 == NULL)
237 goto error;
238 name_str = _PyMem_RawStrdup(name_utf8);
239 Py_DECREF(name);
240 if (name_str == NULL) {
241 PyErr_NoMemory();
242 return NULL;
243 }
244 return name_str;
245
246error:
247 Py_XDECREF(codec);
248 Py_XDECREF(name);
249 return NULL;
250}
251
252static char*
253get_locale_encoding(void)
254{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700255#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000256 char* codeset = nl_langinfo(CODESET);
257 if (!codeset || codeset[0] == '\0') {
258 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
259 return NULL;
260 }
261 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200262#elif defined(__ANDROID__)
263 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000264#else
265 PyErr_SetNone(PyExc_NotImplementedError);
266 return NULL;
267#endif
268}
269
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800270static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700271initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000272{
273 PyObject *importlib;
274 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000275 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800276 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000277
278 /* Import _importlib through its frozen version, _frozen_importlib. */
279 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800280 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000281 }
282 else if (Py_VerboseFlag) {
283 PySys_FormatStderr("import _frozen_importlib # frozen\n");
284 }
285 importlib = PyImport_AddModule("_frozen_importlib");
286 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800287 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000288 }
289 interp->importlib = importlib;
290 Py_INCREF(interp->importlib);
291
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300292 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
293 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800294 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300295 Py_INCREF(interp->import_func);
296
Victor Stinnercd6e6942015-09-18 09:11:57 +0200297 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000298 impmod = PyInit_imp();
299 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800300 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000301 }
302 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200303 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000304 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600305 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800306 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000307 }
308
Victor Stinnercd6e6942015-09-18 09:11:57 +0200309 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000310 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200311 if (value != NULL) {
312 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700313 value = PyObject_CallMethod(importlib,
314 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200315 }
Nick Coghland6009512014-11-20 21:39:37 +1000316 if (value == NULL) {
317 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800318 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000319 }
320 Py_DECREF(value);
321 Py_DECREF(impmod);
322
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800323 err = _PyImportZip_Init();
324 if (_Py_INIT_FAILED(err)) {
325 return err;
326 }
327
328 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000329}
330
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800331static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700332initexternalimport(PyInterpreterState *interp)
333{
334 PyObject *value;
335 value = PyObject_CallMethod(interp->importlib,
336 "_install_external_importers", "");
337 if (value == NULL) {
338 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800339 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700340 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200341 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800342 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700343}
Nick Coghland6009512014-11-20 21:39:37 +1000344
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345/* Helper functions to better handle the legacy C locale
346 *
347 * The legacy C locale assumes ASCII as the default text encoding, which
348 * causes problems not only for the CPython runtime, but also other
349 * components like GNU readline.
350 *
351 * Accordingly, when the CLI detects it, it attempts to coerce it to a
352 * more capable UTF-8 based alternative as follows:
353 *
354 * if (_Py_LegacyLocaleDetected()) {
355 * _Py_CoerceLegacyLocale();
356 * }
357 *
358 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
359 *
360 * Locale coercion also impacts the default error handler for the standard
361 * streams: while the usual default is "strict", the default for the legacy
362 * C locale and for any of the coercion target locales is "surrogateescape".
363 */
364
365int
366_Py_LegacyLocaleDetected(void)
367{
368#ifndef MS_WINDOWS
369 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000370 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
371 * the POSIX locale as a simple alias for the C locale, so
372 * we may also want to check for that explicitly.
373 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000374 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
375 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
376#else
377 /* Windows uses code pages instead of locales, so no locale is legacy */
378 return 0;
379#endif
380}
381
Nick Coghlaneb817952017-06-18 12:29:42 +1000382static const char *_C_LOCALE_WARNING =
383 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
384 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
385 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
386 "locales is recommended.\n";
387
388static int
389_legacy_locale_warnings_enabled(void)
390{
391 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
392 return (coerce_c_locale != NULL &&
393 strncmp(coerce_c_locale, "warn", 5) == 0);
394}
395
396static void
397_emit_stderr_warning_for_legacy_locale(void)
398{
399 if (_legacy_locale_warnings_enabled()) {
400 if (_Py_LegacyLocaleDetected()) {
401 fprintf(stderr, "%s", _C_LOCALE_WARNING);
402 }
403 }
404}
405
Nick Coghlan6ea41862017-06-11 13:16:15 +1000406typedef struct _CandidateLocale {
407 const char *locale_name; /* The locale to try as a coercion target */
408} _LocaleCoercionTarget;
409
410static _LocaleCoercionTarget _TARGET_LOCALES[] = {
411 {"C.UTF-8"},
412 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000413 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000414 {NULL}
415};
416
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200417static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000418get_default_standard_stream_error_handler(void)
419{
420 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
421 if (ctype_loc != NULL) {
422 /* "surrogateescape" is the default in the legacy C locale */
423 if (strcmp(ctype_loc, "C") == 0) {
424 return "surrogateescape";
425 }
426
427#ifdef PY_COERCE_C_LOCALE
428 /* "surrogateescape" is the default in locale coercion target locales */
429 const _LocaleCoercionTarget *target = NULL;
430 for (target = _TARGET_LOCALES; target->locale_name; target++) {
431 if (strcmp(ctype_loc, target->locale_name) == 0) {
432 return "surrogateescape";
433 }
434 }
435#endif
436 }
437
438 /* Otherwise return NULL to request the typical default error handler */
439 return NULL;
440}
441
442#ifdef PY_COERCE_C_LOCALE
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200443static const char _C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000444 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
445 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
446
447static void
448_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
449{
450 const char *newloc = target->locale_name;
451
452 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100453 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000454
455 /* Set the relevant locale environment variable */
456 if (setenv("LC_CTYPE", newloc, 1)) {
457 fprintf(stderr,
458 "Error setting LC_CTYPE, skipping C locale coercion\n");
459 return;
460 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000461 if (_legacy_locale_warnings_enabled()) {
462 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
463 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000464
465 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100466 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000467}
468#endif
469
470void
471_Py_CoerceLegacyLocale(void)
472{
473#ifdef PY_COERCE_C_LOCALE
474 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
475 * the locale settings *before* we try to do anything with the command
476 * line arguments. For cross-platform debugging purposes, we also need
477 * to give end users a way to force even scripts that are otherwise
478 * isolated from their environment to use the legacy ASCII-centric C
479 * locale.
480 *
481 * Ignoring -E and -I is safe from a security perspective, as we only use
482 * the setting to turn *off* the implicit locale coercion, and anyone with
483 * access to the process environment already has the ability to set
484 * `LC_ALL=C` to override the C level locale settings anyway.
485 */
486 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
487 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
488 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
489 const char *locale_override = getenv("LC_ALL");
490 if (locale_override == NULL || *locale_override == '\0') {
491 /* LC_ALL is also not set (or is set to an empty string) */
492 const _LocaleCoercionTarget *target = NULL;
493 for (target = _TARGET_LOCALES; target->locale_name; target++) {
494 const char *new_locale = setlocale(LC_CTYPE,
495 target->locale_name);
496 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100497#if !defined(__APPLE__) && !defined(__ANDROID__) && \
498 defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghlan18974c32017-06-30 00:48:14 +1000499 /* Also ensure that nl_langinfo works in this locale */
500 char *codeset = nl_langinfo(CODESET);
501 if (!codeset || *codeset == '\0') {
502 /* CODESET is not set or empty, so skip coercion */
503 new_locale = NULL;
xdegaye1588be62017-11-12 12:45:59 +0100504 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlan18974c32017-06-30 00:48:14 +1000505 continue;
506 }
507#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000508 /* Successfully configured locale, so make it the default */
509 _coerce_default_locale_settings(target);
510 return;
511 }
512 }
513 }
514 }
515 /* No C locale warning here, as Py_Initialize will emit one later */
516#endif
517}
518
xdegaye1588be62017-11-12 12:45:59 +0100519/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
520 * isolate the idiosyncrasies of different libc implementations. It reads the
521 * appropriate environment variable and uses its value to select the locale for
522 * 'category'. */
523char *
524_Py_SetLocaleFromEnv(int category)
525{
526#ifdef __ANDROID__
527 const char *locale;
528 const char **pvar;
529#ifdef PY_COERCE_C_LOCALE
530 const char *coerce_c_locale;
531#endif
532 const char *utf8_locale = "C.UTF-8";
533 const char *env_var_set[] = {
534 "LC_ALL",
535 "LC_CTYPE",
536 "LANG",
537 NULL,
538 };
539
540 /* Android setlocale(category, "") doesn't check the environment variables
541 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
542 * check the environment variables listed in env_var_set. */
543 for (pvar=env_var_set; *pvar; pvar++) {
544 locale = getenv(*pvar);
545 if (locale != NULL && *locale != '\0') {
546 if (strcmp(locale, utf8_locale) == 0 ||
547 strcmp(locale, "en_US.UTF-8") == 0) {
548 return setlocale(category, utf8_locale);
549 }
550 return setlocale(category, "C");
551 }
552 }
553
554 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
555 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
556 * Quote from POSIX section "8.2 Internationalization Variables":
557 * "4. If the LANG environment variable is not set or is set to the empty
558 * string, the implementation-defined default locale shall be used." */
559
560#ifdef PY_COERCE_C_LOCALE
561 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
562 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
563 /* Some other ported code may check the environment variables (e.g. in
564 * extension modules), so we make sure that they match the locale
565 * configuration */
566 if (setenv("LC_CTYPE", utf8_locale, 1)) {
567 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
568 "environment variable to %s\n", utf8_locale);
569 }
570 }
571#endif
572 return setlocale(category, utf8_locale);
573#else /* __ANDROID__ */
574 return setlocale(category, "");
575#endif /* __ANDROID__ */
576}
577
Nick Coghlan6ea41862017-06-11 13:16:15 +1000578
Eric Snow1abcf672017-05-23 21:46:51 -0700579/* Global initializations. Can be undone by Py_Finalize(). Don't
580 call this twice without an intervening Py_Finalize() call.
581
582 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
583 must have a corresponding call to Py_Finalize.
584
585 Locking: you must hold the interpreter lock while calling these APIs.
586 (If the lock has not yet been initialized, that's equivalent to
587 having the lock, but you cannot use multiple threads.)
588
589*/
590
591/* Begin interpreter initialization
592 *
593 * On return, the first thread and interpreter state have been created,
594 * but the compiler, signal handling, multithreading and
595 * multiple interpreter support, and codec infrastructure are not yet
596 * available.
597 *
598 * The import system will support builtin and frozen modules only.
599 * The only supported io is writing to sys.stderr
600 *
601 * If any operation invoked by this function fails, a fatal error is
602 * issued and the function does not return.
603 *
604 * Any code invoked from this function should *not* assume it has access
605 * to the Python C API (unless the API is explicitly listed as being
606 * safe to call without calling Py_Initialize first)
607 */
608
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800609_PyInitError
Victor Stinnerda273412017-12-15 01:46:02 +0100610_Py_InitializeCore(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000611{
Victor Stinnerda273412017-12-15 01:46:02 +0100612 assert(core_config != NULL);
613
Nick Coghland6009512014-11-20 21:39:37 +1000614 PyInterpreterState *interp;
615 PyThreadState *tstate;
616 PyObject *bimod, *sysmod, *pstderr;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800617 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000618
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800619 err = _PyRuntime_Initialize();
620 if (_Py_INIT_FAILED(err)) {
621 return err;
622 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600623
Victor Stinnerda273412017-12-15 01:46:02 +0100624 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
Victor Stinner5d39e042017-11-29 17:20:38 +0100625 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800626 }
627
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600628 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800629 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700630 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600631 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800632 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700633 }
634
635 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
636 * threads behave a little more gracefully at interpreter shutdown.
637 * We clobber it here so the new interpreter can start with a clean
638 * slate.
639 *
640 * However, this may still lead to misbehaviour if there are daemon
641 * threads still hanging around from a previous Py_Initialize/Finalize
642 * pair :(
643 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600644 _PyRuntime.finalizing = NULL;
645
Nick Coghlan6ea41862017-06-11 13:16:15 +1000646#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000647 /* Set up the LC_CTYPE locale, so we can obtain
648 the locale's charset without having to switch
649 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100650 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlaneb817952017-06-18 12:29:42 +1000651 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000652#endif
Nick Coghland6009512014-11-20 21:39:37 +1000653
Victor Stinnerda273412017-12-15 01:46:02 +0100654 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800655 if (_Py_INIT_FAILED(err)) {
656 return err;
657 }
658
Victor Stinnerda273412017-12-15 01:46:02 +0100659 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700660 /* Random or non-zero hash seed */
661 Py_HashRandomizationFlag = 1;
662 }
Nick Coghland6009512014-11-20 21:39:37 +1000663
Victor Stinnera7368ac2017-11-15 18:11:45 -0800664 err = _PyInterpreterState_Enable(&_PyRuntime);
665 if (_Py_INIT_FAILED(err)) {
666 return err;
667 }
668
Nick Coghland6009512014-11-20 21:39:37 +1000669 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100670 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800671 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100672 }
673
674 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
675 return _Py_INIT_ERR("failed to copy core config");
676 }
Nick Coghland6009512014-11-20 21:39:37 +1000677
678 tstate = PyThreadState_New(interp);
679 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800680 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000681 (void) PyThreadState_Swap(tstate);
682
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000683 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000684 destroying the GIL might fail when it is being referenced from
685 another running thread (see issue #9901).
686 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000687 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000688 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000689 /* Auto-thread-state API */
690 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000691
692 _Py_ReadyTypes();
693
694 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800695 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000696
697 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800698 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000699
700 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800701 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000702
703 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800704 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000705
Eric Snowd393c1b2017-09-14 12:18:12 -0600706 PyObject *modules = PyDict_New();
707 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800708 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600709 interp->modules = modules;
710
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800711 err = _PySys_BeginInit(&sysmod);
712 if (_Py_INIT_FAILED(err)) {
713 return err;
714 }
715
Eric Snowd393c1b2017-09-14 12:18:12 -0600716 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800717 if (interp->sysdict == NULL) {
718 return _Py_INIT_ERR("can't initialize sys dict");
719 }
720
Eric Snowd393c1b2017-09-14 12:18:12 -0600721 Py_INCREF(interp->sysdict);
722 PyDict_SetItemString(interp->sysdict, "modules", modules);
723 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000724
725 /* Init Unicode implementation; relies on the codec registry */
726 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800727 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700728
Nick Coghland6009512014-11-20 21:39:37 +1000729 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800730 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000731
732 bimod = _PyBuiltin_Init();
733 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800734 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600735 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000736 interp->builtins = PyModule_GetDict(bimod);
737 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800738 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000739 Py_INCREF(interp->builtins);
740
741 /* initialize builtin exceptions */
742 _PyExc_Init(bimod);
743
Nick Coghland6009512014-11-20 21:39:37 +1000744 /* Set up a preliminary stderr printer until we have enough
745 infrastructure for the io module in place. */
746 pstderr = PyFile_NewStdPrinter(fileno(stderr));
747 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800748 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000749 _PySys_SetObjectId(&PyId_stderr, pstderr);
750 PySys_SetObject("__stderr__", pstderr);
751 Py_DECREF(pstderr);
752
Victor Stinner672b6ba2017-12-06 17:25:50 +0100753 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800754 if (_Py_INIT_FAILED(err)) {
755 return err;
756 }
Nick Coghland6009512014-11-20 21:39:37 +1000757
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800758 err = _PyImportHooks_Init();
759 if (_Py_INIT_FAILED(err)) {
760 return err;
761 }
Nick Coghland6009512014-11-20 21:39:37 +1000762
763 /* Initialize _warnings. */
Victor Stinner1f151112017-11-23 10:43:14 +0100764 if (_PyWarnings_InitWithConfig(&interp->core_config) == NULL) {
765 return _Py_INIT_ERR("can't initialize warnings");
766 }
Nick Coghland6009512014-11-20 21:39:37 +1000767
Eric Snow1abcf672017-05-23 21:46:51 -0700768 /* This call sets up builtin and frozen import support */
769 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800770 err = initimport(interp, sysmod);
771 if (_Py_INIT_FAILED(err)) {
772 return err;
773 }
Eric Snow1abcf672017-05-23 21:46:51 -0700774 }
775
776 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600777 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800778 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700779}
780
Eric Snowc7ec9982017-05-23 23:00:52 -0700781/* Update interpreter state based on supplied configuration settings
782 *
783 * After calling this function, most of the restrictions on the interpreter
784 * are lifted. The only remaining incomplete settings are those related
785 * to the main module (sys.argv[0], __main__ metadata)
786 *
787 * Calling this when the interpreter is not initializing, is already
788 * initialized or without a valid current thread state is a fatal error.
789 * Other errors should be reported as normal Python exceptions with a
790 * non-zero return code.
791 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800792_PyInitError
793_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700794{
795 PyInterpreterState *interp;
796 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800797 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700798
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800800 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700801 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600802 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800803 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700804 }
805
Eric Snow1abcf672017-05-23 21:46:51 -0700806 /* Get current thread state and interpreter pointer */
807 tstate = PyThreadState_GET();
808 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800809 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700810 interp = tstate->interp;
811 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800812 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700813
814 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100815 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
816 return _Py_INIT_ERR("failed to copy main interpreter config");
817 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700818
Eric Snow1abcf672017-05-23 21:46:51 -0700819 if (interp->core_config._disable_importlib) {
820 /* Special mode for freeze_importlib: run with no import system
821 *
822 * This means anything which needs support from extension modules
823 * or pure Python code in the standard library won't work.
824 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800826 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700827 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100828
Victor Stinner33c377e2017-12-05 15:12:41 +0100829 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100831 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200832
Victor Stinner41264f12017-12-15 02:05:29 +0100833 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800834 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100835 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800836
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 err = initexternalimport(interp);
838 if (_Py_INIT_FAILED(err)) {
839 return err;
840 }
Nick Coghland6009512014-11-20 21:39:37 +1000841
842 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800843 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800844 if (_Py_INIT_FAILED(err)) {
845 return err;
846 }
Nick Coghland6009512014-11-20 21:39:37 +1000847
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800848 err = initfsencoding(interp);
849 if (_Py_INIT_FAILED(err)) {
850 return err;
851 }
Nick Coghland6009512014-11-20 21:39:37 +1000852
Victor Stinner1f151112017-11-23 10:43:14 +0100853 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800854 err = initsigs(); /* Signal handling stuff, including initintr() */
855 if (_Py_INIT_FAILED(err)) {
856 return err;
857 }
858 }
Nick Coghland6009512014-11-20 21:39:37 +1000859
Victor Stinnera7368ac2017-11-15 18:11:45 -0800860 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800861 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000862
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800863 err = add_main_module(interp);
864 if (_Py_INIT_FAILED(err)) {
865 return err;
866 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800867
Victor Stinner91106cd2017-12-13 12:29:09 +0100868 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800869 if (_Py_INIT_FAILED(err)) {
870 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800871 }
Nick Coghland6009512014-11-20 21:39:37 +1000872
873 /* Initialize warnings. */
874 if (PySys_HasWarnOptions()) {
875 PyObject *warnings_module = PyImport_ImportModule("warnings");
876 if (warnings_module == NULL) {
877 fprintf(stderr, "'import warnings' failed; traceback:\n");
878 PyErr_Print();
879 }
880 Py_XDECREF(warnings_module);
881 }
882
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600883 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700884
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800885 if (!Py_NoSiteFlag) {
886 err = initsite(); /* Module site */
887 if (_Py_INIT_FAILED(err)) {
888 return err;
889 }
890 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000892}
893
Eric Snowc7ec9982017-05-23 23:00:52 -0700894#undef _INIT_DEBUG_PRINT
895
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700897_Py_InitializeEx_Private(int install_sigs, int install_importlib)
898{
899 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700900 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700902
Eric Snow1abcf672017-05-23 21:46:51 -0700903 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
904 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700905 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800906
Victor Stinnerda273412017-12-15 01:46:02 +0100907 err = _PyCoreConfig_ReadEnv(&core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800908 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100909 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800910 }
911
Victor Stinnerda273412017-12-15 01:46:02 +0100912 err = _Py_InitializeCore(&core_config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100913 if (_Py_INIT_FAILED(err)) {
914 goto done;
915 }
916
Victor Stinnerb5fd9ad2017-12-14 02:20:52 +0100917 err = _PyMainInterpreterConfig_Read(&config, &core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800918 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100919 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800920 }
921
922 err = _Py_InitializeMainInterpreter(&config);
923 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100924 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800925 }
926
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100927 err = _Py_INIT_OK();
928
929done:
Victor Stinnerb5fd9ad2017-12-14 02:20:52 +0100930 _PyCoreConfig_Clear(&core_config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100931 _PyMainInterpreterConfig_Clear(&config);
932 return err;
Eric Snow1abcf672017-05-23 21:46:51 -0700933}
934
935
936void
Nick Coghland6009512014-11-20 21:39:37 +1000937Py_InitializeEx(int install_sigs)
938{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
940 if (_Py_INIT_FAILED(err)) {
941 _Py_FatalInitError(err);
942 }
Nick Coghland6009512014-11-20 21:39:37 +1000943}
944
945void
946Py_Initialize(void)
947{
948 Py_InitializeEx(1);
949}
950
951
952#ifdef COUNT_ALLOCS
953extern void dump_counts(FILE*);
954#endif
955
956/* Flush stdout and stderr */
957
958static int
959file_is_closed(PyObject *fobj)
960{
961 int r;
962 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
963 if (tmp == NULL) {
964 PyErr_Clear();
965 return 0;
966 }
967 r = PyObject_IsTrue(tmp);
968 Py_DECREF(tmp);
969 if (r < 0)
970 PyErr_Clear();
971 return r > 0;
972}
973
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000974static int
Nick Coghland6009512014-11-20 21:39:37 +1000975flush_std_files(void)
976{
977 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
978 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
979 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000980 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000981
982 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700983 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000984 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000985 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000986 status = -1;
987 }
Nick Coghland6009512014-11-20 21:39:37 +1000988 else
989 Py_DECREF(tmp);
990 }
991
992 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700993 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000994 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000995 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000996 status = -1;
997 }
Nick Coghland6009512014-11-20 21:39:37 +1000998 else
999 Py_DECREF(tmp);
1000 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001001
1002 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001003}
1004
1005/* Undo the effect of Py_Initialize().
1006
1007 Beware: if multiple interpreter and/or thread states exist, these
1008 are not wiped out; only the current thread and interpreter state
1009 are deleted. But since everything else is deleted, those other
1010 interpreter and thread states should no longer be used.
1011
1012 (XXX We should do better, e.g. wipe out all interpreters and
1013 threads.)
1014
1015 Locking: as above.
1016
1017*/
1018
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019int
1020Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001021{
1022 PyInterpreterState *interp;
1023 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001024 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001025
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001026 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001027 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001028
1029 wait_for_thread_shutdown();
1030
1031 /* The interpreter is still entirely intact at this point, and the
1032 * exit funcs may be relying on that. In particular, if some thread
1033 * or exit func is still waiting to do an import, the import machinery
1034 * expects Py_IsInitialized() to return true. So don't say the
1035 * interpreter is uninitialized until after the exit funcs have run.
1036 * Note that Threading.py uses an exit func to do a join on all the
1037 * threads created thru it, so this also protects pending imports in
1038 * the threads created via Threading.
1039 */
1040 call_py_exitfuncs();
1041
1042 /* Get current thread state and interpreter pointer */
1043 tstate = PyThreadState_GET();
1044 interp = tstate->interp;
1045
Victor Stinnerda273412017-12-15 01:46:02 +01001046 /* Copy the core config, PyInterpreterState_Delete() free
1047 the core config memory */
1048 int show_ref_count = interp->core_config.show_ref_count;
1049 int dump_refs = interp->core_config.dump_refs;
1050 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner6bf992a2017-12-06 17:26:10 +01001051
Nick Coghland6009512014-11-20 21:39:37 +10001052 /* Remaining threads (e.g. daemon threads) will automatically exit
1053 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001054 _PyRuntime.finalizing = tstate;
1055 _PyRuntime.initialized = 0;
1056 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001057
Victor Stinnere0deff32015-03-24 13:46:18 +01001058 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001059 if (flush_std_files() < 0) {
1060 status = -1;
1061 }
Nick Coghland6009512014-11-20 21:39:37 +10001062
1063 /* Disable signal handling */
1064 PyOS_FiniInterrupts();
1065
1066 /* Collect garbage. This may call finalizers; it's nice to call these
1067 * before all modules are destroyed.
1068 * XXX If a __del__ or weakref callback is triggered here, and tries to
1069 * XXX import a module, bad things can happen, because Python no
1070 * XXX longer believes it's initialized.
1071 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1072 * XXX is easy to provoke that way. I've also seen, e.g.,
1073 * XXX Exception exceptions.ImportError: 'No module named sha'
1074 * XXX in <function callback at 0x008F5718> ignored
1075 * XXX but I'm unclear on exactly how that one happens. In any case,
1076 * XXX I haven't seen a real-life report of either of these.
1077 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001078 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001079#ifdef COUNT_ALLOCS
1080 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1081 each collection might release some types from the type
1082 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001083 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001084 /* nothing */;
1085#endif
Eric Snowdae02762017-09-14 00:35:58 -07001086
Nick Coghland6009512014-11-20 21:39:37 +10001087 /* Destroy all modules */
1088 PyImport_Cleanup();
1089
Victor Stinnere0deff32015-03-24 13:46:18 +01001090 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001091 if (flush_std_files() < 0) {
1092 status = -1;
1093 }
Nick Coghland6009512014-11-20 21:39:37 +10001094
1095 /* Collect final garbage. This disposes of cycles created by
1096 * class definitions, for example.
1097 * XXX This is disabled because it caused too many problems. If
1098 * XXX a __del__ or weakref callback triggers here, Python code has
1099 * XXX a hard time running, because even the sys module has been
1100 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1101 * XXX One symptom is a sequence of information-free messages
1102 * XXX coming from threads (if a __del__ or callback is invoked,
1103 * XXX other threads can execute too, and any exception they encounter
1104 * XXX triggers a comedy of errors as subsystem after subsystem
1105 * XXX fails to find what it *expects* to find in sys to help report
1106 * XXX the exception and consequent unexpected failures). I've also
1107 * XXX seen segfaults then, after adding print statements to the
1108 * XXX Python code getting called.
1109 */
1110#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001111 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001112#endif
1113
1114 /* Disable tracemalloc after all Python objects have been destroyed,
1115 so it is possible to use tracemalloc in objects destructor. */
1116 _PyTraceMalloc_Fini();
1117
1118 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1119 _PyImport_Fini();
1120
1121 /* Cleanup typeobject.c's internal caches. */
1122 _PyType_Fini();
1123
1124 /* unload faulthandler module */
1125 _PyFaulthandler_Fini();
1126
1127 /* Debugging stuff */
1128#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001129 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001130#endif
1131 /* dump hash stats */
1132 _PyHash_Fini();
1133
Eric Snowdae02762017-09-14 00:35:58 -07001134#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001135 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001136 _PyDebug_PrintTotalRefs();
1137 }
Eric Snowdae02762017-09-14 00:35:58 -07001138#endif
Nick Coghland6009512014-11-20 21:39:37 +10001139
1140#ifdef Py_TRACE_REFS
1141 /* Display all objects still alive -- this can invoke arbitrary
1142 * __repr__ overrides, so requires a mostly-intact interpreter.
1143 * Alas, a lot of stuff may still be alive now that will be cleaned
1144 * up later.
1145 */
Victor Stinnerda273412017-12-15 01:46:02 +01001146 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001147 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001148 }
Nick Coghland6009512014-11-20 21:39:37 +10001149#endif /* Py_TRACE_REFS */
1150
1151 /* Clear interpreter state and all thread states. */
1152 PyInterpreterState_Clear(interp);
1153
1154 /* Now we decref the exception classes. After this point nothing
1155 can raise an exception. That's okay, because each Fini() method
1156 below has been checked to make sure no exceptions are ever
1157 raised.
1158 */
1159
1160 _PyExc_Fini();
1161
1162 /* Sundry finalizers */
1163 PyMethod_Fini();
1164 PyFrame_Fini();
1165 PyCFunction_Fini();
1166 PyTuple_Fini();
1167 PyList_Fini();
1168 PySet_Fini();
1169 PyBytes_Fini();
1170 PyByteArray_Fini();
1171 PyLong_Fini();
1172 PyFloat_Fini();
1173 PyDict_Fini();
1174 PySlice_Fini();
1175 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001176 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001177 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001178 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001179
1180 /* Cleanup Unicode implementation */
1181 _PyUnicode_Fini();
1182
1183 /* reset file system default encoding */
1184 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1185 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1186 Py_FileSystemDefaultEncoding = NULL;
1187 }
1188
1189 /* XXX Still allocated:
1190 - various static ad-hoc pointers to interned strings
1191 - int and float free list blocks
1192 - whatever various modules and libraries allocate
1193 */
1194
1195 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1196
1197 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001198 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001199
1200 /* Delete current thread. After this, many C API calls become crashy. */
1201 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001202
Nick Coghland6009512014-11-20 21:39:37 +10001203 PyInterpreterState_Delete(interp);
1204
1205#ifdef Py_TRACE_REFS
1206 /* Display addresses (& refcnts) of all objects still alive.
1207 * An address can be used to find the repr of the object, printed
1208 * above by _Py_PrintReferences.
1209 */
Victor Stinnerda273412017-12-15 01:46:02 +01001210 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001211 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001212 }
Nick Coghland6009512014-11-20 21:39:37 +10001213#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001214#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001215 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001216 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be807c2016-03-14 12:04:26 +01001217 }
Nick Coghland6009512014-11-20 21:39:37 +10001218#endif
1219
1220 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001221
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001222 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001223 return status;
1224}
1225
1226void
1227Py_Finalize(void)
1228{
1229 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001230}
1231
1232/* Create and initialize a new interpreter and thread, and return the
1233 new thread. This requires that Py_Initialize() has been called
1234 first.
1235
1236 Unsuccessful initialization yields a NULL pointer. Note that *no*
1237 exception information is available even in this case -- the
1238 exception information is held in the thread, and there is no
1239 thread.
1240
1241 Locking: as above.
1242
1243*/
1244
Victor Stinnera7368ac2017-11-15 18:11:45 -08001245static _PyInitError
1246new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001247{
1248 PyInterpreterState *interp;
1249 PyThreadState *tstate, *save_tstate;
1250 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001251 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001252
Victor Stinnera7368ac2017-11-15 18:11:45 -08001253 if (!_PyRuntime.initialized) {
1254 return _Py_INIT_ERR("Py_Initialize must be called first");
1255 }
Nick Coghland6009512014-11-20 21:39:37 +10001256
Victor Stinner8a1be612016-03-14 22:07:55 +01001257 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1258 interpreters: disable PyGILState_Check(). */
1259 _PyGILState_check_enabled = 0;
1260
Nick Coghland6009512014-11-20 21:39:37 +10001261 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001262 if (interp == NULL) {
1263 *tstate_p = NULL;
1264 return _Py_INIT_OK();
1265 }
Nick Coghland6009512014-11-20 21:39:37 +10001266
1267 tstate = PyThreadState_New(interp);
1268 if (tstate == NULL) {
1269 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001270 *tstate_p = NULL;
1271 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001272 }
1273
1274 save_tstate = PyThreadState_Swap(tstate);
1275
Eric Snow1abcf672017-05-23 21:46:51 -07001276 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001277 _PyCoreConfig *core_config;
1278 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001279 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001280 core_config = &save_tstate->interp->core_config;
1281 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001282 } else {
1283 /* No current thread state, copy from the main interpreter */
1284 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001285 core_config = &main_interp->core_config;
1286 config = &main_interp->config;
1287 }
1288
1289 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1290 return _Py_INIT_ERR("failed to copy core config");
1291 }
1292 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1293 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001294 }
1295
Nick Coghland6009512014-11-20 21:39:37 +10001296 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001297 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001298 if (modules == NULL) {
1299 return _Py_INIT_ERR("can't make modules dictionary");
1300 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001301 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001302
Eric Snowd393c1b2017-09-14 12:18:12 -06001303 sysmod = _PyImport_FindBuiltin("sys", modules);
1304 if (sysmod != NULL) {
1305 interp->sysdict = PyModule_GetDict(sysmod);
1306 if (interp->sysdict == NULL)
1307 goto handle_error;
1308 Py_INCREF(interp->sysdict);
1309 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001310 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001311 }
1312
1313 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001314 if (bimod != NULL) {
1315 interp->builtins = PyModule_GetDict(bimod);
1316 if (interp->builtins == NULL)
1317 goto handle_error;
1318 Py_INCREF(interp->builtins);
1319 }
1320
1321 /* initialize builtin exceptions */
1322 _PyExc_Init(bimod);
1323
Nick Coghland6009512014-11-20 21:39:37 +10001324 if (bimod != NULL && sysmod != NULL) {
1325 PyObject *pstderr;
1326
Nick Coghland6009512014-11-20 21:39:37 +10001327 /* Set up a preliminary stderr printer until we have enough
1328 infrastructure for the io module in place. */
1329 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001330 if (pstderr == NULL) {
1331 return _Py_INIT_ERR("can't set preliminary stderr");
1332 }
Nick Coghland6009512014-11-20 21:39:37 +10001333 _PySys_SetObjectId(&PyId_stderr, pstderr);
1334 PySys_SetObject("__stderr__", pstderr);
1335 Py_DECREF(pstderr);
1336
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001337 err = _PyImportHooks_Init();
1338 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001339 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001340 }
Nick Coghland6009512014-11-20 21:39:37 +10001341
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001342 err = initimport(interp, sysmod);
1343 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001344 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001345 }
Nick Coghland6009512014-11-20 21:39:37 +10001346
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001347 err = initexternalimport(interp);
1348 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001349 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001350 }
Nick Coghland6009512014-11-20 21:39:37 +10001351
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001352 err = initfsencoding(interp);
1353 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001354 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001355 }
1356
Victor Stinner91106cd2017-12-13 12:29:09 +01001357 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 if (_Py_INIT_FAILED(err)) {
1359 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001360 }
1361
1362 err = add_main_module(interp);
1363 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001364 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365 }
1366
1367 if (!Py_NoSiteFlag) {
1368 err = initsite();
1369 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001371 }
1372 }
Nick Coghland6009512014-11-20 21:39:37 +10001373 }
1374
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 if (PyErr_Occurred()) {
1376 goto handle_error;
1377 }
Nick Coghland6009512014-11-20 21:39:37 +10001378
Victor Stinnera7368ac2017-11-15 18:11:45 -08001379 *tstate_p = tstate;
1380 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001381
Nick Coghland6009512014-11-20 21:39:37 +10001382handle_error:
1383 /* Oops, it didn't work. Undo it all. */
1384
1385 PyErr_PrintEx(0);
1386 PyThreadState_Clear(tstate);
1387 PyThreadState_Swap(save_tstate);
1388 PyThreadState_Delete(tstate);
1389 PyInterpreterState_Delete(interp);
1390
Victor Stinnera7368ac2017-11-15 18:11:45 -08001391 *tstate_p = NULL;
1392 return _Py_INIT_OK();
1393}
1394
1395PyThreadState *
1396Py_NewInterpreter(void)
1397{
1398 PyThreadState *tstate;
1399 _PyInitError err = new_interpreter(&tstate);
1400 if (_Py_INIT_FAILED(err)) {
1401 _Py_FatalInitError(err);
1402 }
1403 return tstate;
1404
Nick Coghland6009512014-11-20 21:39:37 +10001405}
1406
1407/* Delete an interpreter and its last thread. This requires that the
1408 given thread state is current, that the thread has no remaining
1409 frames, and that it is its interpreter's only remaining thread.
1410 It is a fatal error to violate these constraints.
1411
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001412 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001413 everything, regardless.)
1414
1415 Locking: as above.
1416
1417*/
1418
1419void
1420Py_EndInterpreter(PyThreadState *tstate)
1421{
1422 PyInterpreterState *interp = tstate->interp;
1423
1424 if (tstate != PyThreadState_GET())
1425 Py_FatalError("Py_EndInterpreter: thread is not current");
1426 if (tstate->frame != NULL)
1427 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1428
1429 wait_for_thread_shutdown();
1430
1431 if (tstate != interp->tstate_head || tstate->next != NULL)
1432 Py_FatalError("Py_EndInterpreter: not the last thread");
1433
1434 PyImport_Cleanup();
1435 PyInterpreterState_Clear(interp);
1436 PyThreadState_Swap(NULL);
1437 PyInterpreterState_Delete(interp);
1438}
1439
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001441
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442static _PyInitError
1443add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001444{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001445 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001446 m = PyImport_AddModule("__main__");
1447 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001448 return _Py_INIT_ERR("can't create __main__ module");
1449
Nick Coghland6009512014-11-20 21:39:37 +10001450 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001451 ann_dict = PyDict_New();
1452 if ((ann_dict == NULL) ||
1453 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001454 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001455 }
1456 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001457
Nick Coghland6009512014-11-20 21:39:37 +10001458 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1459 PyObject *bimod = PyImport_ImportModule("builtins");
1460 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001461 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001462 }
1463 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001464 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001465 }
1466 Py_DECREF(bimod);
1467 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001468
Nick Coghland6009512014-11-20 21:39:37 +10001469 /* Main is a little special - imp.is_builtin("__main__") will return
1470 * False, but BuiltinImporter is still the most appropriate initial
1471 * setting for its __loader__ attribute. A more suitable value will
1472 * be set if __main__ gets further initialized later in the startup
1473 * process.
1474 */
1475 loader = PyDict_GetItemString(d, "__loader__");
1476 if (loader == NULL || loader == Py_None) {
1477 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1478 "BuiltinImporter");
1479 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001480 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001481 }
1482 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001483 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001484 }
1485 Py_DECREF(loader);
1486 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001487 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001488}
1489
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001490static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001491initfsencoding(PyInterpreterState *interp)
1492{
1493 PyObject *codec;
1494
Steve Dowercc16be82016-09-08 10:35:16 -07001495#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001496 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001497 Py_FileSystemDefaultEncoding = "mbcs";
1498 Py_FileSystemDefaultEncodeErrors = "replace";
1499 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001500 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001501 Py_FileSystemDefaultEncoding = "utf-8";
1502 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1503 }
1504#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001505 if (Py_FileSystemDefaultEncoding == NULL &&
1506 interp->core_config.utf8_mode)
1507 {
1508 Py_FileSystemDefaultEncoding = "utf-8";
1509 Py_HasFileSystemDefaultEncoding = 1;
1510 }
1511 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001512 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001513 if (Py_FileSystemDefaultEncoding == NULL) {
1514 return _Py_INIT_ERR("Unable to get the locale encoding");
1515 }
Nick Coghland6009512014-11-20 21:39:37 +10001516
1517 Py_HasFileSystemDefaultEncoding = 0;
1518 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001519 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001520 }
Steve Dowercc16be82016-09-08 10:35:16 -07001521#endif
Nick Coghland6009512014-11-20 21:39:37 +10001522
1523 /* the encoding is mbcs, utf-8 or ascii */
1524 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1525 if (!codec) {
1526 /* Such error can only occurs in critical situations: no more
1527 * memory, import a module of the standard library failed,
1528 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001529 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001530 }
1531 Py_DECREF(codec);
1532 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001533 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001534}
1535
1536/* Import the site module (not into __main__ though) */
1537
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001538static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001539initsite(void)
1540{
1541 PyObject *m;
1542 m = PyImport_ImportModule("site");
1543 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001544 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001545 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001546 Py_DECREF(m);
1547 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001548}
1549
Victor Stinner874dbe82015-09-04 17:29:57 +02001550/* Check if a file descriptor is valid or not.
1551 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1552static int
1553is_valid_fd(int fd)
1554{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001555#ifdef __APPLE__
1556 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1557 and the other side of the pipe is closed, dup(1) succeed, whereas
1558 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1559 such error. */
1560 struct stat st;
1561 return (fstat(fd, &st) == 0);
1562#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001563 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001564 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001565 return 0;
1566 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001567 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1568 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1569 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001570 fd2 = dup(fd);
1571 if (fd2 >= 0)
1572 close(fd2);
1573 _Py_END_SUPPRESS_IPH
1574 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001575#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001576}
1577
1578/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001579static PyObject*
1580create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001581 int fd, int write_mode, const char* name,
1582 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001583{
1584 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1585 const char* mode;
1586 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001587 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001588 int buffering, isatty;
1589 _Py_IDENTIFIER(open);
1590 _Py_IDENTIFIER(isatty);
1591 _Py_IDENTIFIER(TextIOWrapper);
1592 _Py_IDENTIFIER(mode);
1593
Victor Stinner874dbe82015-09-04 17:29:57 +02001594 if (!is_valid_fd(fd))
1595 Py_RETURN_NONE;
1596
Nick Coghland6009512014-11-20 21:39:37 +10001597 /* stdin is always opened in buffered mode, first because it shouldn't
1598 make a difference in common use cases, second because TextIOWrapper
1599 depends on the presence of a read1() method which only exists on
1600 buffered streams.
1601 */
1602 if (Py_UnbufferedStdioFlag && write_mode)
1603 buffering = 0;
1604 else
1605 buffering = -1;
1606 if (write_mode)
1607 mode = "wb";
1608 else
1609 mode = "rb";
1610 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1611 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001612 Py_None, Py_None, /* encoding, errors */
1613 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001614 if (buf == NULL)
1615 goto error;
1616
1617 if (buffering) {
1618 _Py_IDENTIFIER(raw);
1619 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1620 if (raw == NULL)
1621 goto error;
1622 }
1623 else {
1624 raw = buf;
1625 Py_INCREF(raw);
1626 }
1627
Steve Dower39294992016-08-30 21:22:36 -07001628#ifdef MS_WINDOWS
1629 /* Windows console IO is always UTF-8 encoded */
1630 if (PyWindowsConsoleIO_Check(raw))
1631 encoding = "utf-8";
1632#endif
1633
Nick Coghland6009512014-11-20 21:39:37 +10001634 text = PyUnicode_FromString(name);
1635 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1636 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001637 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001638 if (res == NULL)
1639 goto error;
1640 isatty = PyObject_IsTrue(res);
1641 Py_DECREF(res);
1642 if (isatty == -1)
1643 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001644 if (Py_UnbufferedStdioFlag)
1645 write_through = Py_True;
1646 else
1647 write_through = Py_False;
1648 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001649 line_buffering = Py_True;
1650 else
1651 line_buffering = Py_False;
1652
1653 Py_CLEAR(raw);
1654 Py_CLEAR(text);
1655
1656#ifdef MS_WINDOWS
1657 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1658 newlines to "\n".
1659 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1660 newline = NULL;
1661#else
1662 /* sys.stdin: split lines at "\n".
1663 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1664 newline = "\n";
1665#endif
1666
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001667 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001668 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001669 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001670 Py_CLEAR(buf);
1671 if (stream == NULL)
1672 goto error;
1673
1674 if (write_mode)
1675 mode = "w";
1676 else
1677 mode = "r";
1678 text = PyUnicode_FromString(mode);
1679 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1680 goto error;
1681 Py_CLEAR(text);
1682 return stream;
1683
1684error:
1685 Py_XDECREF(buf);
1686 Py_XDECREF(stream);
1687 Py_XDECREF(text);
1688 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001689
Victor Stinner874dbe82015-09-04 17:29:57 +02001690 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1691 /* Issue #24891: the file descriptor was closed after the first
1692 is_valid_fd() check was called. Ignore the OSError and set the
1693 stream to None. */
1694 PyErr_Clear();
1695 Py_RETURN_NONE;
1696 }
1697 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001698}
1699
1700/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001701static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001702init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001703{
1704 PyObject *iomod = NULL, *wrapper;
1705 PyObject *bimod = NULL;
1706 PyObject *m;
1707 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001708 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001709 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001710 char *pythonioencoding = NULL;
1711 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001712 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001713
1714 /* Hack to avoid a nasty recursion issue when Python is invoked
1715 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1716 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1717 goto error;
1718 }
1719 Py_DECREF(m);
1720
1721 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1722 goto error;
1723 }
1724 Py_DECREF(m);
1725
1726 if (!(bimod = PyImport_ImportModule("builtins"))) {
1727 goto error;
1728 }
1729
1730 if (!(iomod = PyImport_ImportModule("io"))) {
1731 goto error;
1732 }
1733 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1734 goto error;
1735 }
1736
1737 /* Set builtins.open */
1738 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1739 Py_DECREF(wrapper);
1740 goto error;
1741 }
1742 Py_DECREF(wrapper);
1743
1744 encoding = _Py_StandardStreamEncoding;
1745 errors = _Py_StandardStreamErrors;
1746 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001747 char *opt = Py_GETENV("PYTHONIOENCODING");
1748 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001749 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001750 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001751 if (pythonioencoding == NULL) {
1752 PyErr_NoMemory();
1753 goto error;
1754 }
1755 err = strchr(pythonioencoding, ':');
1756 if (err) {
1757 *err = '\0';
1758 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001759 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001760 errors = err;
1761 }
1762 }
1763 if (*pythonioencoding && !encoding) {
1764 encoding = pythonioencoding;
1765 }
1766 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001767 else if (interp->core_config.utf8_mode) {
1768 encoding = "utf-8";
1769 errors = "surrogateescape";
1770 }
1771
1772 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001773 /* Choose the default error handler based on the current locale */
1774 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001775 }
Nick Coghland6009512014-11-20 21:39:37 +10001776 }
1777
1778 /* Set sys.stdin */
1779 fd = fileno(stdin);
1780 /* Under some conditions stdin, stdout and stderr may not be connected
1781 * and fileno() may point to an invalid file descriptor. For example
1782 * GUI apps don't have valid standard streams by default.
1783 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001784 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1785 if (std == NULL)
1786 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001787 PySys_SetObject("__stdin__", std);
1788 _PySys_SetObjectId(&PyId_stdin, std);
1789 Py_DECREF(std);
1790
1791 /* Set sys.stdout */
1792 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001793 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1794 if (std == NULL)
1795 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001796 PySys_SetObject("__stdout__", std);
1797 _PySys_SetObjectId(&PyId_stdout, std);
1798 Py_DECREF(std);
1799
1800#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1801 /* Set sys.stderr, replaces the preliminary stderr */
1802 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001803 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1804 if (std == NULL)
1805 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001806
1807 /* Same as hack above, pre-import stderr's codec to avoid recursion
1808 when import.c tries to write to stderr in verbose mode. */
1809 encoding_attr = PyObject_GetAttrString(std, "encoding");
1810 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001811 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001812 if (std_encoding != NULL) {
1813 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1814 Py_XDECREF(codec_info);
1815 }
1816 Py_DECREF(encoding_attr);
1817 }
1818 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1819
1820 if (PySys_SetObject("__stderr__", std) < 0) {
1821 Py_DECREF(std);
1822 goto error;
1823 }
1824 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1825 Py_DECREF(std);
1826 goto error;
1827 }
1828 Py_DECREF(std);
1829#endif
1830
Victor Stinnera7368ac2017-11-15 18:11:45 -08001831 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001832
Victor Stinnera7368ac2017-11-15 18:11:45 -08001833error:
1834 res = _Py_INIT_ERR("can't initialize sys standard streams");
1835
1836done:
Nick Coghland6009512014-11-20 21:39:37 +10001837 /* We won't need them anymore. */
1838 if (_Py_StandardStreamEncoding) {
1839 PyMem_RawFree(_Py_StandardStreamEncoding);
1840 _Py_StandardStreamEncoding = NULL;
1841 }
1842 if (_Py_StandardStreamErrors) {
1843 PyMem_RawFree(_Py_StandardStreamErrors);
1844 _Py_StandardStreamErrors = NULL;
1845 }
1846 PyMem_Free(pythonioencoding);
1847 Py_XDECREF(bimod);
1848 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001849 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001850}
1851
1852
Victor Stinner10dc4842015-03-24 12:01:30 +01001853static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001854_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001855{
Victor Stinner10dc4842015-03-24 12:01:30 +01001856 fputc('\n', stderr);
1857 fflush(stderr);
1858
1859 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001860 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001861}
Victor Stinner791da1c2016-03-14 16:53:12 +01001862
1863/* Print the current exception (if an exception is set) with its traceback,
1864 or display the current Python stack.
1865
1866 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1867 called on catastrophic cases.
1868
1869 Return 1 if the traceback was displayed, 0 otherwise. */
1870
1871static int
1872_Py_FatalError_PrintExc(int fd)
1873{
1874 PyObject *ferr, *res;
1875 PyObject *exception, *v, *tb;
1876 int has_tb;
1877
1878 if (PyThreadState_GET() == NULL) {
1879 /* The GIL is released: trying to acquire it is likely to deadlock,
1880 just give up. */
1881 return 0;
1882 }
1883
1884 PyErr_Fetch(&exception, &v, &tb);
1885 if (exception == NULL) {
1886 /* No current exception */
1887 return 0;
1888 }
1889
1890 ferr = _PySys_GetObjectId(&PyId_stderr);
1891 if (ferr == NULL || ferr == Py_None) {
1892 /* sys.stderr is not set yet or set to None,
1893 no need to try to display the exception */
1894 return 0;
1895 }
1896
1897 PyErr_NormalizeException(&exception, &v, &tb);
1898 if (tb == NULL) {
1899 tb = Py_None;
1900 Py_INCREF(tb);
1901 }
1902 PyException_SetTraceback(v, tb);
1903 if (exception == NULL) {
1904 /* PyErr_NormalizeException() failed */
1905 return 0;
1906 }
1907
1908 has_tb = (tb != Py_None);
1909 PyErr_Display(exception, v, tb);
1910 Py_XDECREF(exception);
1911 Py_XDECREF(v);
1912 Py_XDECREF(tb);
1913
1914 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001915 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001916 if (res == NULL)
1917 PyErr_Clear();
1918 else
1919 Py_DECREF(res);
1920
1921 return has_tb;
1922}
1923
Nick Coghland6009512014-11-20 21:39:37 +10001924/* Print fatal error message and abort */
1925
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001926#ifdef MS_WINDOWS
1927static void
1928fatal_output_debug(const char *msg)
1929{
1930 /* buffer of 256 bytes allocated on the stack */
1931 WCHAR buffer[256 / sizeof(WCHAR)];
1932 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1933 size_t msglen;
1934
1935 OutputDebugStringW(L"Fatal Python error: ");
1936
1937 msglen = strlen(msg);
1938 while (msglen) {
1939 size_t i;
1940
1941 if (buflen > msglen) {
1942 buflen = msglen;
1943 }
1944
1945 /* Convert the message to wchar_t. This uses a simple one-to-one
1946 conversion, assuming that the this error message actually uses
1947 ASCII only. If this ceases to be true, we will have to convert. */
1948 for (i=0; i < buflen; ++i) {
1949 buffer[i] = msg[i];
1950 }
1951 buffer[i] = L'\0';
1952 OutputDebugStringW(buffer);
1953
1954 msg += buflen;
1955 msglen -= buflen;
1956 }
1957 OutputDebugStringW(L"\n");
1958}
1959#endif
1960
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001961static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001962fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001963{
1964 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001965 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001966
1967 if (reentrant) {
1968 /* Py_FatalError() caused a second fatal error.
1969 Example: flush_std_files() raises a recursion error. */
1970 goto exit;
1971 }
1972 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001973
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001974 fprintf(stderr, "Fatal Python error: ");
1975 if (prefix) {
1976 fputs(prefix, stderr);
1977 fputs(": ", stderr);
1978 }
1979 if (msg) {
1980 fputs(msg, stderr);
1981 }
1982 else {
1983 fprintf(stderr, "<message not set>");
1984 }
1985 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001986 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001987
Victor Stinnere0deff32015-03-24 13:46:18 +01001988 /* Print the exception (if an exception is set) with its traceback,
1989 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001990 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001991 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001992 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001993
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001994 /* The main purpose of faulthandler is to display the traceback.
1995 This function already did its best to display a traceback.
1996 Disable faulthandler to prevent writing a second traceback
1997 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001998 _PyFaulthandler_Fini();
1999
Victor Stinner791da1c2016-03-14 16:53:12 +01002000 /* Check if the current Python thread hold the GIL */
2001 if (PyThreadState_GET() != NULL) {
2002 /* Flush sys.stdout and sys.stderr */
2003 flush_std_files();
2004 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002005
Nick Coghland6009512014-11-20 21:39:37 +10002006#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002007 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002008#endif /* MS_WINDOWS */
2009
2010exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002011 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002012#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002013 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002014#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002015 abort();
2016 }
2017 else {
2018 exit(status);
2019 }
2020}
2021
2022void
2023Py_FatalError(const char *msg)
2024{
2025 fatal_error(NULL, msg, -1);
2026}
2027
2028void
2029_Py_FatalInitError(_PyInitError err)
2030{
2031 /* On "user" error: exit with status 1.
2032 For all other errors, call abort(). */
2033 int status = err.user_err ? 1 : -1;
2034 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002035}
2036
2037/* Clean up and exit */
2038
Victor Stinnerd7292b52016-06-17 12:29:00 +02002039# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002040
Nick Coghland6009512014-11-20 21:39:37 +10002041/* For the atexit module. */
2042void _Py_PyAtExit(void (*func)(void))
2043{
Antoine Pitroufc5db952017-12-13 02:29:07 +01002044 /* Guard against API misuse (see bpo-17852) */
2045 assert(_PyRuntime.pyexitfunc == NULL || _PyRuntime.pyexitfunc == func);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002046 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002047}
2048
2049static void
2050call_py_exitfuncs(void)
2051{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002052 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002053 return;
2054
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002055 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002056 PyErr_Clear();
2057}
2058
2059/* Wait until threading._shutdown completes, provided
2060 the threading module was imported in the first place.
2061 The shutdown routine will wait until all non-daemon
2062 "threading" threads have completed. */
2063static void
2064wait_for_thread_shutdown(void)
2065{
Nick Coghland6009512014-11-20 21:39:37 +10002066 _Py_IDENTIFIER(_shutdown);
2067 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002068 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002069 if (threading == NULL) {
2070 /* threading not imported */
2071 PyErr_Clear();
2072 return;
2073 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002074 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002075 if (result == NULL) {
2076 PyErr_WriteUnraisable(threading);
2077 }
2078 else {
2079 Py_DECREF(result);
2080 }
2081 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002082}
2083
2084#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002085int Py_AtExit(void (*func)(void))
2086{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002087 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002088 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002089 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002090 return 0;
2091}
2092
2093static void
2094call_ll_exitfuncs(void)
2095{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002096 while (_PyRuntime.nexitfuncs > 0)
2097 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002098
2099 fflush(stdout);
2100 fflush(stderr);
2101}
2102
2103void
2104Py_Exit(int sts)
2105{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002106 if (Py_FinalizeEx() < 0) {
2107 sts = 120;
2108 }
Nick Coghland6009512014-11-20 21:39:37 +10002109
2110 exit(sts);
2111}
2112
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002113static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002114initsigs(void)
2115{
2116#ifdef SIGPIPE
2117 PyOS_setsig(SIGPIPE, SIG_IGN);
2118#endif
2119#ifdef SIGXFZ
2120 PyOS_setsig(SIGXFZ, SIG_IGN);
2121#endif
2122#ifdef SIGXFSZ
2123 PyOS_setsig(SIGXFSZ, SIG_IGN);
2124#endif
2125 PyOS_InitInterrupts(); /* May imply initsignal() */
2126 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002127 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002128 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002129 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002130}
2131
2132
2133/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2134 *
2135 * All of the code in this function must only use async-signal-safe functions,
2136 * listed at `man 7 signal` or
2137 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2138 */
2139void
2140_Py_RestoreSignals(void)
2141{
2142#ifdef SIGPIPE
2143 PyOS_setsig(SIGPIPE, SIG_DFL);
2144#endif
2145#ifdef SIGXFZ
2146 PyOS_setsig(SIGXFZ, SIG_DFL);
2147#endif
2148#ifdef SIGXFSZ
2149 PyOS_setsig(SIGXFSZ, SIG_DFL);
2150#endif
2151}
2152
2153
2154/*
2155 * The file descriptor fd is considered ``interactive'' if either
2156 * a) isatty(fd) is TRUE, or
2157 * b) the -i flag was given, and the filename associated with
2158 * the descriptor is NULL or "<stdin>" or "???".
2159 */
2160int
2161Py_FdIsInteractive(FILE *fp, const char *filename)
2162{
2163 if (isatty((int)fileno(fp)))
2164 return 1;
2165 if (!Py_InteractiveFlag)
2166 return 0;
2167 return (filename == NULL) ||
2168 (strcmp(filename, "<stdin>") == 0) ||
2169 (strcmp(filename, "???") == 0);
2170}
2171
2172
Nick Coghland6009512014-11-20 21:39:37 +10002173/* Wrappers around sigaction() or signal(). */
2174
2175PyOS_sighandler_t
2176PyOS_getsig(int sig)
2177{
2178#ifdef HAVE_SIGACTION
2179 struct sigaction context;
2180 if (sigaction(sig, NULL, &context) == -1)
2181 return SIG_ERR;
2182 return context.sa_handler;
2183#else
2184 PyOS_sighandler_t handler;
2185/* Special signal handling for the secure CRT in Visual Studio 2005 */
2186#if defined(_MSC_VER) && _MSC_VER >= 1400
2187 switch (sig) {
2188 /* Only these signals are valid */
2189 case SIGINT:
2190 case SIGILL:
2191 case SIGFPE:
2192 case SIGSEGV:
2193 case SIGTERM:
2194 case SIGBREAK:
2195 case SIGABRT:
2196 break;
2197 /* Don't call signal() with other values or it will assert */
2198 default:
2199 return SIG_ERR;
2200 }
2201#endif /* _MSC_VER && _MSC_VER >= 1400 */
2202 handler = signal(sig, SIG_IGN);
2203 if (handler != SIG_ERR)
2204 signal(sig, handler);
2205 return handler;
2206#endif
2207}
2208
2209/*
2210 * All of the code in this function must only use async-signal-safe functions,
2211 * listed at `man 7 signal` or
2212 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2213 */
2214PyOS_sighandler_t
2215PyOS_setsig(int sig, PyOS_sighandler_t handler)
2216{
2217#ifdef HAVE_SIGACTION
2218 /* Some code in Modules/signalmodule.c depends on sigaction() being
2219 * used here if HAVE_SIGACTION is defined. Fix that if this code
2220 * changes to invalidate that assumption.
2221 */
2222 struct sigaction context, ocontext;
2223 context.sa_handler = handler;
2224 sigemptyset(&context.sa_mask);
2225 context.sa_flags = 0;
2226 if (sigaction(sig, &context, &ocontext) == -1)
2227 return SIG_ERR;
2228 return ocontext.sa_handler;
2229#else
2230 PyOS_sighandler_t oldhandler;
2231 oldhandler = signal(sig, handler);
2232#ifdef HAVE_SIGINTERRUPT
2233 siginterrupt(sig, 1);
2234#endif
2235 return oldhandler;
2236#endif
2237}
2238
2239#ifdef __cplusplus
2240}
2241#endif