blob: 830f89d0d41b7e41b3d853f9b84f477f328bf353 [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 Stinner374c6e12017-12-14 12:05:26 +0100833 /* Set sys attributes */
Victor Stinnerb5fd9ad2017-12-14 02:20:52 +0100834 assert(interp->config.module_search_path != NULL);
835 if (PySys_SetObject("path", interp->config.module_search_path) != 0) {
836 return _Py_INIT_ERR("can't assign sys.path");
Victor Stinner9316ee42017-11-25 03:17:57 +0100837 }
Victor Stinner374c6e12017-12-14 12:05:26 +0100838 if (interp->config.argv != NULL) {
839 if (PySys_SetObject("argv", interp->config.argv) != 0) {
840 return _Py_INIT_ERR("can't assign sys.argv");
841 }
842 }
843 if (interp->config.warnoptions != NULL) {
844 if (PySys_SetObject("warnoptions", interp->config.warnoptions)) {
845 return _Py_INIT_ERR("can't assign sys.warnoptions");
846 }
847 }
848 if (interp->config.xoptions != NULL) {
849 if (PySys_SetObject("_xoptions", interp->config.xoptions)) {
850 return _Py_INIT_ERR("can't assign sys._xoptions");
851 }
852 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100853
Victor Stinnerda273412017-12-15 01:46:02 +0100854 if (_PySys_EndInit(interp->sysdict) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800855 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100856 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800857
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800858 err = initexternalimport(interp);
859 if (_Py_INIT_FAILED(err)) {
860 return err;
861 }
Nick Coghland6009512014-11-20 21:39:37 +1000862
863 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800864 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 if (_Py_INIT_FAILED(err)) {
866 return err;
867 }
Nick Coghland6009512014-11-20 21:39:37 +1000868
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800869 err = initfsencoding(interp);
870 if (_Py_INIT_FAILED(err)) {
871 return err;
872 }
Nick Coghland6009512014-11-20 21:39:37 +1000873
Victor Stinner1f151112017-11-23 10:43:14 +0100874 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800875 err = initsigs(); /* Signal handling stuff, including initintr() */
876 if (_Py_INIT_FAILED(err)) {
877 return err;
878 }
879 }
Nick Coghland6009512014-11-20 21:39:37 +1000880
Victor Stinnera7368ac2017-11-15 18:11:45 -0800881 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800882 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000883
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800884 err = add_main_module(interp);
885 if (_Py_INIT_FAILED(err)) {
886 return err;
887 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800888
Victor Stinner91106cd2017-12-13 12:29:09 +0100889 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800890 if (_Py_INIT_FAILED(err)) {
891 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800892 }
Nick Coghland6009512014-11-20 21:39:37 +1000893
894 /* Initialize warnings. */
895 if (PySys_HasWarnOptions()) {
896 PyObject *warnings_module = PyImport_ImportModule("warnings");
897 if (warnings_module == NULL) {
898 fprintf(stderr, "'import warnings' failed; traceback:\n");
899 PyErr_Print();
900 }
901 Py_XDECREF(warnings_module);
902 }
903
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600904 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700905
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800906 if (!Py_NoSiteFlag) {
907 err = initsite(); /* Module site */
908 if (_Py_INIT_FAILED(err)) {
909 return err;
910 }
911 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800912 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000913}
914
Eric Snowc7ec9982017-05-23 23:00:52 -0700915#undef _INIT_DEBUG_PRINT
916
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700918_Py_InitializeEx_Private(int install_sigs, int install_importlib)
919{
920 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700921 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800922 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700923
Eric Snow1abcf672017-05-23 21:46:51 -0700924 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
925 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700926 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927
Victor Stinnerda273412017-12-15 01:46:02 +0100928 err = _PyCoreConfig_ReadEnv(&core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100930 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800931 }
932
Victor Stinnerda273412017-12-15 01:46:02 +0100933 err = _Py_InitializeCore(&core_config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100934 if (_Py_INIT_FAILED(err)) {
935 goto done;
936 }
937
Victor Stinnerb5fd9ad2017-12-14 02:20:52 +0100938 err = _PyMainInterpreterConfig_Read(&config, &core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100940 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800941 }
942
943 err = _Py_InitializeMainInterpreter(&config);
944 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100945 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800946 }
947
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100948 err = _Py_INIT_OK();
949
950done:
Victor Stinnerb5fd9ad2017-12-14 02:20:52 +0100951 _PyCoreConfig_Clear(&core_config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100952 _PyMainInterpreterConfig_Clear(&config);
953 return err;
Eric Snow1abcf672017-05-23 21:46:51 -0700954}
955
956
957void
Nick Coghland6009512014-11-20 21:39:37 +1000958Py_InitializeEx(int install_sigs)
959{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
961 if (_Py_INIT_FAILED(err)) {
962 _Py_FatalInitError(err);
963 }
Nick Coghland6009512014-11-20 21:39:37 +1000964}
965
966void
967Py_Initialize(void)
968{
969 Py_InitializeEx(1);
970}
971
972
973#ifdef COUNT_ALLOCS
974extern void dump_counts(FILE*);
975#endif
976
977/* Flush stdout and stderr */
978
979static int
980file_is_closed(PyObject *fobj)
981{
982 int r;
983 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
984 if (tmp == NULL) {
985 PyErr_Clear();
986 return 0;
987 }
988 r = PyObject_IsTrue(tmp);
989 Py_DECREF(tmp);
990 if (r < 0)
991 PyErr_Clear();
992 return r > 0;
993}
994
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000995static int
Nick Coghland6009512014-11-20 21:39:37 +1000996flush_std_files(void)
997{
998 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
999 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1000 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001001 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001002
1003 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001004 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001005 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001006 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001007 status = -1;
1008 }
Nick Coghland6009512014-11-20 21:39:37 +10001009 else
1010 Py_DECREF(tmp);
1011 }
1012
1013 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001014 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001015 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001016 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 status = -1;
1018 }
Nick Coghland6009512014-11-20 21:39:37 +10001019 else
1020 Py_DECREF(tmp);
1021 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001022
1023 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001024}
1025
1026/* Undo the effect of Py_Initialize().
1027
1028 Beware: if multiple interpreter and/or thread states exist, these
1029 are not wiped out; only the current thread and interpreter state
1030 are deleted. But since everything else is deleted, those other
1031 interpreter and thread states should no longer be used.
1032
1033 (XXX We should do better, e.g. wipe out all interpreters and
1034 threads.)
1035
1036 Locking: as above.
1037
1038*/
1039
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001040int
1041Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001042{
1043 PyInterpreterState *interp;
1044 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001045 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001046
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001047 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001048 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001049
1050 wait_for_thread_shutdown();
1051
1052 /* The interpreter is still entirely intact at this point, and the
1053 * exit funcs may be relying on that. In particular, if some thread
1054 * or exit func is still waiting to do an import, the import machinery
1055 * expects Py_IsInitialized() to return true. So don't say the
1056 * interpreter is uninitialized until after the exit funcs have run.
1057 * Note that Threading.py uses an exit func to do a join on all the
1058 * threads created thru it, so this also protects pending imports in
1059 * the threads created via Threading.
1060 */
1061 call_py_exitfuncs();
1062
1063 /* Get current thread state and interpreter pointer */
1064 tstate = PyThreadState_GET();
1065 interp = tstate->interp;
1066
Victor Stinnerda273412017-12-15 01:46:02 +01001067 /* Copy the core config, PyInterpreterState_Delete() free
1068 the core config memory */
1069 int show_ref_count = interp->core_config.show_ref_count;
1070 int dump_refs = interp->core_config.dump_refs;
1071 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner6bf992a2017-12-06 17:26:10 +01001072
Nick Coghland6009512014-11-20 21:39:37 +10001073 /* Remaining threads (e.g. daemon threads) will automatically exit
1074 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001075 _PyRuntime.finalizing = tstate;
1076 _PyRuntime.initialized = 0;
1077 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001078
Victor Stinnere0deff32015-03-24 13:46:18 +01001079 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001080 if (flush_std_files() < 0) {
1081 status = -1;
1082 }
Nick Coghland6009512014-11-20 21:39:37 +10001083
1084 /* Disable signal handling */
1085 PyOS_FiniInterrupts();
1086
1087 /* Collect garbage. This may call finalizers; it's nice to call these
1088 * before all modules are destroyed.
1089 * XXX If a __del__ or weakref callback is triggered here, and tries to
1090 * XXX import a module, bad things can happen, because Python no
1091 * XXX longer believes it's initialized.
1092 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1093 * XXX is easy to provoke that way. I've also seen, e.g.,
1094 * XXX Exception exceptions.ImportError: 'No module named sha'
1095 * XXX in <function callback at 0x008F5718> ignored
1096 * XXX but I'm unclear on exactly how that one happens. In any case,
1097 * XXX I haven't seen a real-life report of either of these.
1098 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001099 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001100#ifdef COUNT_ALLOCS
1101 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1102 each collection might release some types from the type
1103 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001104 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001105 /* nothing */;
1106#endif
Eric Snowdae02762017-09-14 00:35:58 -07001107
Nick Coghland6009512014-11-20 21:39:37 +10001108 /* Destroy all modules */
1109 PyImport_Cleanup();
1110
Victor Stinnere0deff32015-03-24 13:46:18 +01001111 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001112 if (flush_std_files() < 0) {
1113 status = -1;
1114 }
Nick Coghland6009512014-11-20 21:39:37 +10001115
1116 /* Collect final garbage. This disposes of cycles created by
1117 * class definitions, for example.
1118 * XXX This is disabled because it caused too many problems. If
1119 * XXX a __del__ or weakref callback triggers here, Python code has
1120 * XXX a hard time running, because even the sys module has been
1121 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1122 * XXX One symptom is a sequence of information-free messages
1123 * XXX coming from threads (if a __del__ or callback is invoked,
1124 * XXX other threads can execute too, and any exception they encounter
1125 * XXX triggers a comedy of errors as subsystem after subsystem
1126 * XXX fails to find what it *expects* to find in sys to help report
1127 * XXX the exception and consequent unexpected failures). I've also
1128 * XXX seen segfaults then, after adding print statements to the
1129 * XXX Python code getting called.
1130 */
1131#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001132 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001133#endif
1134
1135 /* Disable tracemalloc after all Python objects have been destroyed,
1136 so it is possible to use tracemalloc in objects destructor. */
1137 _PyTraceMalloc_Fini();
1138
1139 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1140 _PyImport_Fini();
1141
1142 /* Cleanup typeobject.c's internal caches. */
1143 _PyType_Fini();
1144
1145 /* unload faulthandler module */
1146 _PyFaulthandler_Fini();
1147
1148 /* Debugging stuff */
1149#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001150 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001151#endif
1152 /* dump hash stats */
1153 _PyHash_Fini();
1154
Eric Snowdae02762017-09-14 00:35:58 -07001155#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001156 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001157 _PyDebug_PrintTotalRefs();
1158 }
Eric Snowdae02762017-09-14 00:35:58 -07001159#endif
Nick Coghland6009512014-11-20 21:39:37 +10001160
1161#ifdef Py_TRACE_REFS
1162 /* Display all objects still alive -- this can invoke arbitrary
1163 * __repr__ overrides, so requires a mostly-intact interpreter.
1164 * Alas, a lot of stuff may still be alive now that will be cleaned
1165 * up later.
1166 */
Victor Stinnerda273412017-12-15 01:46:02 +01001167 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001168 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001169 }
Nick Coghland6009512014-11-20 21:39:37 +10001170#endif /* Py_TRACE_REFS */
1171
1172 /* Clear interpreter state and all thread states. */
1173 PyInterpreterState_Clear(interp);
1174
1175 /* Now we decref the exception classes. After this point nothing
1176 can raise an exception. That's okay, because each Fini() method
1177 below has been checked to make sure no exceptions are ever
1178 raised.
1179 */
1180
1181 _PyExc_Fini();
1182
1183 /* Sundry finalizers */
1184 PyMethod_Fini();
1185 PyFrame_Fini();
1186 PyCFunction_Fini();
1187 PyTuple_Fini();
1188 PyList_Fini();
1189 PySet_Fini();
1190 PyBytes_Fini();
1191 PyByteArray_Fini();
1192 PyLong_Fini();
1193 PyFloat_Fini();
1194 PyDict_Fini();
1195 PySlice_Fini();
1196 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001197 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001198 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001199 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001200
1201 /* Cleanup Unicode implementation */
1202 _PyUnicode_Fini();
1203
1204 /* reset file system default encoding */
1205 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1206 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1207 Py_FileSystemDefaultEncoding = NULL;
1208 }
1209
1210 /* XXX Still allocated:
1211 - various static ad-hoc pointers to interned strings
1212 - int and float free list blocks
1213 - whatever various modules and libraries allocate
1214 */
1215
1216 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1217
1218 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001219 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001220
1221 /* Delete current thread. After this, many C API calls become crashy. */
1222 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001223
Nick Coghland6009512014-11-20 21:39:37 +10001224 PyInterpreterState_Delete(interp);
1225
1226#ifdef Py_TRACE_REFS
1227 /* Display addresses (& refcnts) of all objects still alive.
1228 * An address can be used to find the repr of the object, printed
1229 * above by _Py_PrintReferences.
1230 */
Victor Stinnerda273412017-12-15 01:46:02 +01001231 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001232 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001233 }
Nick Coghland6009512014-11-20 21:39:37 +10001234#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001235#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001236 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001237 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001238 }
Nick Coghland6009512014-11-20 21:39:37 +10001239#endif
1240
1241 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001242
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001243 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001244 return status;
1245}
1246
1247void
1248Py_Finalize(void)
1249{
1250 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001251}
1252
1253/* Create and initialize a new interpreter and thread, and return the
1254 new thread. This requires that Py_Initialize() has been called
1255 first.
1256
1257 Unsuccessful initialization yields a NULL pointer. Note that *no*
1258 exception information is available even in this case -- the
1259 exception information is held in the thread, and there is no
1260 thread.
1261
1262 Locking: as above.
1263
1264*/
1265
Victor Stinnera7368ac2017-11-15 18:11:45 -08001266static _PyInitError
1267new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001268{
1269 PyInterpreterState *interp;
1270 PyThreadState *tstate, *save_tstate;
1271 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001272 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001273
Victor Stinnera7368ac2017-11-15 18:11:45 -08001274 if (!_PyRuntime.initialized) {
1275 return _Py_INIT_ERR("Py_Initialize must be called first");
1276 }
Nick Coghland6009512014-11-20 21:39:37 +10001277
Victor Stinner8a1be612016-03-14 22:07:55 +01001278 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1279 interpreters: disable PyGILState_Check(). */
1280 _PyGILState_check_enabled = 0;
1281
Nick Coghland6009512014-11-20 21:39:37 +10001282 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001283 if (interp == NULL) {
1284 *tstate_p = NULL;
1285 return _Py_INIT_OK();
1286 }
Nick Coghland6009512014-11-20 21:39:37 +10001287
1288 tstate = PyThreadState_New(interp);
1289 if (tstate == NULL) {
1290 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001291 *tstate_p = NULL;
1292 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001293 }
1294
1295 save_tstate = PyThreadState_Swap(tstate);
1296
Eric Snow1abcf672017-05-23 21:46:51 -07001297 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001298 _PyCoreConfig *core_config;
1299 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001300 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001301 core_config = &save_tstate->interp->core_config;
1302 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001303 } else {
1304 /* No current thread state, copy from the main interpreter */
1305 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001306 core_config = &main_interp->core_config;
1307 config = &main_interp->config;
1308 }
1309
1310 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1311 return _Py_INIT_ERR("failed to copy core config");
1312 }
1313 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1314 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001315 }
1316
Victor Stinnerb5fd9ad2017-12-14 02:20:52 +01001317 err = _PyPathConfig_Init(&interp->core_config);
Victor Stinner9316ee42017-11-25 03:17:57 +01001318 if (_Py_INIT_FAILED(err)) {
1319 return err;
1320 }
1321 wchar_t *sys_path = Py_GetPath();
1322
Nick Coghland6009512014-11-20 21:39:37 +10001323 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001324 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001325 if (modules == NULL) {
1326 return _Py_INIT_ERR("can't make modules dictionary");
1327 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001328 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001329
Eric Snowd393c1b2017-09-14 12:18:12 -06001330 sysmod = _PyImport_FindBuiltin("sys", modules);
1331 if (sysmod != NULL) {
1332 interp->sysdict = PyModule_GetDict(sysmod);
1333 if (interp->sysdict == NULL)
1334 goto handle_error;
1335 Py_INCREF(interp->sysdict);
1336 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerd4341102017-11-23 00:12:09 +01001337 PySys_SetPath(sys_path);
Eric Snowd393c1b2017-09-14 12:18:12 -06001338 _PySys_EndInit(interp->sysdict);
1339 }
1340
1341 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001342 if (bimod != NULL) {
1343 interp->builtins = PyModule_GetDict(bimod);
1344 if (interp->builtins == NULL)
1345 goto handle_error;
1346 Py_INCREF(interp->builtins);
1347 }
1348
1349 /* initialize builtin exceptions */
1350 _PyExc_Init(bimod);
1351
Nick Coghland6009512014-11-20 21:39:37 +10001352 if (bimod != NULL && sysmod != NULL) {
1353 PyObject *pstderr;
1354
Nick Coghland6009512014-11-20 21:39:37 +10001355 /* Set up a preliminary stderr printer until we have enough
1356 infrastructure for the io module in place. */
1357 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 if (pstderr == NULL) {
1359 return _Py_INIT_ERR("can't set preliminary stderr");
1360 }
Nick Coghland6009512014-11-20 21:39:37 +10001361 _PySys_SetObjectId(&PyId_stderr, pstderr);
1362 PySys_SetObject("__stderr__", pstderr);
1363 Py_DECREF(pstderr);
1364
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365 err = _PyImportHooks_Init();
1366 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001367 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001368 }
Nick Coghland6009512014-11-20 21:39:37 +10001369
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001370 err = initimport(interp, sysmod);
1371 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001372 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001373 }
Nick Coghland6009512014-11-20 21:39:37 +10001374
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001375 err = initexternalimport(interp);
1376 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001377 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001378 }
Nick Coghland6009512014-11-20 21:39:37 +10001379
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001380 err = initfsencoding(interp);
1381 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001382 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001383 }
1384
Victor Stinner91106cd2017-12-13 12:29:09 +01001385 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001386 if (_Py_INIT_FAILED(err)) {
1387 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001388 }
1389
1390 err = add_main_module(interp);
1391 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001392 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001393 }
1394
1395 if (!Py_NoSiteFlag) {
1396 err = initsite();
1397 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001398 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001399 }
1400 }
Nick Coghland6009512014-11-20 21:39:37 +10001401 }
1402
Victor Stinnera7368ac2017-11-15 18:11:45 -08001403 if (PyErr_Occurred()) {
1404 goto handle_error;
1405 }
Nick Coghland6009512014-11-20 21:39:37 +10001406
Victor Stinnera7368ac2017-11-15 18:11:45 -08001407 *tstate_p = tstate;
1408 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001409
Nick Coghland6009512014-11-20 21:39:37 +10001410handle_error:
1411 /* Oops, it didn't work. Undo it all. */
1412
1413 PyErr_PrintEx(0);
1414 PyThreadState_Clear(tstate);
1415 PyThreadState_Swap(save_tstate);
1416 PyThreadState_Delete(tstate);
1417 PyInterpreterState_Delete(interp);
1418
Victor Stinnera7368ac2017-11-15 18:11:45 -08001419 *tstate_p = NULL;
1420 return _Py_INIT_OK();
1421}
1422
1423PyThreadState *
1424Py_NewInterpreter(void)
1425{
1426 PyThreadState *tstate;
1427 _PyInitError err = new_interpreter(&tstate);
1428 if (_Py_INIT_FAILED(err)) {
1429 _Py_FatalInitError(err);
1430 }
1431 return tstate;
1432
Nick Coghland6009512014-11-20 21:39:37 +10001433}
1434
1435/* Delete an interpreter and its last thread. This requires that the
1436 given thread state is current, that the thread has no remaining
1437 frames, and that it is its interpreter's only remaining thread.
1438 It is a fatal error to violate these constraints.
1439
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001440 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001441 everything, regardless.)
1442
1443 Locking: as above.
1444
1445*/
1446
1447void
1448Py_EndInterpreter(PyThreadState *tstate)
1449{
1450 PyInterpreterState *interp = tstate->interp;
1451
1452 if (tstate != PyThreadState_GET())
1453 Py_FatalError("Py_EndInterpreter: thread is not current");
1454 if (tstate->frame != NULL)
1455 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1456
1457 wait_for_thread_shutdown();
1458
1459 if (tstate != interp->tstate_head || tstate->next != NULL)
1460 Py_FatalError("Py_EndInterpreter: not the last thread");
1461
1462 PyImport_Cleanup();
1463 PyInterpreterState_Clear(interp);
1464 PyThreadState_Swap(NULL);
1465 PyInterpreterState_Delete(interp);
1466}
1467
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001468/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001469
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001470static _PyInitError
1471add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001472{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001473 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001474 m = PyImport_AddModule("__main__");
1475 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001476 return _Py_INIT_ERR("can't create __main__ module");
1477
Nick Coghland6009512014-11-20 21:39:37 +10001478 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001479 ann_dict = PyDict_New();
1480 if ((ann_dict == NULL) ||
1481 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001482 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001483 }
1484 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001485
Nick Coghland6009512014-11-20 21:39:37 +10001486 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1487 PyObject *bimod = PyImport_ImportModule("builtins");
1488 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001489 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001490 }
1491 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001492 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001493 }
1494 Py_DECREF(bimod);
1495 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001496
Nick Coghland6009512014-11-20 21:39:37 +10001497 /* Main is a little special - imp.is_builtin("__main__") will return
1498 * False, but BuiltinImporter is still the most appropriate initial
1499 * setting for its __loader__ attribute. A more suitable value will
1500 * be set if __main__ gets further initialized later in the startup
1501 * process.
1502 */
1503 loader = PyDict_GetItemString(d, "__loader__");
1504 if (loader == NULL || loader == Py_None) {
1505 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1506 "BuiltinImporter");
1507 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001508 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001509 }
1510 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001511 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001512 }
1513 Py_DECREF(loader);
1514 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001516}
1517
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001519initfsencoding(PyInterpreterState *interp)
1520{
1521 PyObject *codec;
1522
Steve Dowercc16be82016-09-08 10:35:16 -07001523#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001525 Py_FileSystemDefaultEncoding = "mbcs";
1526 Py_FileSystemDefaultEncodeErrors = "replace";
1527 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001528 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001529 Py_FileSystemDefaultEncoding = "utf-8";
1530 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1531 }
1532#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001533 if (Py_FileSystemDefaultEncoding == NULL &&
1534 interp->core_config.utf8_mode)
1535 {
1536 Py_FileSystemDefaultEncoding = "utf-8";
1537 Py_HasFileSystemDefaultEncoding = 1;
1538 }
1539 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001540 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541 if (Py_FileSystemDefaultEncoding == NULL) {
1542 return _Py_INIT_ERR("Unable to get the locale encoding");
1543 }
Nick Coghland6009512014-11-20 21:39:37 +10001544
1545 Py_HasFileSystemDefaultEncoding = 0;
1546 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001547 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001548 }
Steve Dowercc16be82016-09-08 10:35:16 -07001549#endif
Nick Coghland6009512014-11-20 21:39:37 +10001550
1551 /* the encoding is mbcs, utf-8 or ascii */
1552 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1553 if (!codec) {
1554 /* Such error can only occurs in critical situations: no more
1555 * memory, import a module of the standard library failed,
1556 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001557 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001558 }
1559 Py_DECREF(codec);
1560 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001562}
1563
1564/* Import the site module (not into __main__ though) */
1565
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001567initsite(void)
1568{
1569 PyObject *m;
1570 m = PyImport_ImportModule("site");
1571 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001572 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001573 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 Py_DECREF(m);
1575 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001576}
1577
Victor Stinner874dbe82015-09-04 17:29:57 +02001578/* Check if a file descriptor is valid or not.
1579 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1580static int
1581is_valid_fd(int fd)
1582{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001583#ifdef __APPLE__
1584 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1585 and the other side of the pipe is closed, dup(1) succeed, whereas
1586 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1587 such error. */
1588 struct stat st;
1589 return (fstat(fd, &st) == 0);
1590#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001591 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001592 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001593 return 0;
1594 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001595 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1596 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1597 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001598 fd2 = dup(fd);
1599 if (fd2 >= 0)
1600 close(fd2);
1601 _Py_END_SUPPRESS_IPH
1602 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001603#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001604}
1605
1606/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001607static PyObject*
1608create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001609 int fd, int write_mode, const char* name,
1610 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001611{
1612 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1613 const char* mode;
1614 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001615 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001616 int buffering, isatty;
1617 _Py_IDENTIFIER(open);
1618 _Py_IDENTIFIER(isatty);
1619 _Py_IDENTIFIER(TextIOWrapper);
1620 _Py_IDENTIFIER(mode);
1621
Victor Stinner874dbe82015-09-04 17:29:57 +02001622 if (!is_valid_fd(fd))
1623 Py_RETURN_NONE;
1624
Nick Coghland6009512014-11-20 21:39:37 +10001625 /* stdin is always opened in buffered mode, first because it shouldn't
1626 make a difference in common use cases, second because TextIOWrapper
1627 depends on the presence of a read1() method which only exists on
1628 buffered streams.
1629 */
1630 if (Py_UnbufferedStdioFlag && write_mode)
1631 buffering = 0;
1632 else
1633 buffering = -1;
1634 if (write_mode)
1635 mode = "wb";
1636 else
1637 mode = "rb";
1638 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1639 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001640 Py_None, Py_None, /* encoding, errors */
1641 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001642 if (buf == NULL)
1643 goto error;
1644
1645 if (buffering) {
1646 _Py_IDENTIFIER(raw);
1647 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1648 if (raw == NULL)
1649 goto error;
1650 }
1651 else {
1652 raw = buf;
1653 Py_INCREF(raw);
1654 }
1655
Steve Dower39294992016-08-30 21:22:36 -07001656#ifdef MS_WINDOWS
1657 /* Windows console IO is always UTF-8 encoded */
1658 if (PyWindowsConsoleIO_Check(raw))
1659 encoding = "utf-8";
1660#endif
1661
Nick Coghland6009512014-11-20 21:39:37 +10001662 text = PyUnicode_FromString(name);
1663 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1664 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001665 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001666 if (res == NULL)
1667 goto error;
1668 isatty = PyObject_IsTrue(res);
1669 Py_DECREF(res);
1670 if (isatty == -1)
1671 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001672 if (Py_UnbufferedStdioFlag)
1673 write_through = Py_True;
1674 else
1675 write_through = Py_False;
1676 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001677 line_buffering = Py_True;
1678 else
1679 line_buffering = Py_False;
1680
1681 Py_CLEAR(raw);
1682 Py_CLEAR(text);
1683
1684#ifdef MS_WINDOWS
1685 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1686 newlines to "\n".
1687 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1688 newline = NULL;
1689#else
1690 /* sys.stdin: split lines at "\n".
1691 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1692 newline = "\n";
1693#endif
1694
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001695 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001696 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001697 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001698 Py_CLEAR(buf);
1699 if (stream == NULL)
1700 goto error;
1701
1702 if (write_mode)
1703 mode = "w";
1704 else
1705 mode = "r";
1706 text = PyUnicode_FromString(mode);
1707 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1708 goto error;
1709 Py_CLEAR(text);
1710 return stream;
1711
1712error:
1713 Py_XDECREF(buf);
1714 Py_XDECREF(stream);
1715 Py_XDECREF(text);
1716 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001717
Victor Stinner874dbe82015-09-04 17:29:57 +02001718 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1719 /* Issue #24891: the file descriptor was closed after the first
1720 is_valid_fd() check was called. Ignore the OSError and set the
1721 stream to None. */
1722 PyErr_Clear();
1723 Py_RETURN_NONE;
1724 }
1725 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001726}
1727
1728/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001729static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001730init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001731{
1732 PyObject *iomod = NULL, *wrapper;
1733 PyObject *bimod = NULL;
1734 PyObject *m;
1735 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001736 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001737 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001738 char *pythonioencoding = NULL;
1739 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001740 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001741
1742 /* Hack to avoid a nasty recursion issue when Python is invoked
1743 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1744 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1745 goto error;
1746 }
1747 Py_DECREF(m);
1748
1749 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1750 goto error;
1751 }
1752 Py_DECREF(m);
1753
1754 if (!(bimod = PyImport_ImportModule("builtins"))) {
1755 goto error;
1756 }
1757
1758 if (!(iomod = PyImport_ImportModule("io"))) {
1759 goto error;
1760 }
1761 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1762 goto error;
1763 }
1764
1765 /* Set builtins.open */
1766 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1767 Py_DECREF(wrapper);
1768 goto error;
1769 }
1770 Py_DECREF(wrapper);
1771
1772 encoding = _Py_StandardStreamEncoding;
1773 errors = _Py_StandardStreamErrors;
1774 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001775 char *opt = Py_GETENV("PYTHONIOENCODING");
1776 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001777 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001778 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001779 if (pythonioencoding == NULL) {
1780 PyErr_NoMemory();
1781 goto error;
1782 }
1783 err = strchr(pythonioencoding, ':');
1784 if (err) {
1785 *err = '\0';
1786 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001787 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001788 errors = err;
1789 }
1790 }
1791 if (*pythonioencoding && !encoding) {
1792 encoding = pythonioencoding;
1793 }
1794 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001795 else if (interp->core_config.utf8_mode) {
1796 encoding = "utf-8";
1797 errors = "surrogateescape";
1798 }
1799
1800 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001801 /* Choose the default error handler based on the current locale */
1802 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001803 }
Nick Coghland6009512014-11-20 21:39:37 +10001804 }
1805
1806 /* Set sys.stdin */
1807 fd = fileno(stdin);
1808 /* Under some conditions stdin, stdout and stderr may not be connected
1809 * and fileno() may point to an invalid file descriptor. For example
1810 * GUI apps don't have valid standard streams by default.
1811 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001812 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1813 if (std == NULL)
1814 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001815 PySys_SetObject("__stdin__", std);
1816 _PySys_SetObjectId(&PyId_stdin, std);
1817 Py_DECREF(std);
1818
1819 /* Set sys.stdout */
1820 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001821 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1822 if (std == NULL)
1823 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001824 PySys_SetObject("__stdout__", std);
1825 _PySys_SetObjectId(&PyId_stdout, std);
1826 Py_DECREF(std);
1827
1828#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1829 /* Set sys.stderr, replaces the preliminary stderr */
1830 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001831 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1832 if (std == NULL)
1833 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001834
1835 /* Same as hack above, pre-import stderr's codec to avoid recursion
1836 when import.c tries to write to stderr in verbose mode. */
1837 encoding_attr = PyObject_GetAttrString(std, "encoding");
1838 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001839 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001840 if (std_encoding != NULL) {
1841 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1842 Py_XDECREF(codec_info);
1843 }
1844 Py_DECREF(encoding_attr);
1845 }
1846 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1847
1848 if (PySys_SetObject("__stderr__", std) < 0) {
1849 Py_DECREF(std);
1850 goto error;
1851 }
1852 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1853 Py_DECREF(std);
1854 goto error;
1855 }
1856 Py_DECREF(std);
1857#endif
1858
Victor Stinnera7368ac2017-11-15 18:11:45 -08001859 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001860
Victor Stinnera7368ac2017-11-15 18:11:45 -08001861error:
1862 res = _Py_INIT_ERR("can't initialize sys standard streams");
1863
1864done:
Nick Coghland6009512014-11-20 21:39:37 +10001865 /* We won't need them anymore. */
1866 if (_Py_StandardStreamEncoding) {
1867 PyMem_RawFree(_Py_StandardStreamEncoding);
1868 _Py_StandardStreamEncoding = NULL;
1869 }
1870 if (_Py_StandardStreamErrors) {
1871 PyMem_RawFree(_Py_StandardStreamErrors);
1872 _Py_StandardStreamErrors = NULL;
1873 }
1874 PyMem_Free(pythonioencoding);
1875 Py_XDECREF(bimod);
1876 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001877 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001878}
1879
1880
Victor Stinner10dc4842015-03-24 12:01:30 +01001881static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001882_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001883{
Victor Stinner10dc4842015-03-24 12:01:30 +01001884 fputc('\n', stderr);
1885 fflush(stderr);
1886
1887 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001888 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001889}
Victor Stinner791da1c2016-03-14 16:53:12 +01001890
1891/* Print the current exception (if an exception is set) with its traceback,
1892 or display the current Python stack.
1893
1894 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1895 called on catastrophic cases.
1896
1897 Return 1 if the traceback was displayed, 0 otherwise. */
1898
1899static int
1900_Py_FatalError_PrintExc(int fd)
1901{
1902 PyObject *ferr, *res;
1903 PyObject *exception, *v, *tb;
1904 int has_tb;
1905
1906 if (PyThreadState_GET() == NULL) {
1907 /* The GIL is released: trying to acquire it is likely to deadlock,
1908 just give up. */
1909 return 0;
1910 }
1911
1912 PyErr_Fetch(&exception, &v, &tb);
1913 if (exception == NULL) {
1914 /* No current exception */
1915 return 0;
1916 }
1917
1918 ferr = _PySys_GetObjectId(&PyId_stderr);
1919 if (ferr == NULL || ferr == Py_None) {
1920 /* sys.stderr is not set yet or set to None,
1921 no need to try to display the exception */
1922 return 0;
1923 }
1924
1925 PyErr_NormalizeException(&exception, &v, &tb);
1926 if (tb == NULL) {
1927 tb = Py_None;
1928 Py_INCREF(tb);
1929 }
1930 PyException_SetTraceback(v, tb);
1931 if (exception == NULL) {
1932 /* PyErr_NormalizeException() failed */
1933 return 0;
1934 }
1935
1936 has_tb = (tb != Py_None);
1937 PyErr_Display(exception, v, tb);
1938 Py_XDECREF(exception);
1939 Py_XDECREF(v);
1940 Py_XDECREF(tb);
1941
1942 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001943 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001944 if (res == NULL)
1945 PyErr_Clear();
1946 else
1947 Py_DECREF(res);
1948
1949 return has_tb;
1950}
1951
Nick Coghland6009512014-11-20 21:39:37 +10001952/* Print fatal error message and abort */
1953
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001954#ifdef MS_WINDOWS
1955static void
1956fatal_output_debug(const char *msg)
1957{
1958 /* buffer of 256 bytes allocated on the stack */
1959 WCHAR buffer[256 / sizeof(WCHAR)];
1960 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1961 size_t msglen;
1962
1963 OutputDebugStringW(L"Fatal Python error: ");
1964
1965 msglen = strlen(msg);
1966 while (msglen) {
1967 size_t i;
1968
1969 if (buflen > msglen) {
1970 buflen = msglen;
1971 }
1972
1973 /* Convert the message to wchar_t. This uses a simple one-to-one
1974 conversion, assuming that the this error message actually uses
1975 ASCII only. If this ceases to be true, we will have to convert. */
1976 for (i=0; i < buflen; ++i) {
1977 buffer[i] = msg[i];
1978 }
1979 buffer[i] = L'\0';
1980 OutputDebugStringW(buffer);
1981
1982 msg += buflen;
1983 msglen -= buflen;
1984 }
1985 OutputDebugStringW(L"\n");
1986}
1987#endif
1988
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001989static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001990fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001991{
1992 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001993 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001994
1995 if (reentrant) {
1996 /* Py_FatalError() caused a second fatal error.
1997 Example: flush_std_files() raises a recursion error. */
1998 goto exit;
1999 }
2000 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002001
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002002 fprintf(stderr, "Fatal Python error: ");
2003 if (prefix) {
2004 fputs(prefix, stderr);
2005 fputs(": ", stderr);
2006 }
2007 if (msg) {
2008 fputs(msg, stderr);
2009 }
2010 else {
2011 fprintf(stderr, "<message not set>");
2012 }
2013 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002014 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002015
Victor Stinnere0deff32015-03-24 13:46:18 +01002016 /* Print the exception (if an exception is set) with its traceback,
2017 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002018 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002019 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002020 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002021
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002022 /* The main purpose of faulthandler is to display the traceback.
2023 This function already did its best to display a traceback.
2024 Disable faulthandler to prevent writing a second traceback
2025 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002026 _PyFaulthandler_Fini();
2027
Victor Stinner791da1c2016-03-14 16:53:12 +01002028 /* Check if the current Python thread hold the GIL */
2029 if (PyThreadState_GET() != NULL) {
2030 /* Flush sys.stdout and sys.stderr */
2031 flush_std_files();
2032 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002033
Nick Coghland6009512014-11-20 21:39:37 +10002034#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002035 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002036#endif /* MS_WINDOWS */
2037
2038exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002039 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002040#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002041 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002042#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002043 abort();
2044 }
2045 else {
2046 exit(status);
2047 }
2048}
2049
2050void
2051Py_FatalError(const char *msg)
2052{
2053 fatal_error(NULL, msg, -1);
2054}
2055
2056void
2057_Py_FatalInitError(_PyInitError err)
2058{
2059 /* On "user" error: exit with status 1.
2060 For all other errors, call abort(). */
2061 int status = err.user_err ? 1 : -1;
2062 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002063}
2064
2065/* Clean up and exit */
2066
Victor Stinnerd7292b52016-06-17 12:29:00 +02002067# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002068
Nick Coghland6009512014-11-20 21:39:37 +10002069/* For the atexit module. */
2070void _Py_PyAtExit(void (*func)(void))
2071{
Antoine Pitroufc5db952017-12-13 02:29:07 +01002072 /* Guard against API misuse (see bpo-17852) */
2073 assert(_PyRuntime.pyexitfunc == NULL || _PyRuntime.pyexitfunc == func);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002074 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002075}
2076
2077static void
2078call_py_exitfuncs(void)
2079{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002080 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002081 return;
2082
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002083 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002084 PyErr_Clear();
2085}
2086
2087/* Wait until threading._shutdown completes, provided
2088 the threading module was imported in the first place.
2089 The shutdown routine will wait until all non-daemon
2090 "threading" threads have completed. */
2091static void
2092wait_for_thread_shutdown(void)
2093{
Nick Coghland6009512014-11-20 21:39:37 +10002094 _Py_IDENTIFIER(_shutdown);
2095 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002096 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002097 if (threading == NULL) {
2098 /* threading not imported */
2099 PyErr_Clear();
2100 return;
2101 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002102 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002103 if (result == NULL) {
2104 PyErr_WriteUnraisable(threading);
2105 }
2106 else {
2107 Py_DECREF(result);
2108 }
2109 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002110}
2111
2112#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002113int Py_AtExit(void (*func)(void))
2114{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002115 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002116 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002117 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002118 return 0;
2119}
2120
2121static void
2122call_ll_exitfuncs(void)
2123{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002124 while (_PyRuntime.nexitfuncs > 0)
2125 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002126
2127 fflush(stdout);
2128 fflush(stderr);
2129}
2130
2131void
2132Py_Exit(int sts)
2133{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002134 if (Py_FinalizeEx() < 0) {
2135 sts = 120;
2136 }
Nick Coghland6009512014-11-20 21:39:37 +10002137
2138 exit(sts);
2139}
2140
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002141static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002142initsigs(void)
2143{
2144#ifdef SIGPIPE
2145 PyOS_setsig(SIGPIPE, SIG_IGN);
2146#endif
2147#ifdef SIGXFZ
2148 PyOS_setsig(SIGXFZ, SIG_IGN);
2149#endif
2150#ifdef SIGXFSZ
2151 PyOS_setsig(SIGXFSZ, SIG_IGN);
2152#endif
2153 PyOS_InitInterrupts(); /* May imply initsignal() */
2154 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002155 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002156 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002157 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002158}
2159
2160
2161/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2162 *
2163 * All of the code in this function must only use async-signal-safe functions,
2164 * listed at `man 7 signal` or
2165 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2166 */
2167void
2168_Py_RestoreSignals(void)
2169{
2170#ifdef SIGPIPE
2171 PyOS_setsig(SIGPIPE, SIG_DFL);
2172#endif
2173#ifdef SIGXFZ
2174 PyOS_setsig(SIGXFZ, SIG_DFL);
2175#endif
2176#ifdef SIGXFSZ
2177 PyOS_setsig(SIGXFSZ, SIG_DFL);
2178#endif
2179}
2180
2181
2182/*
2183 * The file descriptor fd is considered ``interactive'' if either
2184 * a) isatty(fd) is TRUE, or
2185 * b) the -i flag was given, and the filename associated with
2186 * the descriptor is NULL or "<stdin>" or "???".
2187 */
2188int
2189Py_FdIsInteractive(FILE *fp, const char *filename)
2190{
2191 if (isatty((int)fileno(fp)))
2192 return 1;
2193 if (!Py_InteractiveFlag)
2194 return 0;
2195 return (filename == NULL) ||
2196 (strcmp(filename, "<stdin>") == 0) ||
2197 (strcmp(filename, "???") == 0);
2198}
2199
2200
Nick Coghland6009512014-11-20 21:39:37 +10002201/* Wrappers around sigaction() or signal(). */
2202
2203PyOS_sighandler_t
2204PyOS_getsig(int sig)
2205{
2206#ifdef HAVE_SIGACTION
2207 struct sigaction context;
2208 if (sigaction(sig, NULL, &context) == -1)
2209 return SIG_ERR;
2210 return context.sa_handler;
2211#else
2212 PyOS_sighandler_t handler;
2213/* Special signal handling for the secure CRT in Visual Studio 2005 */
2214#if defined(_MSC_VER) && _MSC_VER >= 1400
2215 switch (sig) {
2216 /* Only these signals are valid */
2217 case SIGINT:
2218 case SIGILL:
2219 case SIGFPE:
2220 case SIGSEGV:
2221 case SIGTERM:
2222 case SIGBREAK:
2223 case SIGABRT:
2224 break;
2225 /* Don't call signal() with other values or it will assert */
2226 default:
2227 return SIG_ERR;
2228 }
2229#endif /* _MSC_VER && _MSC_VER >= 1400 */
2230 handler = signal(sig, SIG_IGN);
2231 if (handler != SIG_ERR)
2232 signal(sig, handler);
2233 return handler;
2234#endif
2235}
2236
2237/*
2238 * All of the code in this function must only use async-signal-safe functions,
2239 * listed at `man 7 signal` or
2240 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2241 */
2242PyOS_sighandler_t
2243PyOS_setsig(int sig, PyOS_sighandler_t handler)
2244{
2245#ifdef HAVE_SIGACTION
2246 /* Some code in Modules/signalmodule.c depends on sigaction() being
2247 * used here if HAVE_SIGACTION is defined. Fix that if this code
2248 * changes to invalidate that assumption.
2249 */
2250 struct sigaction context, ocontext;
2251 context.sa_handler = handler;
2252 sigemptyset(&context.sa_mask);
2253 context.sa_flags = 0;
2254 if (sigaction(sig, &context, &ocontext) == -1)
2255 return SIG_ERR;
2256 return ocontext.sa_handler;
2257#else
2258 PyOS_sighandler_t oldhandler;
2259 oldhandler = signal(sig, handler);
2260#ifdef HAVE_SIGINTERRUPT
2261 siginterrupt(sig, 1);
2262#endif
2263 return oldhandler;
2264#endif
2265}
2266
2267#ifdef __cplusplus
2268}
2269#endif